xonecas.io
64875
Mc

mini-coder / commit 6548a80

refactor(agent): encapsulate SessionRunner internals

- Make totalIn/totalOut/lastContextTokens/coreHistory/snapshotStack/
  turnIndex/etc. private — no longer leaked to callers
- Add getStatusInfo() method so input-loop/index.ts get what they need
  without reaching into runner internals
- Add addShellContext() method so input-loop.ts doesn't directly mutate
  runner.coreHistory/session.messages/snapshotStack
- Move undoLastTurn() into the class (was called from agent.ts with
  runner internals passed as raw parameters)
- Remove undo-snapshot.ts import from agent.ts (now called via runner)
- Make cwd/reporter/tools/mcpTools readonly (set once in constructor)

xonecas2026-03-14 6548a80c7e2dc73c7735421b79924e98bb803db4 parent a0dd567

4 files changed

src/agent/agent.ts+1−13
@@ -22,7 +22,6 @@ import type { AgentReporter } from "./reporter.ts";
2222 import { SessionRunner } from "./session-runner.ts";
2323 import { createSubagentRunner } from "./subagent-runner.ts";
2424 import { buildToolSet } from "./tools.ts";
25-import { undoLastTurn } from "./undo-snapshot.ts";
2625
2726 interface AgentOptions {
2827 model: string;
@@ -213,18 +212,7 @@ export async function initAgent(opts: AgentOptions): Promise<{
213212 setPreferredActiveAgent(name);
214213 },
215214
216- undoLastTurn: () =>
217- undoLastTurn({
218- session: runner.session,
219- coreHistory: runner.coreHistory,
220- snapshotStack: runner.snapshotStack,
221- getTurnIndex: () => runner.turnIndex,
222- setTurnIndex: (idx) => {
223- runner.turnIndex = idx;
224- },
225- cwd,
226- reporter: opts.reporter,
227- }),
215+ undoLastTurn: () => runner.undoLastTurn(),
228216 connectMcpServer: connectAndAddMcp,
229217 startSpinner: (label?: string) => opts.reporter.startSpinner(label),
230218 stopSpinner: () => opts.reporter.stopSpinner(),
src/agent/session-runner.ts+125−62
@@ -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 }
src/cli/input-loop.ts+12−23
@@ -3,8 +3,6 @@ import type { AgentReporter } from "../agent/reporter.ts";
33 import type { SessionRunner } from "../agent/session-runner.ts";
44
55 import { getContextWindow } from "../llm-api/providers.ts";
6-import type { CoreMessage } from "../llm-api/turn.ts";
7-import { saveMessages } from "../session/db/index.ts";
86 import { getGitBranch, runShellPassthrough } from "./cli-helpers.ts";
97 import { handleCommand } from "./commands.ts";
108 import { resolveFileRefs } from "./file-refs.ts";
@@ -25,8 +23,9 @@ export async function runInputLoop(opts: InputLoopOptions): Promise<void> {
2523
2624 while (true) {
2725 const branch = await getGitBranch(cwd);
28- const provider = runner.currentModel.split("/")[0] ?? "";
29- const modelShort = runner.currentModel.split("/").slice(1).join("/");
26+ const status = runner.getStatusInfo();
27+ const provider = status.model.split("/")[0] ?? "";
28+ const modelShort = status.model.split("/").slice(1).join("/");
3029 const cwdDisplay = tildePath(cwd);
3130
3231 reporter.renderStatusBar({
@@ -34,21 +33,19 @@ export async function runInputLoop(opts: InputLoopOptions): Promise<void> {
3433 provider,
3534 cwd: cwdDisplay,
3635 gitBranch: branch,
37- sessionId: runner.session.id,
38- inputTokens: runner.totalIn,
39- outputTokens: runner.totalOut,
40- contextTokens: runner.lastContextTokens,
41- contextWindow: getContextWindow(runner.currentModel) ?? 0,
42- thinkingEffort: runner.currentThinkingEffort,
36+ sessionId: status.sessionId,
37+ inputTokens: status.totalIn,
38+ outputTokens: status.totalOut,
39+ contextTokens: status.lastContextTokens,
40+ contextWindow: getContextWindow(status.model) ?? 0,
41+ thinkingEffort: status.thinkingEffort,
4342 activeAgent: cmdCtx.activeAgent,
44- showReasoning: runner.showReasoning,
43+ showReasoning: status.showReasoning,
4544 });
4645
4746 let input: InputResult;
4847 try {
49- input = await readline({
50- cwd,
51- });
48+ input = await readline({ cwd });
5249 } catch {
5350 break;
5451 }
@@ -82,15 +79,7 @@ export async function runInputLoop(opts: InputLoopOptions): Promise<void> {
8279 case "shell": {
8380 const out = await runShellPassthrough(input.command, cwd, reporter);
8481 if (out) {
85- const thisTurn = runner.turnIndex++;
86- const msg: CoreMessage = {
87- role: "user",
88- content: `Shell output of \`${input.command}\`:\n\`\`\`\n${out}\n\`\`\``,
89- };
90- runner.session.messages.push(msg);
91- saveMessages(runner.session.id, [msg], thisTurn);
92- runner.coreHistory.push(msg);
93- runner.snapshotStack.push(null);
82+ runner.addShellContext(input.command, out);
9483 }
9584 continue;
9685 }
src/index.ts+5−3
@@ -124,10 +124,11 @@ async function main(): Promise<void> {
124124 parentCwd,
125125 );
126126 const result = await runner.processUserInput(resolvedText, refImages);
127+ const status = runner.getStatusInfo();
127128 const summary = {
128129 result,
129- inputTokens: runner.totalIn,
130- outputTokens: runner.totalOut,
130+ inputTokens: status.totalIn,
131+ outputTokens: status.totalOut,
131132 };
132133
133134 if (args.outputFd !== null && summary) {
@@ -173,8 +174,9 @@ async function main(): Promise<void> {
173174 args.cwd,
174175 );
175176 await runner.processUserInput(resolvedText, refImages);
177+ const { totalIn, totalOut } = runner.getStatusInfo();
176178 writeln(
177- ` ${c.dim(`${runner.totalIn.toLocaleString()} in / ${runner.totalOut.toLocaleString()} out tokens`)}`,
179+ ` ${c.dim(`${totalIn.toLocaleString()} in / ${totalOut.toLocaleString()} out tokens`)}`,
178180 );
179181 return;
180182 }