{"modulePath":"github.com/memcode-ai/memcode","version":"v0.56.16","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package runtime\n\nPackage runtime: this file is the thin seam to the read-only intelligence Engine (internal/agent/introspect). The commands themselves were carved off the Session god-object into their own leaf package; Session supplies the Engine its state plus the few runtime-internal callbacks it needs and otherwise just delegates.\n\nPackage runtime is the agent loop: orient via the context compiler, call Claude, execute the tool calls it proposes (under the permission gate), capture every step as an event, and stop when the model is done. v0 is the minimal organism: state → context → LLM → tools → edit/command → diff → test → event.\n\n## Constants\n\n```go\nconst (\n\tKindInstruction = \"instruction\"\n\tKindMemory      = \"memory\"\n\tKindReference   = \"reference\"\n\tKindHistory     = \"history\"\n)\n```\nGeneric context kinds. Callers classify their material into these; the engine orders by them and knows nothing more.\n\n## Variables\n\n```go\nvar (\n\tPlanPolicy = AnalysisPolicy{\n\t\tMode:               \"plan\",\n\t\tReflectionMode:     \"reflect\",\n\t\tAllowScratchpad:    true,\n\t\tExecutionApproval:  true,\n\t\tAskBeforeSynthesis: true,\n\t}\n\tResearchPolicy = AnalysisPolicy{\n\t\tMode:               \"research\",\n\t\tReflectionMode:     \"research_reflect\",\n\t\tAllowScratchpad:    true,\n\t\tExecutionApproval:  false,\n\t\tAskBeforeSynthesis: false,\n\t}\n)\n```\n\n## Functions\n\n```go\nfunc CodeQuery(ctx context.Context, root, query, scope string) (string, bool)\n```\nCodeQuery is the deterministic \"where does X live\" oracle over root — a ranked search with no model loop. Shared by the agent tool (Session.codeQuery) and the standalone \\`memcode mcp serve\\` memory server, so an external agent gets the same answer. ok=false marks a usage error (no terms, bad scope, timeout); a no-match result is ok=true with a guidance string.\n\n```go\nfunc EffortLabel(model string, e wire.Effort) string\n```\nEffortLabel is the pure model+effort description behind ReasoningDisplay and the served-by line. Equal labels on different vendors are not equal budgets, so it only ever names the native level the model runs, never a translation.\n\n```go\nfunc ForkSession(root, srcID string) (string, error)\n```\nForkSession copies srcID's saved transcript (and its checkpoints) to a fresh session id and returns it — the original session is untouched. Fork-from-disk is safe because the transcript persists at every turn boundary and callers refuse to fork mid-turn, so disk equals the live history. The episodic log (events.jsonl/transcript.md) is DELIBERATELY not copied: session search, recall, and the focus reducer scan every session dir, and a duplicated history would double-count what happened — the original keeps the episodic truth, and the fork starts logging its own from here. Checkpoints ride along (best-effort) so /rewind still reaches pre-fork turns in the fork.\n\n```go\nfunc ParseEffort(level string) wire.Effort\n```\nParseEffort maps a user-facing effort name onto the wire level, medium for anything it doesn't recognize (including the retired \"auto\").\n\n```go\nfunc RenderThemeSample(width int) string\n```\nRenderThemeSample renders a tiny fixed diff snippet using the ACTIVE theme — the real diff add/del backgrounds, gutters, and syntax highlighting — so the /theme picker's live preview shows what code review actually looks like, not just chrome. It reads the active theme live (newDiffCtx), so it recolors as the picker previews.\n\n```go\nfunc ResolveSession(root, ref string) (string, error)\n```\nResolveSession maps a user reference to a resumable session id: \"\"/\"latest\" → the most recently saved transcript; otherwise an exact id or unique prefix (\"sess\\_\" optional). Only sessions WITH a saved transcript qualify — older sessions predating transcript persistence are recall-only.\n\n```go\nfunc ResumableSessions(root string) []string\n```\nResumableSessions lists resumable session ids, newest first (for pickers).\n\n## Types\n\n```go\ntype AdminExecutor func(ctx context.Context, name string, input json.RawMessage) (string, error)\n```\nAdminExecutor performs one admin tool operation (cmd-injected; see cmd/admin\\_tools.go). It is only invoked after the runtime's gate approves a mutation; read-only calls run directly.\n\n```go\ntype AgentResult struct {\n\tText      string\n\tToolCalls int\n\tServedBy  string // which model actually ran it\n}\n```\nAgentResult is a sub-agent's report-back: its final text plus the telemetry callers surface (the tool-count + served-by on the marker line).\n\n```go\ntype AgentSpec struct {\n\tTask     string      // the self-contained instruction the sub-agent runs to completion\n\tReadOnly bool        // read-only (no edits/mutating bash) vs a full mutating agent\n\tScope    string      // optional subsystem/path tag (telemetry + scout focus)\n\tIterCap  int         // 0 = mode default\n\tPurpose  llm.Purpose // ledger attribution; also picks the run shape (Explore → scout prompt)\n\tEffort   wire.Effort // pin the sub-agent's thinking effort (\"\" = its own per-turn heuristic)\n\t// Root roots the sub-agent at another folder (\"\" = the parent's root). Its\n\t// file tools are confined there, exactly as the parent's are to its own\n\t// root: a website worker edits the site's managed copy and nothing else.\n\tRoot string\n\t// Show streams the worker's activity (its tool lines, edits and notes)\n\t// into the conversation, indented under the caller's marker, instead of\n\t// discarding it: for long, user-visible work like building a website.\n\tShow bool\n\t// Store is the worker's own state store (nil = the parent's). A worker\n\t// rooted at another project must not be oriented by this one's memory.\n\tStore store.Store\n\t// Site makes the worker a website worker: the site tool, a headless\n\t// browser of its own, and package managers reachable only through it.\n\tSite *siteWork\n}\n```\nAgentSpec is everything that configures a sub-agent. Defaults (zero value) are a mutating, MainLoop-ish agent; callers set what they need.\n\n```go\ntype AnalysisPolicy struct {\n\tMode               string\n\tReflectionMode     string\n\tAllowScratchpad    bool\n\tExecutionApproval  bool\n\tAskBeforeSynthesis bool\n}\n```\nAnalysisPolicy governs shared analytical behavior for plan and research modes.\n\n```go\ntype ApprovalDecision struct {\n\tAllow         bool   // run it\n\tRemember      bool   // and don't ask again for like commands (persist an approval rule)\n\tRememberScope string // when Allow: the chosen ApprovalScope.Key (\"\" = none / plain yes)\n\tCommand       string // when Allow and non-empty: run THIS instead of the original\n\tReason        string // when !Allow: why — fed back to the model so it can adjust\n\tInterrupt     bool   // STOP the whole turn (Esc / \"No, stop\") — the model does not get another call\n\tRedirect      bool   // when !Allow with a typed Reason: deny this action and skip its siblings, but let the turn CONTINUE so the model reads the feedback and responds (does NOT terminate)\n}\n```\nApprovalDecision is the user's structured answer. It generalizes yes/no into the four outcomes a real agent needs: allow · allow-with-edited-input · deny-with-reason · interrupt (stop going down this path entirely).\n\n```go\nfunc Allowed() ApprovalDecision\n```\nAllowed is a plain yes.\n\n```go\nfunc Denied(reason string) ApprovalDecision\n```\nDenied is a no, optionally with a reason the model will see.\n\n```go\ntype ApprovalRequest struct {\n\tTitle    string // the thing being approved — the command, or \"edit \u003cpath\u003e\"\n\tLabel    string // category header, e.g. \"Bash command\" / \"Edit file\"\n\tDetail   string // optional one-line description under the title\n\tCommand  string // the command, when this is a command (so it can be edited/remembered)\n\tCwd      string // working directory for a command (for the \"don't ask again … in \u003cdir\u003e\" scope)\n\tEditable bool   // whether \"allow with edited command\" / \"don't ask again\" apply (commands)\n\tRisk     string // risk class label\n\t// RememberScopes replaces the single default don't-ask-again option with one card\n\t// option per scope (MCP: remember this tool / remember the whole server). When set,\n\t// the card reads Execute / \u003cscopes…\u003e / Cancel and Cancel is a plain deny.\n\tRememberScopes []ApprovalScope\n}\n```\nApprovalRequest is a structured description of an action awaiting the user's OK. The metadata (Title/Label/Detail) lets a front-end render a rich prompt; Command + Editable enable \"allow, but run this instead\". This replaces the old bare prompt string — a boolean approver is too crude for a serious agent.\n\n```go\ntype ApprovalScope struct {\n\tKey   string // returned in ApprovalDecision.RememberScope when chosen\n\tLabel string // full option text on the card\n}\n```\nApprovalScope is one scoped \"and don't ask again\" option a request offers.\n\n```go\ntype AskOption = tools.AskOption\n```\nAskOption is one candidate answer — a concise Label plus an optional muted Description line. Aliased to the tool-input type so there's ONE shape from the model's JSON through to the rendered card.\n\n```go\ntype AskRequest struct {\n\tQuestion string\n\tOptions  []AskOption // 2-4 choices (label + optional description); the user may also type their own\n}\n```\nAskRequest is a clarifying question the agent poses to the user (HITL).\n\n```go\ntype AskResponse struct{ Answer string }\n```\nAskResponse is the user's answer (a chosen option or free text); empty means the user dismissed it (the agent should then proceed on its best judgment).\n\n```go\ntype BusyOwner int\n```\nBusyOwner says who owns the frontend's busy state. OwnerTurn is a scheduler transaction (queueing behind it is normal); OwnerAsync is a non-transaction operation (advisor, /compact) that a new turn must not trample.\n\n```go\nconst (\n\tOwnerNone BusyOwner = iota\n\tOwnerTurn\n\tOwnerAsync\n)\n```\n\n```go\ntype ChatState struct {\n\t// contains filtered or unexported fields\n}\n```\nChatState holds the evolving state of an interactive session — the system prompt, the running message history, and the queued follow-ups — so any front-end (the line-REPL below or the TUI) can pump input lines via Submit while the runtime owns routing and the agent loop.\n\n```go\ntype ContextItem struct {\n\tKind    string `json:\"kind\"`\n\tContent string `json:\"content\"`\n\tSource  string `json:\"source,omitempty\"` // provenance label for the injected block header\n}\n```\nContextItem is one piece of supplemental context handed to the engine by a caller (the agent runtime, an API, CI). The engine stays ignorant of where it came from: Kind is a GENERIC content class, never an orchestration concept like \"agent\", \"user\", \"channel\", or \"conversation\". Those live above the engine and are flattened into these generic items before an invocation.\n\n```go\ntype Decision struct {\n\tKind DecisionKind\n\tPos  int          // 1-based queue position (Queued / Coalesced)\n\tTx   *Transaction // the started or queued transaction (nil for Steered)\n}\n```\nDecision is the outcome of accept — for the UI to acknowledge.\n\n```go\ntype DecisionKind int\n```\nDecisionKind is what the scheduler did with an accepted line.\n\n```go\nconst (\n\tDecisionStarted      DecisionKind = iota // started a transaction now (was idle)\n\tDecisionQueued                           // queued behind the active transaction\n\tDecisionCoalesced                        // merged into the previous queued item (rapid paste)\n\tDecisionSteered                          // folded into the active transaction as a steer\n\tDecisionAwaitVerdict                     // planning, unclassified — classify, then Accept again with the verdict (nothing mutated)\n\tDecisionPlanDeferred                     // classified separate — the frontend parks it (nothing mutated)\n\tDecisionBusyDeclined                     // an async op owns busy while idle — declined (nothing mutated, no ghost tx to cancel)\n)\n```\n\n```go\ntype DrainSink int\n```\nDrainSink is where drained deferred messages go.\n\n```go\nconst (\n\tSinkQueueBehind  DrainSink = iota // queue behind what was just accepted (the apply turn)\n\tSinkStartNow                      // route normally — nothing is ahead\n\tSinkCarryForward                  // re-park against the new plan session\n)\n```\n\n```go\nfunc PlanDrainSink(exit PlanExit) DrainSink\n```\nPlanDrainSink is the ONE policy for replaying parked messages at a plan exit — the three hand-rolled drain loops used to each encode a different slice of it.\n\n```go\ntype GateInput struct {\n\tPhase        plan.Phase  // the plan machine's phase at submit/finalize time\n\tPlanEpoch    int         // epoch the verdict was computed against (0 = n/a)\n\tCurrentEpoch int         // the machine's epoch NOW (finalize time)\n\tVerdict      PlanVerdict // the relevance verdict, when one exists\n\tBusy         BusyOwner   // who owns the frontend's busy state\n\t// Internal marks a system-generated accept (the plan task itself, the apply\n\t// instruction, a revise, an already-classified deferred replay): it bypasses the\n\t// plan gate by construction (Phase zero) AND pre-marks a queued tx classified, so\n\t// the background follow-up classifier never judges system text against the active\n\t// task (folding \"Begin implementing the approved plan\" as a steer broke the apply).\n\tInternal bool\n\t// Research marks a /research turn: request-scoped analytical mode that\n\t// bypasses the plan gate and runs without mutating Session state.\n\tResearch bool\n}\n```\nGateInput is the non-scheduler context a frontend supplies with each accept. The zero value is exactly today's plain-chat behavior: chatting, no verdict, not busy.\n\n```go\ntype GitStat struct {\n\tFiles, Added, Removed                   int // unstaged working tree + untracked\n\tStagedFiles, StagedAdded, StagedRemoved int // index (git add'd)\n}\n```\nGitStat is the working-tree summary surfaced in the footer cockpit: how many files are dirty and the +/- line churn, split into unstaged (working tree, incl. untracked) and staged (index). A clean tree is the zero value.\n\n```go\nfunc (g GitStat) Clean() bool\n```\nClean reports whether the working tree has nothing uncommitted.\n\n```go\ntype Orientation struct {\n\tRepo             string\n\tBranch           string\n\tSubsystems       int\n\tHighlights       []string // top subsystem keys by activity (for a concrete prompt)\n\tClaimsCurrent    int\n\tClaimsStale      int\n\tClaimsConflicted int\n\tSources          int\n}\n```\nOrientation is the \"I know where I am and what I know about this repo\" summary the TUI shows on the opening screen, so the first moment proves memcode is repo-aware rather than a blank chatbot.\n\n```go\ntype PlanExit int\n```\nPlanExit names how a plan session ended, for the deferred-message drain policy.\n\n```go\nconst (\n\tExitExecute PlanExit = iota // approved: parked messages run AFTER the apply turn\n\tExitCancel                  // cancelled: nothing ahead — parked messages start now\n\tExitNewPlan                 // a new plan is starting: carry leftovers into it\n)\n```\n\n```go\ntype PlanOpt = plan.Opt\n```\nPlanOpt is a functional option for EnterPlan — an alias for plan.Opt so existing callers (WithYolo) compile unchanged.\n\n```go\nfunc WithTask(task string) PlanOpt\n```\nWithTask anchors this plan session to the task text that started it — the message the user typed, or the /plan argument. Alias for plan.WithTask.\n\n```go\nfunc WithYolo() PlanOpt\n```\nWithYolo suppresses human-in-the-loop questions during planning and auto-resolves them with the model's recommended choice. The TUI also auto-executes the plan without showing the approval selector. Alias for plan.WithYolo.\n\n```go\ntype PlanVerdict int\n```\nPlanVerdict is the plan-relevance classifier's answer as data.\n\n```go\nconst (\n\tVerdictNone     PlanVerdict = iota // not classified (yet)\n\tVerdictRelated                     // continues/steers the plan being drafted\n\tVerdictSeparate                    // a separate ask — park it until the plan is done\n)\n```\n\n```go\ntype Result struct {\n\tSessionID    string   `json:\"session_id\"`\n\tIterations   int      `json:\"iterations\"`\n\tToolCalls    int      `json:\"tool_calls\"`\n\tWrongTurns   int      `json:\"wrong_turns\"` // failed tool calls\n\tFilesRead    int      `json:\"files_read\"`\n\tFilesChanged []string `json:\"files_changed\"`\n\tDiffLines    int      `json:\"diff_lines\"`\n\tInputTokens  int      `json:\"input_tokens\"`\n\tOutputTokens int      `json:\"output_tokens\"`\n\tVerified     bool     `json:\"verified\"` // a verification command passed\n}\n```\nResult reports measurable outcomes of a session (used by the A/B harness).\n\n```go\ntype RouteAction int\n```\nRouteAction is the single vocabulary for what happens to an incoming message.\n\n```go\nconst (\n\tActStartTurn    RouteAction = iota // idle → run it now\n\tActSteer                           // fold into the active transaction\n\tActQueue                           // run after the active transaction\n\tActCoalesce                        // merge into the last queued item (rapid burst)\n\tActAwaitVerdict                    // planning, unclassified → classify first, re-enter with the verdict\n\tActDeferForPlan                    // classified separate → park until the plan exits\n\tActRejectBusy                      // an async op owns busy and nothing is active — decline politely\n)\n```\n\n```go\ntype Scheduler struct {\n\t// contains filtered or unexported fields\n}\n```\nScheduler is the actor wrapper around schedState: ONE owner goroutine (run) holds the state and serializes every access through a command channel. Neither the TUI intake nor the executor mutates scheduler state directly — they only send commands and read replies — so there is no shared mutable state to race (the design constraint).\n\nDrivers:\n\n  - intake (TUI Update goroutine): Accept / Cancel / Snapshot — fast, synchronous round-trips; they never block on execution.\n  - executor (TUI engine goroutine): on a \"run\" kick, TakeActive() → RunTransaction → Finish; DrainSteers mid-run at the runLoop safe boundary. TakeActive is NON-BLOCKING so the executor can keep selecting on its other inputs (sentinels).\n\nThe actor owns the per-transaction context: TakeActive mints context.WithCancel and stores the cancel, so Cancel() is just a command and the executor never owns cancellation state.\n\n```go\nfunc NewScheduler(parent context.Context, obs SchedulerObserver, clock func() time.Time) *Scheduler\n```\nNewScheduler starts the actor goroutine; it runs until parent is cancelled. clock is injectable for tests — pass time.Now in production.\n\n```go\nfunc (s *Scheduler) Accept(line string, gate GateInput) Decision\n```\nAccept routes one submitted line against the current state (intake; never blocks on execution). gate carries the non-scheduler context (plan phase/epoch, relevance verdict, busy owner) — GateInput{} is plain-chat behavior. Returns what the scheduler did, for the UI to acknowledge; the AwaitVerdict/PlanDeferred/BusyDeclined kinds mutated nothing and expect the frontend to act (classify / park / decline).\n\n```go\nfunc (s *Scheduler) Cancel() bool\n```\nCancel aborts the active transaction (Esc/Ctrl-C): marks it cancelling, cancels its context, and DISCARDS the queue — interrupt means STOP, not advance to the next queued item. Reports whether there was an active transaction.\n\n```go\nfunc (s *Scheduler) DrainSeparate() (activeText, activeTitle string, items []separateAsk)\n```\nDrainSeparate returns and clears the buffered separate-task items, along with the active transaction's raw text and the classifier's synthesized title for it (for seeding a \"current task\" placeholder todo item the first time this fires — both go through the synthTitle guard, so raw prose never becomes a list title) — called at the runLoop safe boundary.\n\n```go\nfunc (s *Scheduler) DrainSteers() []string\n```\nDrainSteers returns and clears the active transaction's pending steers — called at the runLoop safe boundary to fold \\`+input\\` into the active turn.\n\n```go\nfunc (s *Scheduler) Finish(result TransactionResult) (promoted bool)\n```\nFinish marks the active transaction terminal and promotes the next queued one (FIFO). Returns true when a transaction was promoted — the executor should kick itself to run it.\n\n```go\nfunc (s *Scheduler) FoldQueued(expectActive string, ids []string) []string\n```\nFoldQueued promotes the named queued transactions into the active transaction as steers (the classifier's \"related\" verdict) and returns their folded texts. expectActive is the active-tx id the classifier judged against — the fold is dropped if the active tx changed since (so a refinement of a finished task can't steer an unrelated running turn).\n\n```go\nfunc (s *Scheduler) NoteSeparate(items []separateAsk, activeTitle string)\n```\nNoteSeparate records items the background follow-up classifier judged SEPARATE from the active task (the \"not related\" verdict) — they stay queued to run as their own turn later, but this buffers them so the runLoop safe boundary can track them on the todo list and give the model a brief FYI note (see DrainSeparate). activeTitle is the SAME classify call's synthesized title for the CURRENT task (empty when synthesis failed).\n\n```go\nfunc (s *Scheduler) PendingClassification() (activeID, active string, items []*Transaction)\n```\nPendingClassification returns the active task's text and the queued transactions the background follow-up classifier hasn't examined yet (marking them examined). The classifier runs the cheap structured-output model OFF the actor goroutine, then calls FoldQueued with the ids it judged related to the active task.\n\n```go\nfunc (s *Scheduler) SendNow() []string\n```\nSendNow folds everything queued into the running turn (it lands at the next safe boundary) instead of waiting for the turn to finish. Returns the folded texts.\n\n```go\nfunc (s *Scheduler) Snapshot() []string\n```\nSnapshot returns the queued transactions' texts (for a quiet UI indicator).\n\n```go\nfunc (s *Scheduler) TakeActive() (*Transaction, context.Context, bool)\n```\nTakeActive hands the active, not-yet-running transaction to the executor with its cancellable context. NON-BLOCKING: returns (nil, nil, false) when nothing is ready, so the executor stays free to handle its other inputs. The executor calls this on a \"run\" kick (after Accept reported Started, or after Finish promoted the next).\n\n```go\ntype SchedulerObserver interface {\n\tSchedulerChanged(activeID string, queued []string)\n}\n```\nSchedulerObserver is notified (best-effort) when the active/queued set changes, so a front-end can render a quiet \"(N queued)\" indicator. The queue is runtime-managed; there is no user-facing queue-editing command in Phase 1.\n\n```go\ntype Session struct {\n\t// contains filtered or unexported fields\n}\n```\nSession runs one agent task against a project.\n\n```go\nfunc New(st store.Store, runner *llm.Runner, root, model string, mode permissions.Mode, out io.Writer) *Session\n```\nNew constructs a Session.\n\n```go\nfunc (s *Session) AddObjective(ctx context.Context, title string) (string, error)\n```\nAddObjective records a human-authored goal for this project (the \\`/goal\\` command). Objectives are never inferred; this is the user asserting one.\n\n```go\nfunc (s *Session) AddRedactSecrets(values ...string)\n```\nAddRedactSecrets registers additional secret values with the session's redactor (e.g. the token /login just received) so they never reach transcripts, traces, or tool output.\n\n```go\nfunc (s *Session) Admin() bool\n```\nAdmin reports whether this is an admin session (the TUI swaps its slash set).\n\n```go\nfunc (s *Session) Analytical() bool\n```\nAnalytical reports whether the session is in any analytical mode (\"plan\" or \"research\").\n\n```go\nfunc (s *Session) AnnouncePlan(yolo bool)\n```\nAnnouncePlan prints the standard ⏺ Plan tool-marker line for both /plan (slash command) and enter\\_plan (tool call).\n\n```go\nfunc (s *Session) AnnounceResearch()\n```\nAnnounceResearch prints the /research turn header to scrollback.\n\n```go\nfunc (s *Session) Answer(ctx context.Context, scope, question string) (string, error)\n```\nAnswer runs a read-only investigation to completion and returns the model's final text. It is the unit of a parallel explorer (a \"reader\" sub-agent): it orients on a scope, reads/searches under the read-only tool set, and never edits or runs MUTATING commands (it may run read-only shell commands like git log via the gated inspect shell) — so any number can run concurrently with no serialized-writer contention. Output is suppressed (the orchestrator owns presentation); every tool call is still recorded as an event.\n\n```go\nfunc (s *Session) ArchDoc() string\n```\nArchDoc renders the repo's architecture diagrams verbatim from its docs (deterministic).\n\n```go\nfunc (s *Session) AskAdvisor(ctx context.Context, question, effort string) (string, bool)\n```\nAskAdvisor sends a question (plus light session context) to the gateway's second-opinion advisor — a DIFFERENT vendor from the coding lanes; the gateway owns which model serves it — and returns its advice. effort is the reasoning depth (low|medium|high; \"\" → high). This is a deliberate user action (/advisor, or \"Ask an advisor\" in plan mode), not part of the coding-inference path. Returns (text, ok).\n\n```go\nfunc (s *Session) BrowserEnabled() bool\n```\nBrowserEnabled reports whether --chrome is active (browser tools are advertised and a Chrome session may be launched). Used by the TUI's /dispatch to forward the capability to spawned sub-agents.\n\n```go\nfunc (s *Session) CacheStats() (read, write int)\n```\nCacheStats returns cumulative prompt-cache token counts (read ≈ 10% cost; write = tokens written to the cache). Shown under /debug.\n\n```go\nfunc (s *Session) Chat(ctx context.Context) error\n```\nChat runs the line-REPL interactive session: streamed stdin with time-based coalescing and routing, multimodal attachments, persisted events. The TUI drives the same StartChat/Submit/EndChat seams without owning stdin.\n\n```go\nfunc (s *Session) Checkpoints() []checkpoint.Manifest\n```\nCheckpoints lists this session's rewind points (turns that edited files), oldest first.\n\n```go\nfunc (s *Session) ClassifyFollowups(ctx context.Context, active string, items []string) (verdicts map[int]followupVerdict, activeTitle string, ok bool)\n```\nClassifyFollowups asks the cheap structured-output classifier which queued follow-ups refine the active task. Returns one verdict per index: Related marks a fold, and Title — present only for a SEPARATE verdict — is the classifier's concise, synthesized todo-list title (never the raw text). It ALSO returns activeTitle: the SAME classifier call's synthesized title for the CURRENT task itself (same call, no extra cost) — used to seed the placeholder todo item for the active task instead of clipping its raw text. ok=false means NO classification happened (error / timeout / missing context): the caller must treat the batch as unjudged — retry or leave it queued — never as a set of \"separate\" verdicts (an empty map read through Go's zero value is what used to turn every classify hiccup into untitled \"separate tasks\" pasted verbatim onto the todo list). Safe to call concurrently with the active turn (the metered Runner is concurrency-safe).\n\n```go\nfunc (s *Session) ClassifyPlanIntent(ctx context.Context, text string) bool\n```\nClassifyPlanIntent resolves the AMBIGUOUS middle of plan-request detection — the front-end's deterministic heuristic handles clear yes/no and only escalates here when \"plan\" is present but the intent is unclear. Lives on Session (not the introspect Engine) so it rides the shared judge plumbing (traced, failure-counted). Best-effort: any error/timeout/parse miss → false, so ambiguity never hijacks an ordinary turn into plan mode.\n\n```go\nfunc (s *Session) ClassifyPlanMessage(ctx context.Context, text, task, draft string) (related bool, title string)\n```\nClassifyPlanMessage asks the cheap structured-output classifier whether text continues the plan anchored at task (with draft — the pinned LastPlan, possibly empty — as context), or is a separate request that should be parked. task/draft are passed in, not read from s.planCtl, so the call is safe off-goroutine: take them from PlanGateSnapshot. Returns related=true (fold-in, the safe default) when there is no task anchor to judge against (e.g. a test that sets planCtl.Active directly without going through EnterPlan), and on ANY classify error/timeout/parse miss — an infra hiccup must never silently swallow a genuine follow-up by mistaking it for something separate. title is populated only for a related=false verdict and is the classifier's synthesized title, never raw text.\n\n```go\nfunc (s *Session) ClearCredentials()\n```\nClearCredentials disconnects the provider (the /logout path).\n\n```go\nfunc (s *Session) ClearReasoning()\n```\nClearReasoning empties the reasoning line before a UI-started model op (/compact, /advisor, …), the same way a user turn does.\n\n```go\nfunc (s *Session) CloseBrowser()\n```\nCloseBrowser tears down the Chrome process if one was launched. Safe to call when no browser session exists (nil-safe). Called at session end.\n\n```go\nfunc (s *Session) CommitGateChoice(ctx context.Context, commitFirst bool)\n```\nCommitGateChoice is the TUI's entry point when the PLAN SELECTOR carries the commit decision (\"Commit first, then execute\" / \"Execute without committing\") instead of a second card: it performs the commit when asked and marks the gate resolved so the apply turn doesn't re-ask.\n\n```go\nfunc (s *Session) CommitGateNeeded(ctx context.Context) bool\n```\nCommitGateNeeded reports whether the plan selector should offer the commit choice: interactive, a git repo, a dirty tree, and no remembered preference (a remembered \"commit\"/\"skip\" is honored silently by commitGateOK).\n\n```go\nfunc (s *Session) Compact(ctx context.Context, st *ChatState) string\n```\nCompact is the manual /compact entry point: force a compaction now and return a one-line result for the front-end to print (success line, or why it was a no-op).\n\n```go\nfunc (s *Session) Connected() bool\n```\nConnected reports whether the session's provider has a usable backend — hosted gateway credentials OR a configured custom endpoint (the Phase C widening; the seam is provider.Connector). Providers without the Connector capability (test fakes, futures) count as connected — the mandatory-login gate only applies to the real lazy client.\n\n```go\nfunc (s *Session) ContextTokens() int\n```\nContextTokens returns the input size of the latest MAIN conversation call — an estimate of how full the context window currently is (footer \"ctx N%\"). Read under dispMu (snapshot): the engine writes s.served mid-turn while View reads this every frame.\n\n```go\nfunc (s *Session) ContextWindow() int\n```\nContextWindow returns the input window (tokens) the meter measures against. It prefers the serving backend's REAL window when the gateway reported one (the lane's max\\_model\\_len — often far smaller than the model-name default), so the meter warns before a self-hosted overflow instead of reading a comfortable 14%. Falls back to the model's nominal window (Anthropic turns report none).\n\n```go\nfunc (s *Session) DeferWhilePlanning(text, title string)\n```\nDeferWhilePlanning parks a message the plan-intake classifier judged SEPARATE from the plan: it never reaches the scheduler while planning (so it can't corrupt the draft), and is held in s.planDeferred (with a concise synthesized display title for the TUI's queued strip via PlanDeferredTitles) until DrainPlanDeferred replays it on ExitPlan.\n\nOwnership invariant: parked user requests are runtime-scheduled state, NOT model-owned tasks — DeferWhilePlanning intentionally never mutates s.todos.\n\n```go\nfunc (s *Session) DelegatedModel() string\n```\nDelegatedModel reports the model delegated work runs on, resolved through policy. It exists for display (/status, /policy) — decision points resolve the target they care about rather than asking a general question.\n\n```go\nfunc (s *Session) DisplayModel() string\n```\nDisplayModel is what the cockpit (footer/banner//status) shows as THE model: the /model pin when one is set — the user picked it, so that's the identity, even before the first pinned turn serves (ServingModel would still show the pre-pin lane) — else the served/default model. The ⇄ line keeps reporting per-turn serving reality (absorbs included).\n\n```go\nfunc (s *Session) DrainPlanDeferred() []string\n```\nDrainPlanDeferred pops and clears every message parked by DeferWhilePlanning, FIFO — called on ExitPlan (Execute or Cancel) so parked messages run once the plan work that pushed them aside is actually done, exactly as the user asked.\n\n```go\nfunc (s *Session) DrainShellReportBacks() []ShellReportBack\n```\nDrainShellReportBacks returns the promoted commands that finished since the last call, each once, with their result redacted for hand-back to the model. Polled by the UI.\n\n```go\nfunc (s *Session) DrainSiteBuildReports() []SiteBuildReport\n```\nDrainSiteBuildReports returns the watched builds that finished since the last call, each once. Polled by the UI.\n\n```go\nfunc (s *Session) EffortOverride() string\n```\nEffortOverride reports the session's chosen effort by name (\"off\" for none).\n\n```go\nfunc (s *Session) Emit(ctx context.Context, kind events.Kind, payload map[string]any)\n```\nEmit is the public alias of emit — the plan.Controller's Session interface needs a callable emitter, and interface methods must be exported. Same behavior as emit.\n\n```go\nfunc (s *Session) EndChat(ctx context.Context)\n```\nEndChat records the session-finished event and closes the episodic log. Idempotent enough for one call.\n\n```go\nfunc (s *Session) Endpoint() (provider.Endpoint, bool)\n```\n\n```go\nfunc (s *Session) EnterPlan(ctx context.Context, opts ...PlanOpt)\n```\nEnterPlan switches the session into plan mode: research-only tools, the reasoning model, and the planning system prompt. Records plan\\_started. Delegates to the plan.Controller machine; already planning/applying → no-op.\n\n```go\nfunc (s *Session) EnterResearch(ctx context.Context, topic string)\n```\nEnterResearch switches the session into research mode on the shared analytical lifecycle controller (plan.Controller with mode=\"research\").\n\n```go\nfunc (s *Session) ExitPlan(ctx context.Context, approved bool)\n```\nExitPlan leaves plan or research mode, restoring the prior model. approved distinguishes an /execute handoff (Approve: pins the contract, arms the apply turn) from a /cancel (Cancel: abandon); either way the lifecycle event is recorded.\n\n```go\nfunc (s *Session) ExitReadOnlyForExecution(mode permissions.Mode) bool\n```\nExitReadOnlyForExecution is the ONLY place Read Only is lifted to let real writes through. Called by every path that reaches the apply phase — the plan selector's explicit mode choice, /yolo's auto-execute, and executePlanTool's typed \"execute\" — so they can't drift into subtly different exits. A session-only transition (like a one-off --auto/--allow-all flag, not a remembered Shift+Tab/\\`/mode\\` choice): it does NOT persist. Returns false (no-op) when the session wasn't read-only.\n\n```go\nfunc (s *Session) ExtraMile() bool\n```\n\n```go\nfunc (s *Session) GitStat(ctx context.Context) GitStat\n```\nGitStat computes the current working-tree diffstat. It shells out to git, so the TUI must call it OFF the render path (a tea.Cmd), cache the result, and re-run it on a throttle / at turn end — never per frame.\n\n```go\nfunc (s *Session) Intelligence(ctx context.Context, command, arg string) (string, bool)\n```\nIntelligence runs a read-only memcode command for the TUI's \"orient me\" shortcuts.\n\n```go\nfunc (s *Session) InvalidateModels()\n```\nInvalidateModels drops the Runner's control-plane snapshot (roles, byok coverage, credits state) so the next model call refetches — the hook for /login, /apikeys mutations, and anything else that changes selection inputs.\n\n```go\nfunc (s *Session) JobsRender() string\n```\nJobsRender lists the running shells (by slot) for /jobs. Finished/failed attempts aren't shown — they live in the session log, not the user's working set.\n\n```go\nfunc (s *Session) KillAllJobs()\n```\nKillAllJobs reaps every running job (session end — nothing orphans).\n\n```go\nfunc (s *Session) KillJobArg(arg string) string\n```\nKillJobArg powers /kill (and the agent's jobs-kill). The arg is a SHELL SLOT: empty stops the lone running shell (lists when several); a slot that isn't running shows what IS running instead of a dead-end.\n\n```go\nfunc (s *Session) Lanes() []provider.LaneInfo\n```\nEndpoint reports the ACTIVE custom endpoint when the session runs against an arbitrary OpenAI-compat backend instead of the memcode gateway (one-wire Phase C). ok=false on the hosted gateway, signed out, and providers without the Endpointer capability (test fakes). The TUI keys the /model picker, cost display, and login-card copy on this; the runtime keys tool gating on it. Lanes reports the attached family lanes (subscriptions + own keys), empty off the Laner seam (exclusive endpoint mode, test fakes).\n\n```go\nfunc (s *Session) LastError() error\n```\nLastError returns the terminal error of the most recent turn (nil on success). Meaningful on the synchronous one-shot path (agent -c / resumed one-shot), where a non-nil result must surface as a non-zero exit code for scripting/CI.\n\n```go\nfunc (s *Session) LastText() string\n```\nLastText returns the most recent assistant message — e.g. the just-proposed plan — so the front-end can hand it to the (stateless) advisor for review. The advisor has no session access, so without this the plan would never reach it.\n\n```go\nfunc (s *Session) Mode() permissions.Mode\n```\nMode returns the active permission mode.\n\n```go\nfunc (s *Session) Model() string\n```\nModel returns the active model id.\n\n```go\nfunc (s *Session) Orientation(ctx context.Context) Orientation\n```\nOrientation gathers the deterministic repo summary (no model call).\n\n```go\nfunc (s *Session) Personality() string\n```\nPersonality returns the chosen voice (\"\" = default).\n\n```go\nfunc (s *Session) PersonalityBlurb(ctx context.Context) string\n```\nPersonalityBlurb returns a one-line greeting in the currently-set voice (best-effort).\n\n```go\nfunc (s *Session) PersonalityResolved() string\n```\nPersonalityResolved returns the concrete voice in effect (\"\" = default): the session's random roll when personality is \"random\", else the chosen voice. Display uses this; persistence keeps the literal choice.\n\n```go\nfunc (s *Session) Pin() string\n```\nPin returns the pinned model label (\"\" = Automatic).\n\n```go\nfunc (s *Session) PlanDeferredTitles() []string\n```\nPlanDeferredTitles returns the display titles of requests currently parked until the active plan finishes, for direct presentation in the TUI's queued-request strip.\n\n```go\nfunc (s *Session) PlanGateSnapshot() (task, draft string)\n```\nPlanGateSnapshot returns the plan anchor task + pinned draft atomically — the machine's own lock covers the read (Controller.Snapshot), so it is safe from the TUI's classify goroutine while the turn goroutine pins the contract at synthesis. Callers snapshot first, then pass the copies into ClassifyPlanMessage.\n\n```go\nfunc (s *Session) PlanPhaseEpoch() (plan.Phase, int)\n```\nPlanPhaseEpoch returns the plan machine's phase and session epoch atomically — the pair the intake gate stamps on a submission so an async relevance verdict can be staleness-checked when it lands.\n\n```go\nfunc (s *Session) PlanPolicyOverride(target string) map[string]any\n```\nPlanPolicyOverride reports policy the user attached to the plan currently in flight, nil when none. It lives on the plan controller and dies with the plan.\n\n```go\nfunc (s *Session) PlanPresentable() bool\n```\nPlanPresentable reports whether the most recent plan turn actually rendered a plan to approve. The TUI gates the \"Plan ready\" approval selector on this so an interrupted plan turn (Ctrl-C on a clarifying question) never raises a selector with no plan behind it.\n\n```go\nfunc (s *Session) PlanYolo() bool\n```\nPlanYolo reports whether the current plan was started with /yolo — suppress HITL questions during planning and auto-execute the plan without showing the selector.\n\n```go\nfunc (s *Session) Planning() bool\n```\nPlanning reports whether the session is currently in plan mode.\n\n```go\nfunc (s *Session) Policy() *policy.Resolver\n```\nPolicy exposes the resolver so callers at a decision point can read it, and so the /policy view and the policy tool can show and mutate the session layer.\n\n```go\nfunc (s *Session) PolicySummary() string\n```\npolicySummary answers \"how have I customized memcode?\" — every target, its effective value, and WHERE each value came from. Per-field resolution across four layers is only comprehensible if the source is visible.\n\n```go\nfunc (s *Session) PostBackground(text string)\n```\nPostBackground queues a finished background result for the ACTIVE turn. Safe from any goroutine. The text is the same report the idle path hands over as a turn.\n\n```go\nfunc (s *Session) ProviderLabel() string\n```\nProviderLabel names WHO will serve the next turn — the footer's \"provider · model\" word before the model name. It asks the provider's router where the displayed model routes NOW (Planner), not what served last: from the first frame, and right after a /model switch, it names the lane the next turn actually takes. A subscription lane (claude-sub/codex/copilot/grok-sub) reads \"claude\" / \"codex\" / \"github\" / \"grok\" via ServingLabel; an own-key lane names its vendor plain (the footer's separate \"byok\" segment already says whose key it was). A subscription lane never sets a custom Endpoint, so this has to come first. Next a custom endpoint (an exclusive endpoint like ollama) is shown via ServingLabel; otherwise (the gateway) it falls back to the model's catalog vendor (\"anthropic\", \"openai\", …) so the hosted path still names a provider. \"\" only when nothing resolves (an unrecognized model id with no endpoint and no lane).\n\n```go\nfunc (s *Session) ReadOnlyChat() bool\n```\nReadOnlyChat reports whether the main session is currently in Read Only.\n\n```go\nfunc (s *Session) ReasoningDisplay() string\n```\nReasoningDisplay describes the effort the next call actually runs at, for the status line and footer: \"medium effort\", \"default effort\", or, when the model lacks the chosen level, \"max effort, runs as xhigh\". \"\" when the model doesn't think (no declared levels and not a reasoning model) or effort is off.\n\n```go\nfunc (s *Session) ReasoningSnippet() string\n```\nReasoningSnippet is the latest line of this turn's streamed reasoning summary (\"\" when the vendor streams none or the turn hasn't reasoned yet).\n\n```go\nfunc (s *Session) Researching() bool\n```\nResearching reports whether the session is currently in research mode.\n\n```go\nfunc (s *Session) Restricted() bool\n```\nRestricted reports whether the session is a restricted management console (admin): a limited slash whitelist, no repo/coding tools.\n\n```go\nfunc (s *Session) ReviewPlanWith(ctx context.Context, plan, model string) (string, string)\n```\nReviewPlanWith runs a ONE-SHOT plan critique on a model the USER named on the approval card (\"Review with another model\").\n\nThis is deliberately its own category: not utility inference (it is not plumbing, and the user chose it), and not routing (nothing selected it on the user's behalf). It is an explicit, user-directed second opinion, scoped to this one operation.\n\nThe chosen model runs on an ephemeral fork. The session pin, the workspace store, and the user store are untouched, the footer keeps showing the session model, and any revision the critique prompts runs back on the pinned model. Returns the critique prose and the model that produced it.\n\n```go\nfunc (s *Session) Rewind(seq int) ([]string, error)\n```\nRewind restores every file edited from checkpoint seq onward to its state before that turn ran. Returns the restored paths.\n\n```go\nfunc (s *Session) Room() room.State\n```\nRoom returns the current assessed room state (for the TUI badge / tests).\n\n```go\nfunc (s *Session) Root() string\n```\nRoot returns the project root.\n\n```go\nfunc (s *Session) Run(ctx context.Context, task string) (Result, error)\n```\nRun executes a task end-to-end and returns its metrics.\n\n```go\nfunc (s *Session) RunFollowupClassifier(ctx context.Context, sched *Scheduler, kick \u003c-chan struct{})\n```\nRunFollowupClassifier is the background loop (one goroutine per session) that drives the batched classify. kick is signaled by the front-end on each mid-turn queue submit; the loop debounces, then within followupMaxWait classifies the whole pending batch against the active task and folds the related ones into it as steers. Runs until ctx is done. The classify call runs here, OFF the scheduler's actor goroutine, so it never stalls intake.\n\n```go\nfunc (s *Session) RunPlan(ctx context.Context, task string) (string, error)\n```\nRunPlan produces a single, detailed plan for task in plan mode — research-only tools, the reasoning model, the planning prompt — and returns the plan text. It makes NO changes; the interactive TUI is where a plan is iterated on and then executed.\n\n```go\nfunc (s *Session) RunShellLine(ctx context.Context, line string) bool\n```\nRunShellLine runs a \\`$\\`/\\`\u003e\\` shell-lane line IMMEDIATELY, outside the turn scheduler — it's a LOCAL capture action (a command the user typed by hand), not an agent turn, so it must never queue behind an active turn. Reports whether the line was actually a shell route (false → the caller routes it normally through the scheduler). Safe to call concurrently with a running turn: the front-end owns its own busy/spinner state (the observer's Busy is a no-op) and command output is marshalled onto the UI thread, so a hand-run \\`$ git status\\` interleaves cleanly mid-turn.\n\n```go\nfunc (s *Session) RunTransaction(ctx context.Context, st *ChatState, tx *Transaction)\n```\nRunTransaction executes one scheduled transaction as a turn — the TUI executor's entry point. The scheduler already routed (this is an active, promoted transaction), so this just scores and runs. A \\`$\\`-prefixed transaction takes the direct-shell lane. Steers submitted into this transaction while it runs are folded in by runLoop (SetSteerDrain).\n\n```go\nfunc (s *Session) RunningJobs() int\n```\nRunningJobs is the count of live shells — the footer's \"N shells\".\n\n```go\nfunc (s *Session) RunningShells() []jobs.View\n```\nRunningShells snapshots this session's background shells that are still running — the live surface behind the footer \"N shells\" segment and the idle-row indicator. In-memory and mutex-cheap, so the TUI may call it on the render path (unlike the agent count, which polls the filesystem).\n\n```go\nfunc (s *Session) RunningSiteBuilds() []SiteBuild\n```\nRunningSiteBuilds lists the builds being watched, oldest first.\n\n```go\nfunc (s *Session) RunningSubagents() []SubagentStatus\n```\nRunningSubagents lists this session's sub-agents that are still working, oldest first.\n\n```go\nfunc (s *Session) ScratchpadDir() (string, error)\n```\nScratchpadDir returns the session-scoped scratchpad directory under $TMPDIR/memcode/\\\u003cproject-id\u003e/\\\u003csession-id\u003e/scratchpad, creating it (0700) on first use.\n\n```go\nfunc (s *Session) ServedBy() string\n```\nServedBy returns a compact label for WHO served the last call — the cheap-lane model's short name (e.g. \"glm-5p1\") when the cheap lane served it, else the model short name (\"sonnet\"/\"haiku\"). Used to tag a scout's Explore marker so you can see, per fan-out, whether it hit the cheap lane or fell back to Anthropic. \"\" if nothing served yet.\n\n```go\nfunc (s *Session) ServedByok() bool\n```\nServedByok reports whether the LAST main call served on the user's own provider key — the footer's per-turn byok segment. Strictly last-turn state: recordServed writes it unconditionally, so a non-BYOK turn clears it.\n\n```go\nfunc (s *Session) ServingModel() string\n```\nServingModel returns the model that ACTUALLY served the last main call — which differs from Model() when a turn escalates (e.g. an apply turn runs on Opus while the session default is Sonnet). The footer uses this so it reflects reality, not the static default.\n\n```go\nfunc (s *Session) SessionID() string\n```\nSessionID returns the current session id (set by Run/StartChat).\n\n```go\nfunc (s *Session) SetAdmin(exec AdminExecutor)\n```\nSetBrowserEnabled enables the browser tools (--chrome). When enabled, the browser toolset is advertised to the model and a persistent Chrome session is lazily launched on the first browser tool call — headed (a visible window, ephemeral profile) for interactive sessions, headless for gateway children (SetBrowserHeadless). The Chrome process is torn down on CloseBrowser (called at session end). SetAdmin switches this session into admin mode: the settings assistant for the gateway and agents. Admin tools only, no shell, no editor.\n\n```go\nfunc (s *Session) SetApprover(fn func(context.Context, ApprovalRequest) ApprovalDecision)\n```\nSetApprover replaces the approval callback. The TUI routes approvals through its own input instead of a separate os.Stdin reader. The callback receives a structured ApprovalRequest and returns a structured ApprovalDecision (allow / allow-with-edited-command / deny-with-reason / interrupt).\n\n```go\nfunc (s *Session) SetAsker(fn func(context.Context, AskRequest) AskResponse)\n```\nSetAsker replaces the human-in-the-loop question callback. The TUI routes ask\\_user questions through its own selector instead of stdin.\n\n```go\nfunc (s *Session) SetBrowserEnabled(enabled bool)\n```\n\n```go\nfunc (s *Session) SetBrowserHeadless(on bool)\n```\nSetBrowserHeadless makes the lazily-launched Chrome run headless — required for gateway/service children with no desktop session.\n\n```go\nfunc (s *Session) SetContext(items []ContextItem)\n```\nSetContext supplies caller-provided supplemental context for the run (agent runtime, API, CI). Injected every turn after project/user context, in the engine's fixed Kind order. The CLI and Desktop never call this, so their context is unchanged. Supplemental context is input for this run only — it does not write project memory.\n\n```go\nfunc (s *Session) SetCredentials(url, token string)\n```\nSetCredentials swaps fresh gateway credentials into the provider (the /login success path — no restart). No-op without the Connector capability.\n\n```go\nfunc (s *Session) SetDenyCommands(patterns []string)\n```\nSetDenyCommands installs the run's capability ceiling: shell command patterns it may never execute, whatever their risk and whoever approves them. Matched against the parsed AST, so wrappers and compounds cannot smuggle one past.\n\n```go\nfunc (s *Session) SetEffortOverride(level string)\n```\nSetEffortOverride sets the session's thinking effort from /effort (or a remembered config value): low, medium, high, xhigh or max on memcode's universal scale, \"default\" for the vendor's own default, or \"off\" (agents pinned to no thinking). The legacy \"auto\" and anything unrecognized become medium, memcode's default; there is no per-turn auto-selection any more.\n\n```go\nfunc (s *Session) SetExtraMCPServers(servers map[string]mcp.ServerConfig)\n```\nSetExtraMCPServers adds server configs that were NOT discovered from .mcp.json (project/user/local config) — currently used for one thing: handing this run its own chrome-devtools-mcp connection to the user's existing Chrome, after the caller has already acquired a broker lease. The caller is responsible for that lease; this only wires the resulting MCP server into the session like any other.\n\n```go\nfunc (s *Session) SetExtraMile(on bool)\n```\nSetExtraMile toggles \"extra mile\" mode: when on, a fact rides every turn and the gateway injects an above-and-beyond rule (edge cases + feature completeness) for planner/executor modes. ExtraMile reports the current state.\n\n```go\nfunc (s *Session) SetMode(m permissions.Mode)\n```\nSetMode changes the permission mode mid-session (e.g. via a \\`/mode\\` command).\n\n```go\nfunc (s *Session) SetModel(model string)\n```\nSetModel changes the model mid-session (e.g. via a \\`/model\\` command).\n\n```go\nfunc (s *Session) SetNoApprover(on bool)\n```\nSetNoApprover marks this session as having no human to answer approval prompts (a detached job child). Tools whose every use would be denied (e.g. browser\\_eval at Dangerous outside allow-all) are then not advertised at all — a tool that can never run must not be offered.\n\n```go\nfunc (s *Session) SetNoContext(v bool)\n```\nSetNoContext puts the session in cold mode (no ContextPack) — for A/B eval.\n\n```go\nfunc (s *Session) SetObserver(o UIObserver)\n```\nSetObserver attaches a UIObserver (see above). Pass nil to detach.\n\n```go\nfunc (s *Session) SetOutput(w io.Writer)\n```\nSetOutput redirects the session's RENDERED output to w — styled text, tool chrome, banners. The TUI points this at a writer that forwards bytes to the Bubble Tea program.\n\nThis is presentation. It is not the assistant's words: see UIObserver.AssistantText for those.\n\n```go\nfunc (s *Session) SetPersonality(p string)\n```\nSetPersonality sets the agent's voice (a built-in key or free-text custom voice); empty clears it back to the default. Tone only — the gateway guards it from affecting behavior. \"random\" rolls a concrete voice ONCE per session, here — so the ready line can name what the roll selected and the session speaks with one voice (a fresh roll each launch keeps the chaos; a per-request re-roll made every reply a different character and nothing displayable). Re-picking random re-rolls.\n\n```go\nfunc (s *Session) SetPin(label string, window int)\n```\nSetPin pins a concrete model for the session (the /model picker's choice): the gateway serves this model for every real request; invisible plumbing (classify/ compact) stays on the utility lanes. label is the gateway's sanitized short name (\"sonnet\", \"glm-5p2\"); \"\" = Automatic. window is the pin's context window from the picker list (0 = unknown → the SDK catalog sizes the meter). A pin change invalidates the learned lane budget/window — the next serve re-teaches them.\n\nA pin change also drops thinking/redacted\\_thinking blocks from the live chat history (if a ChatState is attached via StartChat): those blocks are provider-specific — Anthropic validates signatures it issued, and a different model (even another Anthropic tier) can't vouch for them. Replaying foreign thinking produces \"thinking blocks in the latest assistant message cannot be modified\" (a hard 400). Text and tool blocks are provider-neutral and stay.\n\n```go\nfunc (s *Session) SetPolicy(r *policy.Resolver)\n```\nSetPolicy installs the resolved policy layers for this session. Called once at the cmd boundary, where the workspace and user files are loaded.\n\n```go\nfunc (s *Session) SetReadOnly(on bool)\n```\nSetReadOnly puts the session in explorer mode: the read-only tool whitelist, no edit\\_file and no bash. This is a CAPABILITY restriction, not a permission one, and that distinction is the point — the permission gate can be argued past (the authorization judge downgrades a prompt to an allow when the request plainly asked for the action), but a tool the session was never given cannot be reached at all.\n\n```go\nfunc (s *Session) SetReadOnlyChat(on bool)\n```\nSetReadOnlyChat toggles the main session's ambient Read Only state (the Shift+Tab / \\`/mode\\` 4th stop): a hard \"nothing may mutate\" guarantee for as long as it's on. Session-scoped only — never persisted, never written to config. Distinct from SetReadOnly (a one-shot sub-agent capability gate); this is the main interactive session's own switch.\n\n```go\nfunc (s *Session) SetResume(id string)\n```\nSetResume asks the NEXT StartChat to re-enter session id with its saved history instead of minting a fresh session. Set it from the cmd layer (or a slash command) before the front-end starts the chat; StartChat consumes it.\n\n```go\nfunc (s *Session) SetRuntimeAuth(f func() runtimes.Authorizations)\n```\nSetRuntimeAuth injects the machine's runtime authorizations, used when a newly created task is trial-run. Kept as an injection because the engine must not read the gateway's configuration itself.\n\n```go\nfunc (s *Session) SetSeparateDrain(f func() (activeText string, activeTitle string, items []separateAsk))\n```\nSetSeparateDrain wires the interactive separate-task source (the transaction scheduler). runLoop calls it between tool iterations to track genuinely disparate follow-ups on the todo list instead of leaving them invisible in the queue.\n\n```go\nfunc (s *Session) SetServingDefault(model string)\n```\nSetServingDefault records the gateway's everyday (cheap-lane) model so the footer/banner show what will actually serve — instead of the CLI's bootstrap identity — before any turn has run. Set once at startup (after asking the gateway /v1/models); read under dispMu.\n\n```go\nfunc (s *Session) SetSessionID(id string)\n```\nsetSessionID assigns this Session's id AND ties the metered Runner to it, so every model call carries the session on the wire (the compat \\`user\\` field) for serving affinity + telemetry. Use this everywhere instead of writing s.sessionID directly. SetSessionID pins the session id used by the next StartChat, so a caller can control continuity itself: the gateway derives a stable id per conversation and pins it, and StartChat then does resume-or-create under that id instead of minting a fresh one. (Distinct from a leftover sessionID between two chats on one Session, which must still mint a new id.)\n\n```go\nfunc (s *Session) SetSharedAudience(on bool)\n```\nSetSharedAudience marks a run whose answer is read by a group (a gateway job from a group chat): people the workspace's allow-list never authorized. Publishing anything (artifacts, websites, share links) is refused outright, whatever the mode or a remembered approval, and the agent is told who reads its reply.\n\n```go\nfunc (s *Session) SetSkillRoots(roots []string)\n```\nSetSkillRoots supplies caller-provided EXTRA skill discovery roots (e.g. a gateway agent's own skills dir). They rank between repo-local and user-global skills, so an agent can carry capabilities without editing the project or the user's global skill set. Empty for the CLI and Desktop.\n\n```go\nfunc (s *Session) SetSteerDrain(f func() []string)\n```\nSetSteerDrain wires the interactive steer source (the transaction scheduler). runLoop calls it between tool iterations to fold mid-turn \\`+steer\\` input into the active turn.\n\n```go\nfunc (s *Session) SetStreamIdleForTest(idle time.Duration)\n```\nSetStreamIdleForTest backdates the in-flight call's last-chunk timestamp for TUI tests.\n\n```go\nfunc (s *Session) SetTaskAttachments(atts []input.Attachment)\n```\nSetTaskAttachments supplies caller-resolved attachments for the NEXT submitted turn (a gateway job carrying channel media — a photo texted to the bot, a PDF emailed to it). They merge into that turn's bundle and ride the normal attachment path (caps, downscaling, wire blocks), then clear.\n\n```go\nfunc (s *Session) SetToolNotify(fn func(label string))\n```\nSetToolNotify installs a callback invoked once per tool call with a short human label (\"bash(go test ./...)\", \"read\\_file(internal/sync.go)\"). It is a lightweight activity tap for frontends that surface what a detached agent is doing right now (the job heartbeat); unlike toolLine it fires for quiet tools too. Nil detaches. Set before the session runs; not for mid-turn swaps.\n\n```go\nfunc (s *Session) SetToolPolicy(allow, deny []string) (unknown []string)\n```\nSetToolPolicy restricts the session to the given toolsets/tools (allow; empty = all) minus disabled ones (deny wins) — the gateway applies an agent's configured policy here. Unknown entries are reported, not silently dropped.\n\n```go\nfunc (s *Session) SetWidth(w int)\n```\nSetWidth records the terminal width so rendered diffs can fill the full row with a background. The TUI calls this on resize.\n\n```go\nfunc (s *Session) SignedIn() bool\n```\nSignedIn reports whether the session is signed in to memcode itself (the hosted gateway), as opposed to Connected, which is also true on an attached subscription lane or a custom endpoint. Providers without the seam (test fakes) answer like Connected.\n\n```go\nfunc (s *Session) SitePreviewURL(ctx context.Context, siteID string) (string, error)\n```\nSitePreviewURL mints a fresh preview link for a site. It carries a private access token, so it is for opening in the user's browser or showing to the user, not for the model's context.\n\n```go\nfunc (s *Session) Spend() (in, out, cacheRead, cacheWrite int, usd float64)\n```\nSpend returns the session's token breakdown and estimated cost in USD (priced per response under each call's model; rates are approximate). Powers /cost.\n\n```go\nfunc (s *Session) SpendByBackend() []ledger.BackendSpend\n```\nSpendByBackend returns per-backend usage, busiest first. One entry (\"anthropic\") in a classic session; two once the hybrid router is live.\n\n```go\nfunc (s *Session) SpendByPurpose() []ledger.PurposeSpend\n```\nSpendByPurpose returns per-purpose usage, most expensive first — so /cost can show where the money actually went (e.g. explore scouts vs the main loop vs synthesis).\n\n```go\nfunc (s *Session) StartChat(ctx context.Context) *ChatState\n```\nStartChat begins an interactive session: assigns a session id, loads remembered approvals, records the start event, and builds the system prompt. Pump input with Submit; finish with EndChat. When SetResume was called, the saved transcript is re-entered instead of minting a fresh session — the episodic log appends to the same session dir, so memory stays one thread.\n\n```go\nfunc (s *Session) StreamIdle() time.Duration\n```\nStreamIdle returns how long the current in-flight model call has gone without receiving a streamed chunk (0 when no call is in flight).\n\n```go\nfunc (s *Session) Submit(ctx context.Context, st *ChatState, line string)\n```\nSubmit routes one raw input line and runs the resulting turn(s) to completion, draining any queued follow-ups. Output streams to the session writer; approvals go through the session approver. Blank lines are ignored.\n\n```go\nfunc (s *Session) Sync(ctx context.Context, targets []config.SyncTarget) (string, error)\n```\nSync regenerates the project overview and writes it to the selected AI-editor context files. It mirrors the \\`memcode sync\\` CLI pipeline (cmd/sync.go) but runs against the live session's store/runner/root — so the interactive /sync command needs no separate process. targets is the user's pick from the picker (empty + Everything=false means \"nothing configured\"); the overview is synthesized deterministically from repo facts, so this works without a model call.\n\n```go\nfunc (s *Session) SyncDetect() []memsync.DetectedTarget\n```\nSyncDetect scans the project root for known AI-editor context files (CLAUDE.md, AGENTS.md, .github/copilot-instructions.md, …) and reports which exist on disk and which are already managed by memcode. The /sync picker calls this to show the grid of toggleable targets before the user picks.\n\n```go\nfunc (s *Session) TailJobArg(arg string) string\n```\nTailJobArg powers /tail: the arg is a shell slot; empty tails the lone running shell.\n\n```go\nfunc (s *Session) TakeBackground() []string\n```\nTakeBackground removes and returns every background result not yet delivered. The loop calls it at its safe boundary; the frontend calls it after a turn ends, to start a turn for results the finished turn never reached.\n\n```go\nfunc (s *Session) TaskShapeClassifier() func(context.Context, taskdetect.Turn) (taskdetect.Proposal, bool, error)\n```\nTaskShapeClassifier exposes the live classifier so it can be evaluated against labelled cases. Every other test scripts this, which proves the pipeline and says nothing about the judgement.\n\n```go\nfunc (s *Session) ThinkingEffort() string\n```\nThinkingEffort returns the current turn's thinking-effort label for the status line (\"low\"/\"medium\"/\"high\"/…), or \"\" when thinking is off (so the spinner shows it only while the model is actually thinking).\n\n```go\nfunc (s *Session) Tokens() (in, out int)\n```\nTokens returns cumulative session token flow: total input the model saw (uncached + cache reads) and total output. Footer \"↑in ↓out\".\n\n```go\nfunc (s *Session) TurnText() (text string, spoke bool)\n```\nTurnText is what the model said during the CURRENT turn, and whether it said anything at all.\n\nDistinct from LastText, which is the newest non-empty reply anywhere in the session. A turn that spent every iteration on tool calls answered nothing, and reporting the previous turn's words as this turn's result is how a consumer ends up acting on a stale answer. spoke=false says \"no answer\" out loud so the caller can treat it as the incomplete run it is.\n\n```go\ntype ShellReportBack struct {\n\tCommand string\n\tExit    int\n\tFailed  bool\n\tOutput  string\n}\n```\nShellReportBack is a promoted foreground command that has finished and owes its result back to the model (redacted, ready to inject as a new turn). Identified by command, not shell slot — a finished job holds no slot.\n\n```go\nfunc (b ShellReportBack) ReportPrompt() string\n```\nReportPrompt renders a finished background shell (started or promoted) as the turn text handed to the model.\n\n```go\ntype SiteBuild struct {\n\tSlug    string\n\tStarted time.Time\n}\n```\nSiteBuild is a build the session is watching, for the status bar.\n\n```go\ntype SiteBuildReport struct {\n\tSlug    string\n\tSiteID  string\n\tFailed  bool\n\tDetail  string // the build's summary, or its error\n\tTook    time.Duration\n\tUnknown bool // the watch gave up; the outcome is not known\n}\n```\nSiteBuildReport is a watched build that finished (or was given up on).\n\n```go\ntype SteerEvent struct {\n\tText string\n\tAt   time.Time\n}\n```\nSteerEvent is a \\`+input\\` the user submitted while a transaction was active: recorded immediately, then folded into the SAME transaction at the next safe boundary in runLoop (after tool\\_results, before the next model call). It cannot affect an in-flight model call — that is what cancel is for.\n\n```go\ntype SubagentStatus struct {\n\tLabel, Task string\n\tElapsed     time.Duration\n\tTools       int\n}\n```\nSubagentStatus is one running sub-agent for the TUI: what it is, what it was asked, how long it has run and how many tools it has used so far.\n\n```go\ntype Transaction struct {\n\tID        string // \"tx_\u003cn\u003e\" — unique within a session, deterministic for tests\n\tText      string // the user intent (paste-expanded, routing marker stripped)\n\tResearch  bool   // request-scoped /research turn\n\tState     TxState\n\tCreatedAt time.Time\n\tStartedAt time.Time\n\tEndedAt   time.Time\n\n\tResult TransactionResult\n\t// contains filtered or unexported fields\n}\n```\nTransaction is the unit the scheduler manages. steers is unexported because it is mutated only through schedState (actor-serialized); everything else is read-only once the transaction is created, except the lifecycle fields the scheduler advances.\n\n```go\ntype TransactionResult struct {\n\tState TxState\n\tErr   string\n}\n```\nTransactionResult is a transaction's outcome. v1 records only the terminal state and any error; the commented fields are the deliberate seam for Phase-3 undo (revert a completed transaction's edits via git/patch) — shaped now so it attaches cleanly later.\n\n```go\ntype TxState string\n```\nTxState is the explicit lifecycle of a Transaction. Transitions are owned by the scheduler state core (schedState) and serialized by the actor; nothing mutates a transaction's state from two goroutines.\n\n```go\nconst (\n\tTxQueued     TxState = \"queued\"     // accepted while another was active; inert (no ChatState yet)\n\tTxRunning    TxState = \"running\"    // the active transaction; the only writer of ChatState\n\tTxCancelling TxState = \"cancelling\" // Esc/Ctrl-C requested; unwinding\n\tTxCompleted  TxState = \"completed\"  // finished normally (terminal)\n\tTxFailed     TxState = \"failed\"     // errored (terminal)\n\tTxCancelled  TxState = \"cancelled\"  // aborted before completion (terminal)\n)\n```\n\n```go\ntype UIObserver interface {\n\t// Routed reports how a submitted line was classified.\n\tRouted(route input.Route, reason string)\n\t// QueueChanged reports the current queued-task texts (most-recent last).\n\tQueueChanged(items []string)\n\t// Busy reports whether a turn is actively running.\n\tBusy(busy bool)\n\t// Mood reports the running interaction-friction reading (for the TUI gauge).\n\tMood(r mood.Reading)\n\t// Room reports the assessed room state (mode/intent/policy) for the TUI badge.\n\tRoom(s room.State)\n\t// Todos reports the agent's current work-tracker checklist (the live region).\n\tTodos(list todos.List)\n\t// Tokens reports the running output-token count for the current turn (the ↓\n\t// counter): a live estimate between the API's usage events, snapped to the\n\t// authoritative value when it arrives.\n\tTokens(output int)\n\t// Raw prints a block VERBATIM into scrollback — no markdown/prose processing,\n\t// internal whitespace and blank lines preserved exactly. Used by the `$`\n\t// direct-shell lane so command output is high-fidelity terminal output, not an\n\t// assistant-rendered artifact.\n\tRaw(text string)\n\t// AssistantText reports what the MODEL said, once per response, before any\n\t// rendering. This is the semantic channel: a protocol consumer deciding what\n\t// the assistant actually replied reads this, never the byte stream handed to\n\t// SetOutput, which carries ANSI, tool chrome and routing lines.\n\tAssistantText(text string)\n\t// Tool reports that a tool ran: its name, what it acted on, and how it\n\t// finished (\"ok\" | \"warning\" | \"failed\"). Fires for EVERY tool, including\n\t// the quiet tier the terminal declines to draw — whether a line appears in\n\t// scrollback is a rendering decision, and a client building its own tool UI\n\t// is asking a different question.\n\tTool(name, target, status string)\n}\n```\nUIObserver lets a front-end (the TUI) observe the interactive session's routing and lifecycle without scraping stdout. Every method is optional — the runtime nil-checks before calling — so a headless caller can ignore it. This is a tap on the existing event points in Submit, NOT a change to the agent loop itself.\n\n","path":"github.com/memcode-ai/memcode/internal/agent/runtime","name":"runtime","synopsis":"Package runtime: this file is the thin seam to the read-only intelligence Engine (internal/agent/introspect).","isRedistributable":true}
