// The application core. It owns the current agent session and decides what a submitted line means: a prompt, a slash command, // a shell command, or a steering/queued message while the agent works. It has no terminal I/O; it talks to the outside only // through the Transcript (what to show) and the Surface (what only a screen can do). import { openAgentSession } from "./agent-session.ts"; import type { AgentSession, AgentSessionFactory, AgentSessionRequest } from "./agent-session.ts"; import type { Settings } from "./config.ts"; import { expandMentions } from "./mentions.ts"; import { nextPermission } from "./permissions.ts"; import type { PermissionName } from "./permissions.ts"; import { allProviders, chooseProvider } from "./providers.ts"; import { createRunDriver } from "./run-driver.ts"; import type { PendingMessage, RunDriver, RunOutcome } from "./run-driver.ts"; import { sessionLabel, titleFromPrompt } from "./session-store.ts"; import type { SessionMeta, SessionStore } from "./session-store.ts"; import { runShell } from "./shell.ts"; import type { ShellRunner } from "./shell.ts"; import { findCommand, parseSlash } from "./slash-commands.ts"; import { createCommandHost } from "./command-host.ts"; import type { Choice } from "./command-host.ts"; import { measureContext } from "./context-estimate.ts"; import { contextLeftPercent } from "./status-line.ts"; import type { StatusInfo } from "./status-line.ts"; import { createPersister, createScheduler, outcomeOfRun, promptFor, readScheduleState, SCHEDULE_ENTRY, systemClock } from "./schedule.ts"; import type { Clock } from "./schedule.ts"; import { schedulePlugin } from "./schedule-tool.ts"; import { excerpt, replayLog } from "./transcript.ts"; import type { Transcript } from "./transcript.ts"; import type { Content, ContextStatus, Environment, RunResult, UserInput } from "./framework.ts"; import { imageMediaType } from "./images.ts"; import { MIN_COMPACT_TOKENS } from "./idle-compaction.ts"; import { isThinkingLevel } from "./framework.ts"; import type { ThinkingLevel } from "./framework.ts"; /** What only a screen can do. The TUI implements it with painting, tests with arrays. */ export interface Surface { /** Something that the status line or the live area shows has changed. */ changed(): void; pickSession(sessions: SessionMeta[]): Promise; pickThinking?(levels: readonly ThinkingLevel[], current: ThinkingLevel | undefined): Promise; clearScreen(): void; /** Puts text into the prompt (for /undo). */ prefill(text: string): void; /** The user has text in the composer (a scheduled prompt waits while it is true). */ typing?(): boolean; exit(): void; } export interface ControllerDeps { settings: Settings; cwd: string; home: string | undefined; env: Record; store: SessionStore; transcript: Transcript; surface: Surface; openSession?: AgentSessionFactory; runShell?: ShellRunner; /** Image files for the first prompt (`--image`). */ images?: string[]; /** Ready-made model clients instead of a provider (scripted tests). */ clients?: AgentSessionRequest["clients"]; requestApproval?: AgentSessionRequest["requestApproval"]; /** Where the tools run when it is not this machine (`--ssh`, `--docker`). */ makeEnvironment?: () => Promise; /** Time for scheduled prompts (tests move it by hand). */ clock?: Clock; } export interface StartOptions { /** A session id, prefix, file path or "last". */ resume?: string; } export interface Controller { start(options?: StartOptions): Promise; /** `mode` is what Enter (steer) or Tab (queue) means while the agent is working. */ submit(text: string, mode?: "steer" | "queue"): Promise; /** Sends a prompt and waits for the run (and any follow-up of undelivered messages) to end. */ runPrompt(text: string): Promise; cancel(): void; /** Compacts when the context holds at least `minTokens`; says whether it did. One dim line tells the user. */ compactIdle(minTokens: number, idleMinutes: number): Promise; /** Shift+Tab: the next permission mode (see `nextPermission`). During a run it is only remembered and applied when the run ends. */ cyclePermissions(): Promise; readonly driver: RunDriver; statusInfo(): StatusInfo; pending(): readonly PendingMessage[]; current(): AgentSession | undefined; currentMeta(): SessionMeta | undefined; close(): Promise; } const thousands = (tokens: number) => (tokens < 1000 ? String(tokens) : `${Math.round(tokens / 1000)}k`); export function createController(deps: ControllerDeps): Controller { const { transcript, surface, store } = deps; const openSession = deps.openSession ?? openAgentSession; const shell = deps.runShell ?? runShell; const driver = createRunDriver(transcript); let session: AgentSession | undefined; let meta: SessionMeta | undefined; let contextPercent: number | undefined; // a mode asked for during a run; the agent is not reopened while it works let pendingPermissions: PermissionName | undefined; let contextEstimated = false; let contextEstimatedShown = false; let contextWindow = 0; // a newer measurement wins over an older one that finishes later let contextVersion = 0; const firstImages = [...(deps.images ?? [])]; let choice: Choice = { provider: deps.clients ? "scripted" : chooseProvider(deps.settings, deps.env), model: deps.settings.model, permissions: deps.settings.permissions, redaction: deps.settings.redaction, thinking: deps.settings.thinking, }; driver.onChange(() => surface.changed()); // The percentage follows the run: each finished reply carries the provider-reported usage, and a compaction changes the size at once. driver.onEvent((event) => { if (event.type === "message_end" && event.message.role === "assistant" && event.message.usage && contextWindow > 0) { const { input, output, cacheRead, cacheWrite } = event.message.usage; contextVersion++; contextEstimated = false; setContextPercent(contextLeftPercent(contextWindow - (input + output + cacheRead + cacheWrite), contextWindow)); } else if (event.type === "compaction") { void refreshContext().catch(() => undefined); } }); const notice = (level: "info" | "warn" | "error", text: string) => transcript.add({ kind: "notice", level, text }); const requireSession = (): AgentSession => { if (!session) throw new Error("no session is open"); return session; }; // ---------- opening and closing ---------- async function open(target: SessionMeta, next: Choice): Promise { const opened = await openSession({ settings: deps.settings, provider: next.provider, model: next.model, sessionId: target.id, sessionFile: store.sessionFile(target.id), cwd: deps.cwd, permissions: next.permissions, requestApproval: deps.requestApproval, redaction: next.redaction, thinking: next.thinking, maxTokens: deps.settings.maxTokens, timeLimitSeconds: deps.settings.timeLimitSeconds, env: deps.env, onRetry: (message) => notice("warn", message), extraPlugins: [schedulePlugin(scheduler)], ...(deps.makeEnvironment ? { makeEnvironment: deps.makeEnvironment } : {}), ...(deps.clients ? { clients: deps.clients } : {}), }); session = opened; // the jobs belong to the conversation: another session brings its own (a change of model or permissions keeps them) if (scheduleLoadedFor !== target.id) { scheduleLoadedFor = target.id; scheduler.load(readScheduleState(await opened.agent.log.branch())); } choice = { ...next, model: opened.model, thinking: opened.thinking }; meta = await store.update(target.id, { provider: next.provider, model: opened.model, thinking: opened.thinking, manualApproval: next.permissions === "manual" }); await refreshContext(); surface.changed(); } async function closeCurrent(options: { discardIfEmpty: boolean }): Promise { if (!session || !meta) return; const closing = meta; await session.close(); session = undefined; if (options.discardIfEmpty && closing.title === undefined) await store.remove(closing.id); } /** Reopens the current session with other settings; if that fails the old settings are restored. */ async function reopen(patch: Partial): Promise { if (!meta) return false; const previous = choice; const target = meta; await closeCurrent({ discardIfEmpty: false }); try { await open(target, { ...previous, ...patch }); return true; } catch (error) { notice("error", `Could not switch: ${(error as Error).message}`); await open(target, previous); return false; } } async function startFresh(): Promise { const created = await store.create({ cwd: deps.cwd, provider: choice.provider, model: choice.model ?? "" }); await open(created, choice); } async function switchTo(target: SessionMeta): Promise { await closeCurrent({ discardIfEmpty: true }); const known = target.provider in allProviders(deps.settings) || deps.clients !== undefined; const keyed = deps.clients !== undefined || Boolean(deps.env[allProviders(deps.settings)[target.provider]?.keyEnv ?? ""]); const provider = known && keyed && deps.settings.provider === undefined ? target.provider : choice.provider; const next: Choice = { ...choice, provider, model: deps.settings.model ?? (provider === target.provider ? target.model : undefined) }; const definition = allProviders(deps.settings)[next.provider]; const sameModel = next.provider === target.provider && (next.model ?? definition?.model) === target.model; const thinking = deps.settings.thinking ?? (sameModel && isThinkingLevel(target.thinking) ? target.thinking : undefined); transcript.reset(); await open(target, { ...next, thinking, ...(target.manualApproval ? { permissions: "manual" as const } : {}) }); const entries = await requireSession().agent.log.branch(); replayLog(transcript, entries); notice("info", `Resumed ${sessionLabel(meta ?? target)} (${target.id.slice(0, 8)}).`); } async function statusContext(active: AgentSession): Promise<{ context: ContextStatus; contextEstimated: boolean }> { const status = await active.agent.context(); const measured = await measureContext(active.agent); return { context: { ...status, tokens: measured.tokens, free: Math.max(0, measured.window - measured.tokens) }, contextEstimated: measured.estimated }; } function setContextPercent(next: number): void { const flagChanged = contextEstimatedShown !== contextEstimated; contextEstimatedShown = contextEstimated; if (next === contextPercent && !flagChanged) return; contextPercent = next; surface.changed(); } async function refreshContext(): Promise { if (!session) return; const version = ++contextVersion; const measured = await measureContext(session.agent); if (version !== contextVersion) return; contextWindow = measured.window; contextEstimated = measured.estimated; setContextPercent(contextLeftPercent(measured.window - measured.tokens, measured.window)); } // ---------- running ---------- async function runInput(input: UserInput | undefined, options?: { compact?: boolean }): Promise { const active = requireSession(); let next: UserInput | undefined = input; let outcome: RunOutcome; for (;;) { outcome = await driver.run(active.agent, next, options?.compact ? { compact: true } : undefined); reportEnd(outcome.result); await refreshContext(); if (outcome.leftover.length === 0 || outcome.result.reason !== "done") break; next = outcome.leftover.map((item) => item.text).join("\n\n"); options = undefined; } if (meta) meta = await store.update(meta.id, {}); await applyPendingPermissions(); persister.flush(); scheduler.poke(); return outcome.result; } async function applyPendingPermissions(): Promise { const wanted = pendingPermissions; pendingPermissions = undefined; if (wanted === undefined || wanted === choice.permissions) return surface.changed(); if (await reopen({ permissions: wanted })) notice("info", `Permissions: ${wanted} (Shift+Tab to change)`); surface.changed(); } function reportEnd(result: RunResult) { if (result.reason === "error") notice("error", `The run failed: ${result.error ?? "unknown error"}`); else if (result.reason === "paused" && result.pause === "approval") notice("warn", "The run was paused because too many actions were refused. Send a message to continue."); } // Between "a prompt was submitted" and "the driver is working" there are a few awaits; a second line typed in that // moment must wait for the run to exist, or it would start a second run. let launching: Promise | undefined; async function startPrompt(text: string): Promise { let ready!: () => void; launching = new Promise((resolve) => (ready = resolve)); try { if (meta && meta.title === undefined) meta = await store.update(meta.id, { title: titleFromPrompt(text) }); const mentions = await expandMentions(text, deps.cwd, deps.home); const images = [...firstImages.splice(0), ...mentions.images]; const body = mentions.text; const running = runInput( images.length === 0 ? body : [{ type: "text", text: body }, ...images.map((path): Content => ({ type: "image", mediaType: imageMediaType(path) ?? "image/png", ref: path }))], ); // driver.run marks the driver as working before its first await launching = undefined; ready(); return await running; } finally { launching = undefined; ready(); } } // ---------- scheduled prompts ---------- const persister = createPersister({ append: async (state) => void (await session?.agent.log.append({ type: "custom", customType: SCHEDULE_ENTRY, data: state })), busy: () => driver.working || launching !== undefined, }); const scheduler = createScheduler({ settings: deps.settings.schedule, clock: deps.clock ?? systemClock, busy: () => !session || driver.working || launching !== undefined, typing: () => surface.typing?.() ?? false, fire: async (job) => outcomeOfRun(await startPrompt(promptFor(job))), save(state) { persister.save(state); surface.changed(); }, notify: (text) => notice("info", text), }); let scheduleLoadedFor: string | undefined; async function runShellForUser(command: string): Promise { const result = await shell(command, deps.cwd); const { lines, hidden } = excerpt(result.output, 40); transcript.add({ kind: "shell", command, output: lines, hidden, exitCode: result.exitCode }); } // ---------- the commands ---------- const host = createCommandHost({ deps, shell, driver, scheduler, notice, requireSession, meta: () => meta, setMeta: (next) => { meta = next; }, choice: () => choice, clearPendingPermissions: () => { pendingPermissions = undefined; }, reopen, closeCurrent, open, startFresh, switchTo, refreshContext, runInput, startPrompt, statusContext, }); // ---------- the public side ---------- async function dispatchSlash(name: string, args: string): Promise { const command = findCommand(name); if (!command) return notice("error", `Unknown command /${name}. Type /help for the list.`); if (driver.working && !command.duringRun) return notice("warn", `/${command.name} cannot be used while the agent is working. Press Esc to cancel the run first.`); try { await command.run(args, host); } catch (error) { notice("error", `/${command.name} failed: ${(error as Error).message}`); } surface.changed(); } return { driver, async start(options = {}) { if (options.resume !== undefined) { const target = await store.find(options.resume, options.resume === "last" ? { cwd: deps.cwd } : {}); const found = target ?? (options.resume === "last" ? (await store.list())[0] : undefined); if (!found) throw new Error(`No session matches "${options.resume}".`); await switchTo(found); } else await startFresh(); }, async submit(raw, mode = "steer") { const text = raw.trim(); if (text === "") return; const slash = parseSlash(text); if (slash) return dispatchSlash(slash.name, slash.args); if (text.startsWith("!") && text.length > 1 && !text.startsWith("!!")) return runShellForUser(text.slice(1).trim()); if (launching) await launching; if (driver.working) { const mentioned = await expandMentions(text, deps.cwd, deps.home); const expanded = mentioned.images.length === 0 ? mentioned.text : `${mentioned.text}\nImage files (open them with the read tool):\n${mentioned.images.map((path) => `- ${path}`).join("\n")}`; if (mode === "queue") driver.queue(expanded); else driver.steer(expanded); return; } await startPrompt(text); }, runPrompt: (text) => startPrompt(text), cancel: () => driver.cancel(), async compactIdle(minTokens, idleMinutes) { if (!session || driver.working || launching) return false; const active = session; const before = (await active.agent.context()).tokens; if (session !== active || driver.working || launching) return false; if (before < Math.max(MIN_COMPACT_TOKENS, minTokens)) return false; let compacted = false; const stop = driver.onEvent((event) => { if (event.type === "compaction") compacted = true; }); transcript.muteCompaction(true); try { const result = await runInput(undefined, { compact: true }); if (result.reason !== "done" || !compacted) return false; } finally { transcript.muteCompaction(false); stop(); } const after = (await measureContext(requireSession().agent)).tokens; notice("info", `compacted after ${idleMinutes} min idle, ${thousands(before)} to ${thousands(after)} tokens`); return true; }, async cyclePermissions() { const next = nextPermission(pendingPermissions ?? choice.permissions); if (driver.working || launching) { pendingPermissions = next === choice.permissions ? undefined : next; return surface.changed(); } if (!session) return; if (await reopen({ permissions: next })) notice("info", `Permissions: ${next} (Shift+Tab to change)`); surface.changed(); }, statusInfo: () => ({ provider: choice.provider, model: choice.model ?? "", thinking: session?.thinking, cwd: deps.cwd, home: deps.home, contextLeftPercent: contextPercent, contextEstimated: contextEstimatedShown, permissions: choice.permissions, pendingPermissions, redaction: choice.redaction, working: driver.working, queued: driver.pending().length, scheduled: scheduler.active(), }), pending: () => driver.pending(), current: () => session, currentMeta: () => meta, async close() { scheduler.close(); await closeCurrent({ discardIfEmpty: true }); }, }; }