agent

package
v0.17.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2026 License: AGPL-3.0 Imports: 84 Imported by: 0

Documentation

Overview

Package agent coordinates the server's per-chat runtime: SSE fan-out, the one agent engine and the ACP sessions on it, POST /api/command dispatch, the workspace services (engine calls and observer passes), agent terminals, the browser shell shim, and the MCP runtime registry.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RunHolders added in v0.17.0

func RunHolders(parents []string, l *runlease.Lease, owners chat.SessionOwners) (holders []marotte.ChatID, known bool)

RunHolders names the chats a run's keep fact goes to: every chat whose session chain holds one of the run's parent sessions (the test the purge teardown deletes runs by), plus the holders its lease already records. known is false when nothing names a launcher and the run could be a chat's: no valid parent session, and a lease that is absent or of OriginAgent with no holder.

Types

type EngineSource added in v0.15.0

type EngineSource interface {
	// CLIPath is the kiro-cli binary the engine runs `acp` on, "" while none is available.
	CLIPath() string
	// Installed closes once a managed install is active; nil means an unmanaged runtime that starts at once.
	Installed() <-chan struct{}
	// Env is appended to the engine's environment, so the active install directory leads PATH.
	Env() []string
	// EnvAllow re-permits credential-shaped names the engine's inherit screen would drop.
	EnvAllow() map[string]struct{}
}

EngineSource is where the agent engine's binary and environment come from, as the composition root resolves them.

type Option

type Option func(*Runtime)

Option configures optional Runtime parameters.

func WithACPArgs

func WithACPArgs(args []string) Option

WithACPArgs sets the operator kiro-cli flags appended to the agent engine's argv, pre-filtered by bridge.ParseACPArgs.

func WithAPIKey added in v0.15.0

func WithAPIKey(active bool) Option

WithAPIKey records that an API key reaches the agent engine: a sign-in or a switch then marks no restart pending and reloads no session, and the stored account applies again on an engine started without the key.

func WithAuthReadiness

func WithAuthReadiness(readiness *command.AuthReadiness) Option

WithAuthReadiness wires command-layer sign-in outcomes to readiness.

func WithConfigDir

func WithConfigDir(dir string) Option

WithConfigDir sets the configuration directory for permissions, checkpoints, and ignore rules.

func WithDebugLogs added in v0.12.16

func WithDebugLogs(current func() bool, set func(on bool)) Option

WithDebugLogs wires the process log level a debug_logs change moves: current reports it (logctl.Debug), set moves it (logctl.SetDebug).

func WithGovernanceLocksHook added in v0.12.0

func WithGovernanceLocksHook(fn func(context.Context)) Option

WithGovernanceLocksHook wires a callback for when the governance lock map moves, for locks living outside the runtime; it reads the locks itself (Settings.GovernanceLocks).

func WithKASMCPRenderer added in v0.12.16

func WithKASMCPRenderer(r kasMCPRenderer) Option

WithKASMCPRenderer wires the re-render that carries the MCP wait setting to open chats.

func WithMCPConfig

func WithMCPConfig(c mcpNameSets) Option

WithMCPConfig wires the MCP config store, whose name sets attribute statuses and gate live control.

func WithPowers added in v0.12.0

func WithPowers(b powersBackend) Option

WithPowers wires the Powers backend. Unset, the Powers routes answer 503.

func WithPresence

func WithPresence(p presenceTable) Option

WithPresence wires the push presence table; absent, every push is sent (fail-open).

func WithPush

func WithPush(p pushService) Option

WithPush wires the push notification service at construction time.

func WithRunLeases

func WithRunLeases(st *runlease.Store) Option

