@juanbenjumea/pi-agy 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,170 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+
4
+ const execFileAsync = promisify(execFile);
5
+
6
+ const MAX_DIFF_CHARS = 2000;
7
+
8
+ export interface GitBaseline {
9
+ /** Porcelain paths that were already dirty before agy ran. */
10
+ dirtyFiles: Set<string>;
11
+ /** True when the baseline could not be captured (not a repo, git missing). */
12
+ unavailable: boolean;
13
+ }
14
+
15
+ /** Capture dirty state before accept-edits so the summary can attribute only new changes to agy. */
16
+ export async function captureGitBaseline(cwd: string, signal?: AbortSignal): Promise<GitBaseline> {
17
+ try {
18
+ const { stdout } = await execFileAsync("git", ["status", "--porcelain"], {
19
+ cwd,
20
+ maxBuffer: 64 * 1024,
21
+ signal,
22
+ timeout: 10_000,
23
+ });
24
+ const dirtyFiles = new Set<string>();
25
+ for (const line of stdout.split("\n")) {
26
+ const trimmed = line.trim();
27
+ if (!trimmed) continue;
28
+ // Porcelain v1: XY <path>[ -> <orig>]. Keep the raw path token(s).
29
+ const file = trimmed.slice(3).trim();
30
+ if (file) dirtyFiles.add(file);
31
+ }
32
+ return { dirtyFiles, unavailable: false };
33
+ } catch {
34
+ if (signal?.aborted) throw new Error("agy was cancelled");
35
+ return { dirtyFiles: new Set(), unavailable: true };
36
+ }
37
+ }
38
+
39
+ /** One-line pre-run dirty count for confirmation dialogs. Best effort; null when unknown. */
40
+ export async function describePreRunDirt(
41
+ cwd: string,
42
+ signal?: AbortSignal,
43
+ ): Promise<string | null> {
44
+ try {
45
+ const baseline = await captureGitBaseline(cwd, signal);
46
+ if (baseline.unavailable) return null;
47
+ if (baseline.dirtyFiles.size === 0) return "clean";
48
+ return `${baseline.dirtyFiles.size} already-dirty file(s)`;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Summarize workspace changes after accept-edits. Returns null when clean or not a git repo.
56
+ * Covers staged and unstaged tracked modifications plus untracked files.
57
+ */
58
+ export async function summarizeGitDiff(cwd: string, signal?: AbortSignal): Promise<string | null> {
59
+ try {
60
+ const opts = { cwd, maxBuffer: 64 * 1024, signal, timeout: 10_000 };
61
+ const [workingStat, stagedStat, workingNames, stagedNames, status] = await Promise.all([
62
+ execFileAsync("git", ["diff", "--stat"], opts),
63
+ execFileAsync("git", ["diff", "--cached", "--stat"], opts),
64
+ execFileAsync("git", ["diff", "--name-only"], opts),
65
+ execFileAsync("git", ["diff", "--cached", "--name-only"], opts),
66
+ execFileAsync("git", ["status", "--short"], opts),
67
+ ]);
68
+ const unstagedStat = workingStat.stdout.trim();
69
+ const cachedStat = stagedStat.stdout.trim();
70
+ const names = uniqueLines(`${workingNames.stdout}\n${stagedNames.stdout}`);
71
+ const untracked = status.stdout
72
+ .split("\n")
73
+ .map((line) => line.trim())
74
+ .filter((line) => line.startsWith("??"))
75
+ .map((line) => line.slice(2).trim());
76
+ if (!unstagedStat && !cachedStat && names.length === 0 && untracked.length === 0) return null;
77
+
78
+ const sections: string[] = [];
79
+ if (unstagedStat) sections.push("## git diff --stat\n" + unstagedStat);
80
+ if (cachedStat) sections.push("## git diff --cached --stat\n" + cachedStat);
81
+ if (sections.length === 0) sections.push("## git diff --stat\n(no tracked diff)");
82
+
83
+ let summary = sections.join("\n\n");
84
+ if (names.length > 0) summary += "\n\n## changed files\n" + names.join("\n");
85
+ if (untracked.length > 0) summary += "\n\n## untracked files\n" + untracked.join("\n");
86
+ if (summary.length > MAX_DIFF_CHARS) {
87
+ summary = summary.slice(0, MAX_DIFF_CHARS) + "\n\n(diff summary truncated)";
88
+ }
89
+ return summary;
90
+ } catch (error) {
91
+ if (signal?.aborted) throw error;
92
+ return null;
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Filter a post-run summary to files agy newly touched. Files already dirty
98
+ * in the baseline are listed separately so pre-existing work is never
99
+ * misattributed to the delegation.
100
+ */
101
+ export async function summarizeGitDiffSince(
102
+ baseline: GitBaseline,
103
+ cwd: string,
104
+ signal?: AbortSignal,
105
+ ): Promise<{ summary: string | null; newFiles: string[]; preexistingFiles: string[] }> {
106
+ const full = await summarizeGitDiff(cwd, signal);
107
+ if (!full) return { summary: null, newFiles: [], preexistingFiles: [] };
108
+ if (baseline.unavailable || baseline.dirtyFiles.size === 0) {
109
+ return { summary: full, newFiles: listChangedFiles(full), preexistingFiles: [] };
110
+ }
111
+ try {
112
+ const opts = { cwd, maxBuffer: 64 * 1024, signal, timeout: 10_000 };
113
+ const [workingNames, stagedNames, status] = await Promise.all([
114
+ execFileAsync("git", ["diff", "--name-only"], opts),
115
+ execFileAsync("git", ["diff", "--cached", "--name-only"], opts),
116
+ execFileAsync("git", ["status", "--porcelain"], opts),
117
+ ]);
118
+ const current = new Set<string>();
119
+ for (const name of uniqueLines(`${workingNames.stdout}\n${stagedNames.stdout}`)) {
120
+ current.add(name);
121
+ }
122
+ for (const line of status.stdout.split("\n")) {
123
+ const trimmed = line.trim();
124
+ if (trimmed.startsWith("??")) {
125
+ const file = trimmed.slice(2).trim();
126
+ if (file) current.add(file);
127
+ }
128
+ }
129
+ const newFiles = [...current].filter((f) => !baseline.dirtyFiles.has(f)).sort();
130
+ const preexistingFiles = [...current].filter((f) => baseline.dirtyFiles.has(f)).sort();
131
+ if (newFiles.length === 0) {
132
+ const note =
133
+ preexistingFiles.length > 0
134
+ ? `agy made no newly-dirty files; ${preexistingFiles.length} pre-existing dirty file(s) unchanged in attribution:\n` +
135
+ preexistingFiles.join("\n")
136
+ : "agy made no newly-dirty files.";
137
+ return { summary: note, newFiles, preexistingFiles };
138
+ }
139
+ let summary = full;
140
+ if (preexistingFiles.length > 0) {
141
+ summary +=
142
+ `\n\n## pre-existing dirty files (not attributed to agy)\n` + preexistingFiles.join("\n");
143
+ }
144
+ return { summary, newFiles, preexistingFiles };
145
+ } catch (error) {
146
+ if (signal?.aborted) throw error;
147
+ return { summary: full, newFiles: listChangedFiles(full), preexistingFiles: [] };
148
+ }
149
+ }
150
+
151
+ function uniqueLines(value: string): string[] {
152
+ return [...new Set(value.split("\n").map((line) => line.trim()).filter(Boolean))];
153
+ }
154
+
155
+ function listChangedFiles(summary: string): string[] {
156
+ const files: string[] = [];
157
+ let inList = false;
158
+ for (const line of summary.split("\n")) {
159
+ if (line.startsWith("## changed files") || line.startsWith("## untracked files")) {
160
+ inList = true;
161
+ continue;
162
+ }
163
+ if (line.startsWith("## ")) {
164
+ inList = false;
165
+ continue;
166
+ }
167
+ if (inList && line.trim()) files.push(line.trim());
168
+ }
169
+ return files;
170
+ }
@@ -0,0 +1,26 @@
1
+ import { checkAgyConnectivity, checkAgyHealth } from "./cli.js";
2
+
3
+ const TTL_MS = 5 * 60 * 1000;
4
+ let cachedAt = 0;
5
+
6
+ /** Run agy health/connectivity checks, cached for a few minutes per process. */
7
+ export async function runPreflight(
8
+ cwd: string,
9
+ signal?: AbortSignal,
10
+ timeoutMs?: number,
11
+ ): Promise<void> {
12
+ if (cachedAt && Date.now() - cachedAt < TTL_MS) return;
13
+ if (timeoutMs !== undefined && timeoutMs <= 0) {
14
+ throw new Error("agy timed out before preflight");
15
+ }
16
+ await Promise.all([
17
+ checkAgyHealth(cwd, signal, timeoutMs),
18
+ checkAgyConnectivity(cwd, signal, timeoutMs),
19
+ ]);
20
+ cachedAt = Date.now();
21
+ }
22
+
23
+ /** Test helper — reset the in-process cache. */
24
+ export function resetPreflightCache(): void {
25
+ cachedAt = 0;
26
+ }
@@ -0,0 +1,278 @@
1
+ import {
2
+ chmod,
3
+ mkdir,
4
+ readFile,
5
+ rename,
6
+ rm,
7
+ stat as statFile,
8
+ unlink,
9
+ writeFile,
10
+ } from "node:fs/promises";
11
+ import * as os from "node:os";
12
+ import * as path from "node:path";
13
+ import { randomUUID } from "node:crypto";
14
+
15
+ /** One recorded agy conversation for a working directory. */
16
+ export interface AgyConversationEntry {
17
+ conversation_id: string;
18
+ model?: string;
19
+ updated_at: string;
20
+ }
21
+
22
+ export interface AgySessionRecord {
23
+ last_conversation_id?: string;
24
+ last_model?: string;
25
+ updated_at?: string;
26
+ /** Recent conversations for the directory, most recent first. */
27
+ history?: AgyConversationEntry[];
28
+ }
29
+
30
+ const HISTORY_LIMIT = 10;
31
+ const LOCK_RETRY_MS = 25;
32
+ const LOCK_STALE_MS = 30_000;
33
+
34
+ function waitForStoreLockRetry(signal?: AbortSignal): Promise<void> {
35
+ if (signal?.aborted) {
36
+ return Promise.reject(new Error("agy was cancelled while waiting for session storage"));
37
+ }
38
+ return new Promise<void>((resolve, reject) => {
39
+ const timer = setTimeout(() => {
40
+ signal?.removeEventListener("abort", onAbort);
41
+ resolve();
42
+ }, LOCK_RETRY_MS);
43
+ const onAbort = () => {
44
+ clearTimeout(timer);
45
+ signal?.removeEventListener("abort", onAbort);
46
+ reject(new Error("agy was cancelled while waiting for session storage"));
47
+ };
48
+ signal?.addEventListener("abort", onAbort, { once: true });
49
+ if (signal?.aborted) onAbort();
50
+ });
51
+ }
52
+
53
+ type SessionStore = Record<string, AgySessionRecord>;
54
+
55
+ export function getDefaultStorePath(): string {
56
+ const agentDir =
57
+ process.env.PI_CODING_AGENT_DIR?.trim() || path.join(os.homedir(), ".pi", "agent");
58
+ return path.join(agentDir, "agy-sessions.json");
59
+ }
60
+
61
+ export interface AgySessionStore {
62
+ getSession(dir: string): Promise<AgySessionRecord | undefined>;
63
+ getHistory(dir: string): Promise<AgyConversationEntry[]>;
64
+ saveSession(
65
+ dir: string,
66
+ conversationId: string,
67
+ model?: string,
68
+ signal?: AbortSignal,
69
+ ): Promise<void>;
70
+ }
71
+
72
+ /**
73
+ * Create a session store. The optional path (string or lazy resolver) makes
74
+ * persistence testable; the lazy form re-reads `PI_CODING_AGENT_DIR` on each
75
+ * operation.
76
+ */
77
+ export function createSessionStore(
78
+ storePath: string | (() => string) = getDefaultStorePath,
79
+ ): AgySessionStore {
80
+ const resolvePath = (): string => (typeof storePath === "function" ? storePath() : storePath);
81
+ let mutationChain = Promise.resolve();
82
+
83
+ async function loadStore(signal?: AbortSignal): Promise<SessionStore> {
84
+ try {
85
+ const parsed: unknown = JSON.parse(
86
+ await readFile(resolvePath(), { encoding: "utf8", signal }),
87
+ );
88
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
89
+ throw new Error("Invalid agy session store format");
90
+ }
91
+ return parsed as SessionStore;
92
+ } catch (error) {
93
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
94
+ throw error;
95
+ }
96
+ }
97
+
98
+ async function saveStore(store: SessionStore): Promise<void> {
99
+ const target = resolvePath();
100
+ await mkdir(path.dirname(target), { recursive: true });
101
+ const tempPath = `${target}.${process.pid}.${randomUUID()}.tmp`;
102
+ try {
103
+ await writeFile(tempPath, JSON.stringify(store, null, 2) + "\n", {
104
+ encoding: "utf8",
105
+ mode: 0o600,
106
+ });
107
+ await chmod(tempPath, 0o600);
108
+ await rename(tempPath, target);
109
+ } finally {
110
+ await unlink(tempPath).catch(() => undefined);
111
+ }
112
+ }
113
+
114
+ /** A corrupt store must never block the user's task; saves stay strict. */
115
+ function isCorruptStoreError(error: unknown): boolean {
116
+ return (
117
+ error instanceof SyntaxError ||
118
+ (error instanceof Error && error.message === "Invalid agy session store format")
119
+ );
120
+ }
121
+
122
+ async function getSession(dir: string): Promise<AgySessionRecord | undefined> {
123
+ try {
124
+ const store = await loadStore();
125
+ return store[path.resolve(dir)];
126
+ } catch (error) {
127
+ if (isCorruptStoreError(error)) return undefined;
128
+ throw error;
129
+ }
130
+ }
131
+
132
+ async function getHistory(dir: string): Promise<AgyConversationEntry[]> {
133
+ let history: AgyConversationEntry[] | undefined;
134
+ try {
135
+ const store = await loadStore();
136
+ history = store[path.resolve(dir)]?.history;
137
+ } catch (error) {
138
+ if (!isCorruptStoreError(error)) throw error;
139
+ }
140
+ return Array.isArray(history)
141
+ ? history
142
+ .filter(
143
+ (entry) =>
144
+ entry &&
145
+ typeof entry.conversation_id === "string" &&
146
+ typeof entry.updated_at === "string",
147
+ )
148
+ .slice()
149
+ : [];
150
+ }
151
+
152
+ async function withStoreLock<T>(fn: () => Promise<T>, signal?: AbortSignal): Promise<T> {
153
+ const target = resolvePath();
154
+ const lockPath = `${target}.lock`;
155
+ const owner = randomUUID();
156
+ await mkdir(path.dirname(target), { recursive: true });
157
+
158
+ while (true) {
159
+ if (signal?.aborted) throw new Error("agy was cancelled while waiting for session storage");
160
+ try {
161
+ await mkdir(lockPath);
162
+ try {
163
+ await writeFile(path.join(lockPath, "owner"), owner, {
164
+ encoding: "utf8",
165
+ mode: 0o600,
166
+ });
167
+ } catch (error) {
168
+ await rm(lockPath, { recursive: true, force: true }).catch(() => undefined);
169
+ throw error;
170
+ }
171
+ break;
172
+ } catch (error) {
173
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
174
+ try {
175
+ const lockStat = await statFile(lockPath);
176
+ if (Date.now() - lockStat.mtimeMs > LOCK_STALE_MS) {
177
+ await rm(lockPath, { recursive: true, force: true });
178
+ continue;
179
+ }
180
+ } catch {
181
+ // The lock disappeared between mkdir and stat; retry immediately.
182
+ continue;
183
+ }
184
+ await waitForStoreLockRetry(signal);
185
+ }
186
+ }
187
+
188
+ try {
189
+ return await fn();
190
+ } finally {
191
+ try {
192
+ if ((await readFile(path.join(lockPath, "owner"), "utf8")) === owner) {
193
+ await rm(lockPath, { recursive: true, force: true });
194
+ }
195
+ } catch {
196
+ // Preserve the operation result if cleanup races with a stale-lock recovery.
197
+ }
198
+ }
199
+ }
200
+
201
+ async function waitForMutation(signal?: AbortSignal): Promise<void> {
202
+ if (!signal) {
203
+ await mutationChain;
204
+ return;
205
+ }
206
+ if (signal.aborted) throw new Error("agy was cancelled while waiting for session storage");
207
+ await new Promise<void>((resolve, reject) => {
208
+ const onAbort = () => finish(() => reject(new Error("agy was cancelled while waiting for session storage")));
209
+ const finish = (settle: () => void) => {
210
+ signal.removeEventListener("abort", onAbort);
211
+ settle();
212
+ };
213
+ signal.addEventListener("abort", onAbort, { once: true });
214
+ if (signal.aborted) {
215
+ onAbort();
216
+ return;
217
+ }
218
+ mutationChain.then(() => finish(resolve), (error) => finish(() => reject(error)));
219
+ });
220
+ }
221
+
222
+ function saveSession(
223
+ dir: string,
224
+ conversationId: string,
225
+ model?: string,
226
+ signal?: AbortSignal,
227
+ ): Promise<void> {
228
+ const operation = waitForMutation(signal).then(() =>
229
+ withStoreLock(async () => {
230
+ const store = await loadStore(signal);
231
+ const key = path.resolve(dir);
232
+ const record = store[key] ?? {};
233
+ const updatedAt = new Date().toISOString();
234
+ store[key] = {
235
+ last_conversation_id: conversationId,
236
+ last_model: model,
237
+ updated_at: updatedAt,
238
+ history: [
239
+ { conversation_id: conversationId, model, updated_at: updatedAt },
240
+ ...(Array.isArray(record.history) ? record.history : []).filter(
241
+ (entry) =>
242
+ entry &&
243
+ typeof entry.conversation_id === "string" &&
244
+ entry.conversation_id !== conversationId,
245
+ ),
246
+ ].slice(0, HISTORY_LIMIT),
247
+ };
248
+ await saveStore(store);
249
+ }, signal),
250
+ );
251
+ mutationChain = operation.then(
252
+ () => undefined,
253
+ () => undefined,
254
+ );
255
+ return operation;
256
+ }
257
+
258
+ return { getSession, getHistory, saveSession };
259
+ }
260
+
261
+ const defaultStore = createSessionStore();
262
+
263
+ export function getSession(dir: string): Promise<AgySessionRecord | undefined> {
264
+ return defaultStore.getSession(dir);
265
+ }
266
+
267
+ export function getHistory(dir: string): Promise<AgyConversationEntry[]> {
268
+ return defaultStore.getHistory(dir);
269
+ }
270
+
271
+ export function saveSession(
272
+ dir: string,
273
+ conversationId: string,
274
+ model?: string,
275
+ signal?: AbortSignal,
276
+ ): Promise<void> {
277
+ return defaultStore.saveSession(dir, conversationId, model, signal);
278
+ }
@@ -0,0 +1,221 @@
1
+ export interface AgyUsage {
2
+ input_tokens?: number;
3
+ output_tokens?: number;
4
+ thinking_tokens?: number;
5
+ cache_read_tokens?: number;
6
+ total_tokens?: number;
7
+ }
8
+
9
+ export interface AgyStepUpdate {
10
+ conversation_id?: string;
11
+ step_index?: number;
12
+ state?: string;
13
+ step_type?: string;
14
+ tool_name?: string;
15
+ text_delta?: string;
16
+ duration_seconds?: number;
17
+ usage?: AgyUsage;
18
+ tool_info?: {
19
+ name?: string;
20
+ parameters?: Record<string, unknown>;
21
+ };
22
+ }
23
+
24
+ export interface AgyStreamLine {
25
+ event?: string;
26
+ conversation_id?: string;
27
+ init?: { model?: string; cwd?: string };
28
+ step_update?: AgyStepUpdate;
29
+ result?: {
30
+ conversation_id?: string;
31
+ status?: string;
32
+ response?: string;
33
+ duration_seconds?: number;
34
+ usage?: AgyUsage;
35
+ };
36
+ }
37
+
38
+ export interface AgyRunResult {
39
+ response: string;
40
+ /** Internal marker distinguishing a valid empty response from no response. */
41
+ response_complete?: boolean;
42
+ conversation_id?: string;
43
+ usage?: AgyUsage;
44
+ duration_seconds?: number;
45
+ }
46
+
47
+ export type AgyProgressHandler = (
48
+ message: string,
49
+ /** "activity" = real agy work (tool step or response text); "status" = lifecycle chatter. */
50
+ kind?: "status" | "activity",
51
+ ) => void;
52
+
53
+ export function parseStreamLine(line: string): AgyStreamLine | null {
54
+ const trimmed = line.trim().replace(/^\uFEFF/, "");
55
+ if (!trimmed) return null;
56
+ try {
57
+ const parsed: unknown = JSON.parse(trimmed);
58
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
59
+ ? (parsed as AgyStreamLine)
60
+ : null;
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ export function formatStepProgress(parsed: AgyStreamLine): string | null {
67
+ if (parsed.event === "init") {
68
+ const model = parsed.init?.model ?? "agy";
69
+ return `agy: session started (${model})`;
70
+ }
71
+
72
+ // Result events do not contain step_update, so handle them before the
73
+ // step guard below. This also gives users a visible terminal status.
74
+ if (parsed.event === "result" && parsed.result?.status) {
75
+ const secs = parsed.result.duration_seconds;
76
+ const dur = typeof secs === "number" ? ` in ${secs.toFixed(1)}s` : "";
77
+ return `agy: ${parsed.result.status}${dur}`;
78
+ }
79
+
80
+ const step = parsed.step_update;
81
+ if (!step) return null;
82
+
83
+ if (step.step_type === "tool" && step.state === "ACTIVE") {
84
+ const name = step.tool_name ?? step.tool_info?.name ?? "tool";
85
+ const target = step.tool_info?.parameters?.TargetFile;
86
+ return target ? `▸ ${name} → ${String(target)}` : `▸ ${name}`;
87
+ }
88
+
89
+ if (step.step_type === "agent_response" && step.text_delta) {
90
+ return "agy: generating response…";
91
+ }
92
+
93
+ return null;
94
+ }
95
+
96
+ export const MAX_RESPONSE_CHARS = 1_000_000;
97
+ // A single JSONL record without a newline is almost certainly a runaway or
98
+ // hostile producer. Discard it with a warning instead of growing memory
99
+ // without bound.
100
+ export const MAX_STREAM_LINE_BYTES = 256 * 1024;
101
+
102
+ export interface StreamChunk {
103
+ /** Complete newline-terminated records ready to parse. */
104
+ lines: string[];
105
+ /** Unterminated remainder to prepend to the next chunk. */
106
+ lineBuffer: string;
107
+ }
108
+
109
+ /**
110
+ * Accumulate stdout text into newline-delimited records. An unterminated
111
+ * remainder past the bound is discarded with a warning, as are oversized
112
+ * complete records — neighbors are still delivered.
113
+ */
114
+ export function appendStreamChunk(
115
+ lineBuffer: string,
116
+ chunk: string,
117
+ onProgress?: AgyProgressHandler,
118
+ ): StreamChunk {
119
+ const warn = () =>
120
+ onProgress?.("agy: warning — discarded oversized stream record", "status");
121
+ const combined = lineBuffer + chunk;
122
+ if (!combined.includes("\n")) {
123
+ if (combined.length > MAX_STREAM_LINE_BYTES) {
124
+ warn();
125
+ return { lines: [], lineBuffer: "" };
126
+ }
127
+ return { lines: [], lineBuffer: combined };
128
+ }
129
+ const parts = combined.split("\n");
130
+ let remainder = parts.pop() ?? "";
131
+ if (remainder.length > MAX_STREAM_LINE_BYTES) {
132
+ warn();
133
+ remainder = "";
134
+ }
135
+ const lines: string[] = [];
136
+ for (const line of parts) {
137
+ if (line.length > MAX_STREAM_LINE_BYTES) {
138
+ warn();
139
+ continue;
140
+ }
141
+ lines.push(line);
142
+ }
143
+ return { lines, lineBuffer: remainder };
144
+ }
145
+
146
+ export function accumulateRunResult(parsed: AgyStreamLine, current: AgyRunResult): AgyRunResult {
147
+ const next = { ...current };
148
+
149
+ if (parsed.conversation_id) next.conversation_id = parsed.conversation_id;
150
+ if (parsed.init && parsed.conversation_id) next.conversation_id = parsed.conversation_id;
151
+
152
+ const step = parsed.step_update;
153
+ if (step?.conversation_id) next.conversation_id = step.conversation_id;
154
+
155
+ if (parsed.result) {
156
+ if (parsed.result.conversation_id) next.conversation_id = parsed.result.conversation_id;
157
+ if (parsed.result.response != null) {
158
+ next.response =
159
+ parsed.result.response.length > MAX_RESPONSE_CHARS
160
+ ? parsed.result.response.slice(0, MAX_RESPONSE_CHARS) + "\n\n(response truncated)"
161
+ : parsed.result.response;
162
+ next.response_complete = true;
163
+ }
164
+ if (parsed.result.usage) next.usage = parsed.result.usage;
165
+ if (parsed.result.duration_seconds != null) {
166
+ next.duration_seconds = parsed.result.duration_seconds;
167
+ }
168
+ }
169
+
170
+ return next;
171
+ }
172
+
173
+ export function finalizeRunResult(rawStdout: string, current: AgyRunResult): AgyRunResult {
174
+ if (current.response_complete || current.response) return current;
175
+
176
+ // Fall back to plain json envelope or raw text when stream-json had no result event.
177
+ for (const line of rawStdout.split("\n")) {
178
+ const parsed = parseStreamLine(line);
179
+ if (typeof parsed?.result?.response === "string") {
180
+ return accumulateRunResult(parsed, { ...current, response: parsed.result.response });
181
+ }
182
+ }
183
+
184
+ try {
185
+ const parsed: unknown = JSON.parse(rawStdout);
186
+ const next = mergeJsonEnvelope(parsed, current);
187
+ if (next) return next;
188
+ } catch {
189
+ // not json
190
+ }
191
+
192
+ return { ...current, response: rawStdout.trim() || "(empty response)" };
193
+ }
194
+
195
+ /** Preserve metadata from agy's non-stream JSON envelope when available. */
196
+ function mergeJsonEnvelope(parsed: unknown, current: AgyRunResult): AgyRunResult | null {
197
+ if (typeof parsed !== "object" || parsed === null) return null;
198
+ const record = parsed as Record<string, unknown>;
199
+ let next = { ...current };
200
+ let found = false;
201
+
202
+ if (typeof record.conversation_id === "string") {
203
+ next.conversation_id = record.conversation_id;
204
+ found = true;
205
+ }
206
+ if (typeof record.response === "string") {
207
+ next.response = record.response;
208
+ next.response_complete = true;
209
+ found = true;
210
+ }
211
+ if (typeof record.duration_seconds === "number") {
212
+ next.duration_seconds = record.duration_seconds;
213
+ found = true;
214
+ }
215
+ if (typeof record.usage === "object" && record.usage !== null) {
216
+ next.usage = record.usage as AgyUsage;
217
+ found = true;
218
+ }
219
+
220
+ return found ? next : null;
221
+ }