@@ -21,6 +21,7 @@ import { snapshotBeforeEdit } from "../tools/snapshot.ts";
2121 import { extractAssistantText, makeInterruptMessage } from "./agent-helpers.ts";
2222 import type { AgentReporter } from "./reporter.ts";
2323 import { buildSystemPrompt } from "./system-prompt.ts";
24+import { undoLastTurn } from "./undo-snapshot.ts";
2425
2526 interface SessionRunnerOptions {
2627 cwd: string;
@@ -41,11 +42,23 @@ interface SessionRunnerOptions {
4142 killSubprocesses?: (() => void) | undefined;
4243 }
4344
45+interface RunnerStatusInfo {
46+ model: string;
47+ sessionId: string;
48+ thinkingEffort: ThinkingEffort | null;
49+ showReasoning: boolean;
50+ totalIn: number;
51+ totalOut: number;
52+ lastContextTokens: number;
53+}
54+
4455 export class SessionRunner {
45- public cwd: string;
46- public reporter: AgentReporter;
47- public tools: ToolDef[];
48- public mcpTools: ToolDef[];
56+ public readonly cwd: string;
57+ public readonly reporter: AgentReporter;
58+ public readonly tools: ToolDef[];
59+ public readonly mcpTools: ToolDef[];
60+
61+ // ─── Mutable settings (updated via cmdCtx) ────────────────────────────────
4962 public currentModel: string;
5063 public currentThinkingEffort: ThinkingEffort | null;
5164 public showReasoning: boolean;
@@ -55,58 +68,21 @@ export class SessionRunner {
5568 public openaiPromptCacheRetention: "in_memory" | "24h";
5669 public googleCachedContent: string | null;
5770
71+ // ─── Session state ─────────────────────────────────────────────────────────
5872 public session!: ActiveSession;
59- public sessionTimeAnchor!: string;
60- public coreHistory!: CoreMessage[];
61- public turnIndex = 1;
62- public snapshotStack: Array<number | null> = [];
63- public currentSnappedPaths: Set<string> | null = null;
64- public currentTurn: number | null = null;
65-
66- public async snapshotCallback(filePath: string) {
67- if (this.currentTurn !== null && this.currentSnappedPaths !== null) {
68- this.reporter.renderSubState("snapshot");
69-
70- await snapshotBeforeEdit(
71- this.cwd,
72- this.session.id,
73- this.currentTurn,
74- filePath,
75- this.currentSnappedPaths,
76- );
77- }
78- }
7973
80- public totalIn = 0;
81- public totalOut = 0;
82- public lastContextTokens = 0;
83- // Cache the system prompt so the file-system reads in buildSystemPrompt
84- // (context files, skills index) are not repeated on every processUserInput call.
74+ // ─── Internal state ────────────────────────────────────────────────────────
75+ private sessionTimeAnchor!: string;
76+ private coreHistory!: CoreMessage[];
77+ private turnIndex = 1;
78+ private snapshotStack: Array<number | null> = [];
79+ private currentSnappedPaths: Set<string> | null = null;
80+ private currentTurn: number | null = null;
81+ private totalIn = 0;
82+ private totalOut = 0;
83+ private lastContextTokens = 0;
8584 private _extraSystemPrompt: string | undefined;
8685 private _systemPrompt: string | undefined;
87-
88- public get extraSystemPrompt(): string | undefined {
89- return this._extraSystemPrompt;
90- }
91-
92- public set extraSystemPrompt(value: string | undefined) {
93- this._extraSystemPrompt = value;
94- this.rebuildSystemPrompt();
95- }
96-
97- private rebuildSystemPrompt(): void {
98- if (!this.sessionTimeAnchor) {
99- this._systemPrompt = undefined;
100- return;
101- }
102- this._systemPrompt = buildSystemPrompt(
103- this.sessionTimeAnchor,
104- this.cwd,
105- this._extraSystemPrompt,
106- this.isSubagent,
107- );
108- }
109-
11086 private isSubagent: boolean | undefined;
11187 private killSubprocesses: (() => void) | undefined;
11288
@@ -129,6 +105,47 @@ export class SessionRunner {
129105 this.initSession(opts.sessionId);
130106 }
131107
108+ // ─── Public accessors ──────────────────────────────────────────────────────
109+
110+ public get extraSystemPrompt(): string | undefined {
111+ return this._extraSystemPrompt;
112+ }
113+
114+ public set extraSystemPrompt(value: string | undefined) {
115+ this._extraSystemPrompt = value;
116+ this.rebuildSystemPrompt();
117+ }
118+
119+ /** Returns the data needed to render the status bar. */
120+ public getStatusInfo(): RunnerStatusInfo {
121+ return {
122+ model: this.currentModel,
123+ sessionId: this.session.id,
124+ thinkingEffort: this.currentThinkingEffort,
125+ showReasoning: this.showReasoning,
126+ totalIn: this.totalIn,
127+ totalOut: this.totalOut,
128+ lastContextTokens: this.lastContextTokens,
129+ };
130+ }
131+
132+ // ─── Snapshot callback (used by tools) ────────────────────────────────────
133+
134+ public async snapshotCallback(filePath: string) {
135+ if (this.currentTurn !== null && this.currentSnappedPaths !== null) {
136+ this.reporter.renderSubState("snapshot");
137+ await snapshotBeforeEdit(
138+ this.cwd,
139+ this.session.id,
140+ this.currentTurn,
141+ filePath,
142+ this.currentSnappedPaths,
143+ );
144+ }
145+ }
146+
147+ // ─── Session lifecycle ─────────────────────────────────────────────────────
148+
132149 public initSession(sessionId?: string) {
133150 if (sessionId) {
134151 const resumed = resumeSession(sessionId);
@@ -150,7 +167,6 @@ export class SessionRunner {
150167 // Model-authored messages must remain byte-for-byte equivalent in structure
151168 // (including providerOptions/providerMetadata thought-signature fields and
152169 // part ordering); do not reconstruct tool-call history on resume.
153-
154170 this.sessionTimeAnchor = new Date(this.session.createdAt).toISOString();
155171 this.coreHistory = [...this.session.messages];
156172 this.rebuildSystemPrompt();
@@ -169,6 +185,42 @@ export class SessionRunner {
169185 this.snapshotStack.length = 0;
170186 }
171187
188+ // ─── Shell passthrough ─────────────────────────────────────────────────────
189+
190+ /**
191+ * Persist a shell command's output as a user message so the LLM has context.
192+ * Called by input-loop.ts after a `!cmd` passthrough.
193+ */
194+ public addShellContext(command: string, output: string): void {
195+ const thisTurn = this.turnIndex++;
196+ const msg: CoreMessage = {
197+ role: "user",
198+ content: `Shell output of \`${command}\`:\n\`\`\`\n${output}\n\`\`\``,
199+ };
200+ this.session.messages.push(msg);
201+ saveMessages(this.session.id, [msg], thisTurn);
202+ this.coreHistory.push(msg);
203+ this.snapshotStack.push(null);
204+ }
205+
206+ // ─── Undo ──────────────────────────────────────────────────────────────────
207+
208+ public async undoLastTurn(): Promise<boolean> {
209+ return undoLastTurn({
210+ session: this.session,
211+ coreHistory: this.coreHistory,
212+ snapshotStack: this.snapshotStack,
213+ getTurnIndex: () => this.turnIndex,
214+ setTurnIndex: (idx) => {
215+ this.turnIndex = idx;
216+ },
217+ cwd: this.cwd,
218+ reporter: this.reporter,
219+ });
220+ }
221+
222+ // ─── Main turn processing ──────────────────────────────────────────────────
223+
172224 public async processUserInput(
173225 text: string,
174226 pastedImages: ImageAttachment[] = [],
@@ -182,27 +234,25 @@ export class SessionRunner {
182234 killSubs();
183235 });
184236 }
185- const allImages = [...pastedImages];
186- const thisTurn = this.turnIndex++;
187237
238+ const thisTurn = this.turnIndex++;
188239 this.currentTurn = thisTurn;
189240 this.currentSnappedPaths = new Set<string>();
190- const coreContent = text;
191241
192242 const userMsg: CoreMessage =
193- allImages.length > 0
243+ pastedImages.length > 0
194244 ? {
195245 role: "user",
196246 content: [
197- { type: "text", text: coreContent },
198- ...allImages.map((img) => ({
247+ { type: "text", text },
248+ ...pastedImages.map((img) => ({
199249 type: "image" as const,
200250 image: img.data,
201251 mediaType: img.mediaType,
202252 })),
203253 ],
204254 }
205- : { role: "user", content: coreContent };
255+ : { role: "user", content: text };
206256
207257 this.session.messages.push(userMsg);
208258 saveMessages(this.session.id, [userMsg], thisTurn);
@@ -248,12 +298,10 @@ export class SessionRunner {
248298 // serialization and preserve exact shape/ordering (including
249299 // providerOptions/providerMetadata thought-signature fields). Never
250300 // reconstruct tool-call history during save/load.
251-
252301 saveMessages(this.session.id, newMessages, thisTurn);
253302 }
254303
255304 lastAssistantText = extractAssistantText(newMessages);
256-
257305 this.totalIn += inputTokens;
258306 this.totalOut += outputTokens;
259307 this.lastContextTokens = contextTokens;
@@ -271,4 +319,19 @@ export class SessionRunner {
271319 }
272320 return lastAssistantText;
273321 }
322+
323+ // ─── Private helpers ───────────────────────────────────────────────────────
324+
325+ private rebuildSystemPrompt(): void {
326+ if (!this.sessionTimeAnchor) {
327+ this._systemPrompt = undefined;
328+ return;
329+ }
330+ this._systemPrompt = buildSystemPrompt(
331+ this.sessionTimeAnchor,
332+ this.cwd,
333+ this._extraSystemPrompt,
334+ this.isSubagent,
335+ );
336+ }
274337 }