WithRunLeases wires the durable run-lease store. Absent falls back to memory (a lease carries the run's clock); this adds restart survival.

func WithSchedules

func WithSchedules(st *schedule.Store) Option

WithSchedules wires the schedule store; absent, the schedule routes are not registered.

func WithSessionReaper

func WithSessionReaper(r *kirosession.Reaper, refs func(context.Context) (map[string]struct{}, bool)) Option

WithSessionReaper wires the KAS session reaper and the referenced-session thunk. refs returns (set, complete); an incomplete set skips the sweep (sweepSessionsOnce).

func WithSessionSweepGate

func WithSessionSweepGate(gate <-chan struct{}) Option

WithSessionSweepGate holds the periodic orphan-session sweep until gate closes, once the listener bound: the cheapest ownership evidence, since the reaper's root is $KIRO_HOME.

func WithSignIn added in v0.15.0

func WithSignIn(v *signin.Vault, backend signin.BackendID) Option

WithSignIn wires the sign-in vault and the backend the agent engine runs.

func WithSpecApprovals

func WithSpecApprovals(st *specapproval.Store) Option

WithSpecApprovals wires the spec-phase approval record; absent, approve_spec_phase is unavailable.

func WithTabs

func WithTabs(st *tabs.Store) Option

WithTabs wires the open-tab set, enabling the tab commands, tabs_changed and retention's predicate. Absent, tab commands answer unavailable.

func WithVersions

func WithVersions(v *subject.Versions) Option

WithVersions wires the shared subject registry; absent, the runtime mints into a private one.

type RouteRegistrar

type RouteRegistrar interface {
	RegisterRoutes(mux *http.ServeMux)
}

RouteRegistrar mounts its own routes under a sub-tree of /api/*.

type RunPurgeResult added in v0.12.0

type RunPurgeResult struct {
	NextDeadline time.Time
	Purged       int
	Kept         int
	Errors       int
}

RunPurgeResult reports one retention side pass over runs or run logs; NextDeadline is when the earliest keep that lapses by itself (a run's age, a retry in flight) lapses, or the next pass's turn for work it deferred, zero for none.

type RunRetention added in v0.17.0

type RunRetention struct {
	Window   time.Duration
	Enabled  bool // false under Keep forever and for a present but unreadable config.json
	ChatRuns bool // a living chat's finished runs age out too; only with a positive Window
}

RunRetention is how the retention side passes treat runs and run logs, read from chat_retention_days.

type RunRow added in v0.17.0

type RunRow struct {
	WorkflowID      string
	ParentSessionID string
	Terminal        bool
}

RunRow is one run as the keep-state reconcile reads it from KAS.

type Runs

type Runs struct {
	// contains filtered or unexported fields
}

Runs owns the workflow-run surface: launch, cancel, retry, the durable lease, the deadline and turn-cap arms, and the schedule store. It holds collaborators, not a *Runtime; `mu` guards bounds.

func (*Runs) BootSweep added in v0.15.0

func (rs *Runs) BootSweep(ctx context.Context) (reached bool)

BootSweep is the boot pass: the finder of the sign-in gate's pauses, which retries on its own, the orphan sweep, then one read of every leased run's asks. Reports whether the sweep reached KAS; when it did not, nothing was read. Its loop outlives Shutdown, so the pass is held on inflight and none runs once draining.

func (*Runs) CancelRun

func (rs *Runs) CancelRun(ctx context.Context, workflowID string) error

CancelRun cancels one run for the reader and waits for its lease release. command.ErrRunStillLive when the wait runs out; the cancel landed either way.

func (*Runs) ForgetRunNotices added in v0.15.0

func (rs *Runs) ForgetRunNotices(chatID marotte.ChatID, n int)

ForgetRunNotices drops n of the chat's notices for a clear naming that many: it carries no words to join them by, and a kept notice would hold clearStaleNotices open. Ambiguous notices go first, since no read can name their run anyway, then the oldest.

func (*Runs) InspectRunRow added in v0.17.0

func (rs *Runs) InspectRunRow(ctx context.Context, workflowID string) (RunRow, error)

InspectRunRow reads one run by inspect. "Workflow not found", a failed call and a reply that does not name the run are all errors: none of them shows the run's status or its launcher.

func (*Runs) IsScheduled

func (rs *Runs) IsScheduled(workflowID string) bool

IsScheduled reports whether a schedule launched the run, from its lease, granted before the first lifecycle frame.

func (*Runs) LaunchScheduled

func (rs *Runs) LaunchScheduled(
	ctx context.Context, source string, row schedule.Row, defaults marotte.RunDefaults, slotAt time.Time,
) (id, name string, err error)

LaunchScheduled launches an unattended run for a schedule. slotAt is its next slot; zero leaves the idle window and backstop. The sign-in gate's refusal wraps schedule.ErrNoRunCanStart; an engine that did not answer before the run was created wraps schedule.ErrEngineBusy.

func (*Runs) LeaseChat added in v0.16.0

func (rs *Runs) LeaseChat(workflowID string) (marotte.ChatID, bool)

LeaseChat is the chat workflowID's lease names, false when no lease is held.

func (*Runs) LiveRuns

func (rs *Runs) LiveRuns(workflowIDs []string) []command.LiveRunRef

LiveRuns filters workflowIDs to those still leased, labelled by display name, satisfying command.runCutter.

func (*Runs) ReadRun added in v0.16.0

func (rs *Runs) ReadRun(workflowID string, done func())

ReadRun reads workflowID's state once in the background; rawInspect hands the reply to the translator, and done runs after the read, or at once when no read starts.

func (*Runs) RecordLeaseHolders added in v0.17.0

func (rs *Runs) RecordLeaseHolders(ctx context.Context, workflowID string, holders []marotte.ChatID)

RecordLeaseHolders adds holders to a held lease's KeepChats, a union; a lease released meanwhile is left alone. The unattributed mark stays for reattributeRuns, which holds the facts on every chat before it clears the mark.

func (*Runs) RecordedRuns added in v0.17.0

func (rs *Runs) RecordedRuns(context.Context) ([]string, error)

RecordedRuns answers every workflow id with a run record under runs/, the fill-in's candidates beside the leases and the run list. No run log answers none.

func (*Runs) RunAppendAfterClosed

func (rs *Runs) RunAppendAfterClosed(ctx context.Context, runID, nodePath string, e *marotte.Entry) error

RunAppendAfterClosed files an entry after the path's newest closed turn and announces it; no closed turn is an error.

func (*Runs) RunFoldTarget

func (rs *Runs) RunFoldTarget(ctx context.Context, step *translate.RunStep, chatID marotte.ChatID) (*turnlog.Turn, bool)

RunFoldTarget answers the step path's open turn, opening one when the path has neither an open nor a closed turn.

func (*Runs) RunLabel added in v0.12.0

func (rs *Runs) RunLabel(workflowID string) string

RunLabel is the label the launch sent KAS, rebuilt from the lease; run_start carries none of its own.

func (*Runs) RunMadeProgress

func (rs *Runs) RunMadeProgress(workflowID string)

RunMadeProgress rolls a run's idle window forward and, at most once per chat.RunMarkRefresh, its keep marks. Satisfies translate.runBoundsAccess. Called per tool-call frame, so the pre-checks keep it two map reads.

func (*Runs) RunMeter

func (rs *Runs) RunMeter(runID, nodePath string, credits, elapsedMs float64) bool

RunMeter folds a step's turn_completion into its open turn's aggregate.

func (*Runs) RunNodeComplete

func (rs *Runs) RunNodeComplete(ctx context.Context, runID string, path []string, status, reason string)

RunNodeComplete closes the step path's turn with KAS's status and announces what the close sealed.

func (*Runs) RunNodePaused added in v0.13.0

func (rs *Runs) RunNodePaused(ctx context.Context, runID string, path []string)

RunNodePaused ends the paused step's steering turn: the execution that read its buffer has stopped.

func (*Runs) RunNodeStart

func (rs *Runs) RunNodeStart(ctx context.Context, step *translate.RunStep, chatID marotte.ChatID)

RunNodeStart opens the step path's turn and announces its turn_open under the run scope; a path already open appends nothing.

func (*Runs) RunNotice

func (rs *Runs) RunNotice(chatID marotte.ChatID, text string) (workflowID string, producedTs int64, ok bool)

RunNotice consumes the chat's notice whose label the read notice's text quotes: KAS mints the notice id at random, so the words are the only join. A text no label matches names no run. One several notices match (two launches of one workflow) names none either, since any pick could stamp another run's provenance: it consumes the first and marks the rest ambiguous, each still owed its own read or clear. translate.runOriginAccess.

func (*Runs) RunOwner added in v0.17.0

func (rs *Runs) RunOwner(ctx context.Context, workflowID string) (command.RunOwner, error)

RunOwner answers a run's owners by RunHolders (command.runOwner). A leased run answers from its lease and the chats; an unleased one from KAS's inventory row, or its inspect reply when the inventory omits it, and the chats. RunUnknown when no lease, row or reply names the run: the list leaves out a run whose state it could not read, so an omission is not parentless. The error is an unreadable inventory, an owner scan that could not read every chat and found no holder, or a run that names no launcher.

func (*Runs) RunPlanUpdate added in v0.13.0

func (rs *Runs) RunPlanUpdate(ctx context.Context, chatID marotte.ChatID, runID string, u marotte.RunPlanUpdate)

RunPlanUpdate records a queued revision, naming the top-level step it replaces the plan after, or settles the queued one. A rejection also reaches the launching chat.

func (*Runs) RunReadBound added in v0.15.0

func (rs *Runs) RunReadBound(ctx context.Context, workflowID string) (uint64, error)

RunReadBound is the run's read position now, read as GET /api/runs/{id} reads it: the clamp for an acknowledgement (command.runOwner). It errors when the run's state or log cannot be read.

func (*Runs) RunRows added in v0.17.0

func (rs *Runs) RunRows(ctx context.Context) ([]RunRow, error)

RunRows lists KAS's runs for this workspace with their launching session and whether each is terminal.

func (*Runs) RunSteer added in v0.13.0

func (rs *Runs) RunSteer(ctx context.Context, runID, nodePath, steerID string, steer *marotte.EntrySteer)

RunSteer files a step steer's entry in the path's open run turn, else after its newest closed turn.

func (*Runs) RunSteerCleared added in v0.15.0

func (rs *Runs) RunSteerCleared(ctx context.Context, runID, nodePath, clearID string, c *marotte.EntrySteerCleared) bool

RunSteerCleared files a step's steering clear under clearID in the path's open run turn, else after its newest closed turn, and reports whether it landed.

func (*Runs) RunSteerDelivered added in v0.13.0

func (rs *Runs) RunSteerDelivered(ctx context.Context, runID, nodePath string, d *marotte.EntrySteerDelivered) bool

RunSteerDelivered files a workflow message's take-up in the path's open run turn, else after its newest closed turn, and reports whether it landed.

func (*Runs) RunStopReason

func (rs *Runs) RunStopReason(runID, nodePath string, raw marotte.StopReason) bool

RunStopReason records a step's last turn_end stop reason on its open turn.

func (*Runs) RunUnsettledWorkflowMessages added in v0.15.0

func (rs *Runs) RunUnsettledWorkflowMessages(ctx context.Context, runID string) ([]marotte.WorkflowMessage, error)

RunUnsettledWorkflowMessages answers the run log's workflow messages nothing has settled, oldest first; none for a run with no log.

func (*Runs) RunsParentedBy added in v0.17.0

func (rs *Runs) RunsParentedBy(ctx context.Context, sessionID string) (live, all []string, err error)

RunsParentedBy answers the runs sessionID launched (command.runOwner): live holds every lease naming it as parent, every listed non-terminal row with that parent and every run recorded under runs/ that the keep-state reconcile attributed to it; all adds the listed terminal rows. Until the reconcile has read runs/ this boot, and on an unreadable inventory or lease file, it errors.

func (*Runs) SetRecordedRuns added in v0.17.0

func (rs *Runs) SetRecordedRuns(parents map[string]string)

SetRecordedRuns records the live runs the keep-state reconcile found only under runs/, workflow id to launching session, and marks runs/ read for RunsParentedBy.

type Runtime

type Runtime struct {
	// contains filtered or unexported fields
}

Runtime is the central coordinator.

func New

func New(ctx context.Context, workDir string, source EngineSource, chatStore chatRecords, opts ...Option) *Runtime

New constructs a Runtime over the agent engine source resolves; tool authorization is Cedar's. ctx is the required lifetime (nil panics in context.WithCancel); Shutdown cancels the runtime's own child. chatStore is required too. The engine starts once the runtime is built: at once for an unmanaged kiro-cli, when the managed install is active. A nil source never starts one.

func (*Runtime) AbandonInFlightTurn

func (rt *Runtime) AbandonInFlightTurn(ctx context.Context, chatID marotte.ChatID, turnID string, stop marotte.StopReason, reason string, kind marotte.FailureKind, seq uint64)

AbandonInFlightTurn finalizes a turn that failed before it could end.

func (*Runtime) AccountUsage

func (rt *Runtime) AccountUsage(ctx context.Context) (*marotte.AccountUsage, error)

AccountUsage fetches account usage with an engine call, so it works with no chat open. Uncached: the HTTP layer caches.

func (*Runtime) AdmissionHolderSource

func (rt *Runtime) AdmissionHolderSource(chatID marotte.ChatID) (marotte.TurnOpenSource, bool)

AdmissionHolderSource reports who holds the admission slot: the open turn, else the reservation.

func (*Runtime) ArmStopGrace added in v0.15.0

func (rt *Runtime) ArmStopGrace(stop *command.TurnStop, d time.Duration) bool

ArmStopGrace backstops the stop's captured targets with the grace budget d.

func (*Runtime) AwaitNoClose added in v0.17.0

func (rt *Runtime) AwaitNoClose(ctx context.Context, chatID marotte.ChatID) (bool, error)

AwaitNoClose waits until no close of chatID is held.

func (*Runtime) AwaitSessionLeases added in v0.17.0

func (rt *Runtime) AwaitSessionLeases(ctx context.Context, chatID marotte.ChatID)

AwaitSessionLeases waits until every lease on the chat's session admitted before its close committed has returned; the commit cut each, so the teardown's own cancel and release are the only session access after it.

func (*Runtime) AwaitTurn

func (rt *Runtime) AwaitTurn(ctx context.Context, chatID marotte.ChatID, turnID string) (marotte.TurnResult, error)

AwaitTurn blocks until the named turn has finalized and reports what it did.

func (*Runtime) AwaitTurnBound added in v0.13.0

func (rt *Runtime) AwaitTurnBound(ctx context.Context, chatID marotte.ChatID, turnID string) (bool, error)

AwaitTurnBound blocks until KAS binds the named turn's prompt or the turn finalizes unbound.

func (*Runtime) BeginChatTeardown added in v0.10.12

func (rt *Runtime) BeginChatTeardown(chatID marotte.ChatID, keep bool)

BeginChatTeardown is command.chatTeardown's first step, before its cancel, so that turn end resends nothing.

func (*Runtime) Broadcast

func (rt *Runtime) Broadcast(_ context.Context, evt marotte.ServerEvent)

Broadcast sends a ServerEvent to every SSE client: the app-facing door; in-package code uses h.bus.Broadcast.

func (*Runtime) CloseChatState

func (rt *Runtime) CloseChatState(ctx context.Context, chatID marotte.ChatID, stop *chat.Claim)

CloseChatState tears down in-memory state without touching the KAS session, so a reopen session/loads it, and stops the chat's runs under stop, a person's close's stop hold, when it is set (Runs.stopChatRuns).

func (*Runtime) CloseImpact added in v0.17.0

func (rt *Runtime) CloseImpact(ctx context.Context, chatIDs []marotte.ChatID) map[marotte.ChatID]command.CloseWork

CloseImpact reads what closing each chat stops, from in-memory and cached state only (command.closeImpactReader).

func (*Runtime) CloseNextSSEAfter

func (rt *Runtime) CloseNextSSEAfter(n int)

CloseNextSSEAfter arms the next SSE connection to be cut after its n-th data frame: the write of frame n+1 fails and the peer sees the stream close between frames. n <= 0 disarms.

func (*Runtime) Config

func (rt *Runtime) Config() *Settings

Config exposes the settings surface to the composition root as the server's policyProvider.

func (*Runtime) DeleteChatStateByChain

func (rt *Runtime) DeleteChatStateByChain(ctx context.Context, chatID marotte.ChatID, sessionChain []string, cause command.RunStopCause)

DeleteChatStateByChain deletes a chat's runs and KAS sessions from a captured chain. Order is the contract: runs before sessions (KAS refuses a session owning a live run), sessions before the bridge closes, Reap last.

func (*Runtime) DischargeWaiting

func (rt *Runtime) DischargeWaiting(ctx context.Context, chatID marotte.ChatID)

DischargeWaiting ends a chat's retained waiting_on_user claim and broadcasts the clear.

func (*Runtime) EndPromptCall added in v0.15.0

func (rt *Runtime) EndPromptCall(turn command.TurnRef)

EndPromptCall forgets the turn's call once it returned.

func (*Runtime) EngineReady added in v0.15.0

func (rt *Runtime) EngineReady() <-chan struct{}

EngineReady is closed once the first agent engine is ready; it never closes when none can start.

func (*Runtime) EnsureCustomProfile added in v0.12.9

func (rt *Runtime) EnsureCustomProfile(ctx context.Context) error

EnsureCustomProfile runs Customize unless the profile already is Custom, so a rule an answer saves lands in the policy the picker names. It returns once the user file is written, and leaves both files as they were on any refusal but securityprofile.ErrRestoreFailed.

func (*Runtime) Epoch

func (rt *Runtime) Epoch() string

Epoch is the hub's current epoch, stamped on every REST envelope so a client refuses a previous epoch's response.

func (*Runtime) HoldChat added in v0.17.0

func (rt *Runtime) HoldChat(chatID marotte.ChatID) command.ChatHold

HoldChat holds chatID's life gate for a close being decided (chatGates owns the contract).

func (*Runtime) HoldUnlessDraining added in v0.15.0

func (rt *Runtime) HoldUnlessDraining() (release func(), ok bool)

HoldUnlessDraining holds Shutdown's in-flight wait for a caller off the runtime's own goroutines (a background loop the app stops after Shutdown), until release; ok is false, and nothing is held, once Shutdown has begun.

func (*Runtime) KickCodeIntelligence added in v0.17.0

func (rt *Runtime) KickCodeIntelligence()

KickCodeIntelligence runs ensureCodeIntelligence behind the caller on the runtime's lifetime, which Shutdown cancels and waits for; once Shutdown has begun it starts nothing.

func (*Runtime) LifeStamp added in v0.17.0

func (rt *Runtime) LifeStamp() uint64

LifeStamp is the life gate's position now.

func (*Runtime) MCPRegistry

func (rt *Runtime) MCPRegistry() RouteRegistrar

MCPRegistry returns the MCP runtime registry as a RouteRegistrar.

func (*Runtime) MCPSnapshot

func (rt *Runtime) MCPSnapshot() []marotte.MCPSnapshotServer

MCPSnapshot returns a stable-ordered snapshot of connected MCP servers only.

func (*Runtime) Membership

func (rt *Runtime) Membership() *command.Membership

Membership returns the coordinator over the chat store and open-tab set, for retention.

func (*Runtime) Notify added in v0.13.0

func (rt *Runtime) Notify(ctx context.Context, n *marotte.NotificationPayload)

Notify shows n on the page and as a Web Push, as every notification in the app is shown.

func (*Runtime) OpenTurn

func (rt *Runtime) OpenTurn(ctx context.Context, chatID marotte.ChatID, open command.TurnOpen) (string, error)

OpenTurn appends the turn_open and creates the registry record together; an answering source discharges the waiting claim.

func (*Runtime) OpenTurns

func (rt *Runtime) OpenTurns(chatID marotte.ChatID) []chat.OpenTurnTail

OpenTurns returns the chat's open turns with their coalescing lane entries, for the GET (chat.WithOpenTurns).

func (*Runtime) PreSendCompact added in v0.12.0

func (rt *Runtime) PreSendCompact(ctx context.Context, chatID marotte.ChatID, sb command.Bridge)

PreSendCompact runs the compaction policy's before-a-send trigger.

func (*Runtime) PromptHolder added in v0.12.0

func (rt *Runtime) PromptHolder(chatID marotte.ChatID) (string, bool)

PromptHolder names the prompt-class turn holding the chat's admission.

func (*Runtime) PurgeFinishedRuns added in v0.17.0

func (rt *Runtime) PurgeFinishedRuns(ctx context.Context, p RunRetention) RunPurgeResult

PurgeFinishedRuns deletes, oldest first and at most one per runPurgePace, finished runs older than p.Window (from last update) with no retry in flight, judged on the list and again on a fresh read before the delete, whether or not a chat claims them; with p.ChatRuns false a claimed run is left to its chat. Shown, live or paused runs, unreadable ages, runs naming no valid launching session and runs whose launching chat is in teardown are kept, and nothing is deleted while the tab arrangement is unread or a chat file is.

func (*Runtime) ReattributeRuns added in v0.17.0

func (rt *Runtime) ReattributeRuns(ctx context.Context)

ReattributeRuns is Runs.reattributeRuns, a retention side pass.

func (*Runtime) ReconcileSessionSettings added in v0.12.9

func (rt *Runtime) ReconcileSessionSettings(ctx context.Context)

ReconcileSessionSettings marks resident sessions for reload when a setting they read only at their door moved since the last reconcile, recomputes whether an engine restart is pending, and pushes the engine each live setting it has not confirmed. Every writer calls it after its write lands, and it returns once each push landed or failed. A hand edit has no writer to call it: the next chat open syncs it.

func (*Runtime) RegisterRoutes

func (rt *Runtime) RegisterRoutes(mux *http.ServeMux)

RegisterRoutes wires /api/events (SSE), /api/command (POST) and /api/shell/ws (WebSocket PTY).

func (*Runtime) ReleaseStop added in v0.15.0

func (rt *Runtime) ReleaseStop(stop *command.TurnStop)

ReleaseStop lifts the stop's hold on the chat's sends.

func (*Runtime) ReleaseTurn

func (rt *Runtime) ReleaseTurn(chatID marotte.ChatID, turnID string)

ReleaseTurn gives up the completion handle OpenTurn issued.

func (*Runtime) ReleaseTurnReservation

func (rt *Runtime) ReleaseTurnReservation(res command.Reservation)

ReleaseTurnReservation frees the chat's admission slot and wakes waiters.

func (*Runtime) RenameSession added in v0.12.0

func (rt *Runtime) RenameSession(ctx context.Context, sessionID, title string) error

RenameSession renames a session, resident or not, with an engine call.

func (*Runtime) RequestStop added in v0.12.0

func (rt *Runtime) RequestStop(chatID marotte.ChatID, cause marotte.TurnStopCause) *command.TurnStop

RequestStop records a stop for cause and captures the turns it targets.

func (*Runtime) ReserveTurnForPrompt

func (rt *Runtime) ReserveTurnForPrompt(
	ctx context.Context, chatID marotte.ChatID, wait time.Duration, stamp uint64, messageID string,
) (command.AdmissionOutcome, command.Reservation)

ReserveTurnForPrompt takes the chat's admission slot for a prompt, waiting up to wait; a refusal keys on the holder's source.

func (*Runtime) Runs

func (rt *Runtime) Runs() *Runs

Runs exposes the run surface to the composition root (orphan sweep, schedule.Launcher).

func (*Runtime) SSEClientCount

func (rt *Runtime) SSEClientCount() int

SSEClientCount is the number of connections the hub is serving right now.

func (*Runtime) SSEConnects

func (rt *Runtime) SSEConnects() (legacy, v3 uint64)

SSEConnects reports connects per wire generation: legacy (no SSE-Wire header) and v3.

func (*Runtime) SecurityProfileChanged added in v0.12.9

func (rt *Runtime) SecurityProfileChanged(ctx context.Context)

SecurityProfileChanged applies a persisted profile change: presets ride the session door and KAS has no live setter, so resident sessions reload. A parentless run keeps the presets its lease recorded at launch.

func (*Runtime) SetChatSteering added in v0.12.0

func (rt *Runtime) SetChatSteering(fn func(context.Context) []marotte.ClientSteeringDoc)

SetChatSteering installs the chat-only steering renderer, on the coordinator for SetPreSessionOpen's reason.

func (*Runtime) SetCodeIntelligence

func (rt *Runtime) SetCodeIntelligence(lspConfigPath string, gate func() bool)

SetCodeIntelligence wires the activation inputs; unset in tests. The engine's ready hook may already be reading them, since the tools engine that owns the gate is built after the runtime.

func (*Runtime) SetMCPOnChange

func (rt *Runtime) SetMCPOnChange(fn func())

SetMCPOnChange wires a callback fired on every MCP registry change (main.go regenerates environment.md).

func (*Runtime) SetPreSessionOpen added in v0.15.0

func (rt *Runtime) SetPreSessionOpen(fn func(context.Context))

SetPreSessionOpen wires a callback run synchronously before each chat session door (refreshing `environment.md`, which KAS reads as steering at the door), so it must be fast. It lives on the coordinator, which would otherwise capture a nil at construction.

func (*Runtime) SetWriteHook added in v0.12.13

func (rt *Runtime) SetWriteHook(path string, hook WriteHook)

SetWriteHook runs hook on every agent write whose target is the file at path, an absolute path; a later hook for the same path replaces this one.

func (*Runtime) SettleTurnOnResponse

func (rt *Runtime) SettleTurnOnResponse(ctx context.Context, chatID marotte.ChatID, turnID string, seq uint64, resp *marotte.RPCResponse)

SettleTurnOnResponse closes the turn on its settling response once the queue behind it is consumed, unless turn_end got there first.

func (*Runtime) Shutdown

func (rt *Runtime) Shutdown(ctx context.Context) error

Shutdown drains in-flight prompts and stops the agent engine, bounded by ctx. The engine stops before the inflight wait, since a stuck Call returns only through the engine's teardown. ctx is the only bound: webhttp.Run's pre-drain hook is synchronous. The error names the first wait to exceed it.

func (*Runtime) StartTurn

func (rt *Runtime) StartTurn(ctx context.Context, turn command.TurnRef, cancel context.CancelCauseFunc) bool

StartTurn stamps the model and credit baseline onto the turn, with the bridge live, just before the call.

func (*Runtime) StepSessionOf added in v0.15.0

func (rt *Runtime) StepSessionOf(ctx context.Context, sessionID string) (workflowID string, found bool, err error)

StepSessionOf reports whether a KAS session is a workflow step's, and whose, from the workspace's session list: a session read, which unlike a run read reconciles no run. The step row is the one carrying `_meta.kiro.workflow`.

func (*Runtime) StopRequestedAfter added in v0.12.0

func (rt *Runtime) StopRequestedAfter(chatID marotte.ChatID, turnID string) bool

StopRequestedAfter reports whether a stop was requested after turnID opened.

func (*Runtime) SweepOrphanRunLogs added in v0.17.0

func (rt *Runtime) SweepOrphanRunLogs(ctx context.Context, p RunRetention) RunPurgeResult

SweepOrphanRunLogs removes, oldest first and at most orphanRunLogCap per runPurgePace, the run logs under the config dir's runs/ older than p.Window (and orphanRunLogGuard) whose run is absent from a complete workflow/list and from KAS's run state on disk. A failed or partial list, an unreadable KAS store or lease file removes nothing; a log marotte leases or has a step open in is kept; a log whose removal fails is skipped until restart.

func (*Runtime) SyncPowers added in v0.12.0

func (rt *Runtime) SyncPowers(ctx context.Context)

SyncPowers renders the legacy block under the locks known now (servers suppressed at boot) and requests the administrator rules, re-rendering on their resolution and every lock change.

func (*Runtime) TangentParent added in v0.13.0

func (rt *Runtime) TangentParent(ctx context.Context, chatID marotte.ChatID) (marotte.ChatID, error)

TangentParent answers the chat chatID was forked from through KAS's own link: the first session of chatID's chain whose session/list row names a parentSessionId outside that chain, mapped to the chat whose chain holds it. A successor session (a compaction, a model switch) carries no link, so the whole chain is walked.

func (*Runtime) TeardownCancel added in v0.17.0

func (rt *Runtime) TeardownCancel(ctx context.Context, chatID marotte.ChatID) error

TeardownCancel sends the chat's session/cancel as the teardown's closer, after AwaitSessionLeases. A chat with no session has nothing to cancel.

func (*Runtime) TryReserveIdleTurn added in v0.12.16

func (rt *Runtime) TryReserveIdleTurn(chatID marotte.ChatID, source marotte.TurnOpenSource, stamp uint64) (command.Reservation, bool)

TryReserveIdleTurn takes the chat's admission slot iff no turn is open and nothing holds it.

func (*Runtime) TryReserveTurn

func (rt *Runtime) TryReserveTurn(chatID marotte.ChatID, source marotte.TurnOpenSource, stamp uint64) (command.Reservation, bool)

TryReserveTurn takes the chat's admission slot iff it is free.

func (*Runtime) TryReserveTurnFenced added in v0.12.0

func (rt *Runtime) TryReserveTurnFenced(chatID marotte.ChatID, source marotte.TurnOpenSource, fence command.TurnFence) (command.Reservation, bool)

TryReserveTurnFenced takes the chat's admission slot iff it is free and no turn opened after the fenced one.

func (*Runtime) TurnIsOpen added in v0.17.0

func (rt *Runtime) TurnIsOpen(chatID marotte.ChatID, turnID string) bool

TurnIsOpen reports whether turnID is an open, non-finalizing turn of the chat's live lifecycle.

func (*Runtime) TurnLive

func (rt *Runtime) TurnLive(chatID marotte.ChatID) bool

TurnLive reports whether the reader must treat the chat as running: its own turn, an admitted prompt awaiting its bracket, or a held slot (chat.WithLiveTurn).

func (*Runtime) TurnOpenedAfter

func (rt *Runtime) TurnOpenedAfter(chatID marotte.ChatID, turnID string) bool

TurnOpenedAfter reports whether any own turn on the chat opened after turnID.

func (*Runtime) TurnReply added in v0.13.0

func (rt *Runtime) TurnReply(ctx context.Context, chatID marotte.ChatID, turnID string) (string, error)

TurnReply answers the main-lane text of one turn: consecutive text entries join as they streamed, and a tool call or any other entry between two says starts a new paragraph.

type Settings

type Settings struct {
	// contains filtered or unexported fields
}

Settings owns the KAS configuration surface (knowledge, hooks, governance, Cedar policy queries) and its routes: engine calls, and observer passes for the reads KAS answers only on a resident session.

func (*Settings) GovernanceLocks added in v0.12.0

func (st *Settings) GovernanceLocks() map[string]marotte.GovernanceLock

GovernanceLocks answers the lock map in force.

func (*Settings) KiroDefaults added in v0.13.0

func (st *Settings) KiroDefaults() map[string]marotte.KiroDefault

KiroDefaults answers what each kiroDefaultKeys setting resolves to in kiro-cli, keyed by the marotte setting key; empty until the engine has reported a view. The caller drops the keys the user has set.

func (*Settings) PolicyChanged added in v0.12.0

func (st *Settings) PolicyChanged(ctx context.Context, errs []marotte.PolicyErrorItem, reloaded bool)

PolicyChanged re-reads the administrator rules after a policy notification. A fatal administration error fails every lock closed until a clean reload. Satisfies translate.governanceAccess.

func (*Settings) PolicyExplain

PolicyExplain simulates a policy decision without executing or prompting (KAS evaluateSingleResource). Exactly one of Capability and ToolID; shell also needs a resource.

func (*Settings) PolicyList

func (st *Settings) PolicyList(ctx context.Context, scope string) ([]marotte.PolicyRule, error)

PolicyList returns the native policy rules, optionally for one scope, via _kiro/permissions/list.

func (*Settings) SetGovernance

func (st *Settings) SetGovernance(ctx context.Context, p marotte.GovernanceStatePayload)

SetGovernance caches the account profile. Satisfies translate.governanceAccess.

func (*Settings) SetMCPRegistry added in v0.12.0

func (st *Settings) SetMCPRegistry(ctx context.Context, r *marotte.GovernanceMCPRegistry)

SetMCPRegistry caches the organization's MCP registry. Satisfies translate.governanceAccess.

type WriteHook added in v0.12.13

type WriteHook struct {
	// Check runs before anything is written; a non-nil error refuses the write, and its text is
	// the answer the agent reads. A restore KAS makes after a turn approval or during a rewind is
	// written even so (turnRegistry.expectRestores): refusing it would keep a change the user rejected.
	Check func(content []byte) error
	// Saved runs once a write is on disk, a restore Check refused included, before the agent is answered.
	Saved func()
}

WriteHook governs the agent's fs/write_text_file writes of one file. Either func may be nil.

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL