@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,211 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ import { promisify } from "node:util";
6
+
7
+ import { isAgyModel, type AgyModel } from "./cli.js";
8
+ import { getDefaultStorePath } from "./sessions.js";
9
+
10
+ const execFileAsync = promisify(execFile);
11
+
12
+ const COMMAND_TTL_MS = 5 * 60 * 1000;
13
+ const COMMAND_TIMEOUT_MS = 5_000;
14
+
15
+ /**
16
+ * Optional overrides loaded from `$PI_CODING_AGENT_DIR/agy-config.json`
17
+ * (default `~/.pi/agent/agy-config.json`). Missing or malformed files fall
18
+ * back to built-in defaults.
19
+ */
20
+ export interface AgyConfig {
21
+ /**
22
+ * Auto-approve agy tool permission requests for accept-edits runs
23
+ * (`--dangerously-skip-permissions`). Default `true`. When `false`,
24
+ * accept-edits runs without the permission bypass — agy print mode has
25
+ * no interactive approval path, so restricted operations may fail.
26
+ */
27
+ skipPermissions?: boolean;
28
+ /** Default model alias when agy_execute omits model/tier (e.g. "flash-medium"). */
29
+ defaultModel?: string;
30
+ /**
31
+ * Steer the default by recent usage balance when no explicit
32
+ * `defaultModel`/`defaultModelCommand` is set: when the Gemini group
33
+ * (flash/pro) carried `AGY_DEFAULT_MODEL_GEMINI_SHARE`% (default 75) of
34
+ * the last `AGY_DEFAULT_MODEL_WINDOW_HOURS`h (default 24) of recorded
35
+ * conversations (minimum `AGY_DEFAULT_MODEL_MIN_SESSIONS`, default 3),
36
+ * the default flips to `sonnet` so routine delegation rests the hot
37
+ * quota group. Missing/corrupt stores mean no signal (built-in default).
38
+ */
39
+ quotaBalancing?: boolean;
40
+ /**
41
+ * Shell command whose stdout is used as the default model alias when
42
+ * `defaultModel` is unset — e.g. a quota-aware resolver. Must print a
43
+ * single valid alias; failures and invalid output fall back to the
44
+ * built-in default. Result cached for a few minutes per process.
45
+ *
46
+ * Trust boundary: executed verbatim via `sh -c`. Only point this at a
47
+ * command you control — the config file is user-owned.
48
+ */
49
+ defaultModelCommand?: string;
50
+ }
51
+
52
+ export function getDefaultConfigPath(): string {
53
+ const agentDir =
54
+ process.env.PI_CODING_AGENT_DIR?.trim() || path.join(os.homedir(), ".pi", "agent");
55
+ return path.join(agentDir, "agy-config.json");
56
+ }
57
+
58
+ export async function loadAgyConfig(
59
+ configPath = getDefaultConfigPath(),
60
+ signal?: AbortSignal,
61
+ ): Promise<AgyConfig> {
62
+ try {
63
+ const parsed: unknown = JSON.parse(
64
+ await readFile(configPath, { encoding: "utf8", signal }),
65
+ );
66
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
67
+ const record = parsed as Record<string, unknown>;
68
+ const config: AgyConfig = {};
69
+ if (typeof record.defaultModel === "string") config.defaultModel = record.defaultModel;
70
+ if (typeof record.defaultModelCommand === "string") {
71
+ config.defaultModelCommand = record.defaultModelCommand;
72
+ }
73
+ if (typeof record.skipPermissions === "boolean") {
74
+ config.skipPermissions = record.skipPermissions;
75
+ } else if ("skipPermissions" in record) {
76
+ // A malformed permission setting must never silently enable bypasses.
77
+ config.skipPermissions = false;
78
+ }
79
+ return config;
80
+ }
81
+ } catch {
82
+ // Missing or malformed config falls back to defaults.
83
+ }
84
+ return {};
85
+ }
86
+
87
+ const cachedCommandAliases = new Map<string, { at: number; alias?: AgyModel }>();
88
+
89
+ /**
90
+ * Resolve the default model alias: an explicit `defaultModel` always wins,
91
+ * then `defaultModelCommand` runs (cached) and its output is validated,
92
+ * then `quotaBalancing` steers by recent usage. Returns undefined for the
93
+ * built-in fallback.
94
+ */
95
+ export async function resolveDefaultModel(
96
+ config: AgyConfig,
97
+ signal?: AbortSignal,
98
+ ): Promise<AgyModel | undefined> {
99
+ const configuredModel = normalizeConfiguredModel(config.defaultModel);
100
+ if (configuredModel) return configuredModel;
101
+ const command = config.defaultModelCommand?.trim();
102
+ if (command) {
103
+ const cached = cachedCommandAliases.get(command);
104
+ if (cached && Date.now() - cached.at < COMMAND_TTL_MS) {
105
+ return cached.alias;
106
+ }
107
+
108
+ const alias = await runDefaultModelCommand(command, signal);
109
+ if (!signal?.aborted) {
110
+ cachedCommandAliases.set(command, { at: Date.now(), alias });
111
+ }
112
+ return alias;
113
+ }
114
+ if (config.quotaBalancing) return resolveQuotaBalancedDefault();
115
+ return undefined;
116
+ }
117
+
118
+ async function runDefaultModelCommand(
119
+ command: string,
120
+ signal?: AbortSignal,
121
+ ): Promise<AgyModel | undefined> {
122
+ try {
123
+ const { stdout } = await execFileAsync("sh", ["-c", command], {
124
+ timeout: COMMAND_TIMEOUT_MS,
125
+ maxBuffer: 16 * 1024,
126
+ signal,
127
+ });
128
+ const alias = stdout.trim().split("\n")[0]?.trim() ?? "";
129
+ return isAgyModel(alias) ? alias : undefined;
130
+ } catch {
131
+ return undefined;
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Native quota balancing (replaces the external agy-default-model.sh):
137
+ * flip the default to `sonnet` when Gemini models carried nearly all
138
+ * recent conversations. Unreadable stores mean no signal — never throw.
139
+ */
140
+ async function resolveQuotaBalancedDefault(): Promise<AgyModel | undefined> {
141
+ const windowHours = envNumber("AGY_DEFAULT_MODEL_WINDOW_HOURS", 24);
142
+ const minSessions = envNumber("AGY_DEFAULT_MODEL_MIN_SESSIONS", 3);
143
+ const geminiShare = envNumber("AGY_DEFAULT_MODEL_GEMINI_SHARE", 75);
144
+ let gemini = 0;
145
+ let other = 0;
146
+ try {
147
+ const parsed: unknown = JSON.parse(await readFile(getDefaultStorePath(), "utf8"));
148
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined;
149
+ const cutoff = Date.now() - windowHours * 3_600_000;
150
+ for (const record of Object.values(parsed as Record<string, unknown>)) {
151
+ if (typeof record !== "object" || record === null) continue;
152
+ const entry = record as {
153
+ history?: unknown;
154
+ last_conversation_id?: unknown;
155
+ last_model?: unknown;
156
+ updated_at?: unknown;
157
+ };
158
+ const entries: unknown[] = [
159
+ ...(Array.isArray(entry.history) ? entry.history : []),
160
+ ...(typeof entry.last_conversation_id === "string"
161
+ ? [
162
+ {
163
+ conversation_id: entry.last_conversation_id,
164
+ model: entry.last_model,
165
+ updated_at: entry.updated_at,
166
+ },
167
+ ]
168
+ : []),
169
+ ];
170
+ const seen = new Set<unknown>();
171
+ for (const item of entries) {
172
+ if (typeof item !== "object" || item === null) continue;
173
+ const { conversation_id, model, updated_at } = item as {
174
+ conversation_id?: unknown;
175
+ model?: unknown;
176
+ updated_at?: unknown;
177
+ };
178
+ if (seen.has(conversation_id)) continue;
179
+ seen.add(conversation_id);
180
+ const when = Date.parse(typeof updated_at === "string" ? updated_at : "");
181
+ if (!Number.isFinite(when) || when < cutoff) continue;
182
+ if (typeof model !== "string") continue;
183
+ if (model.startsWith("flash") || model.startsWith("pro")) gemini++;
184
+ else if (model === "sonnet" || model === "opus" || model === "gpt-oss") other++;
185
+ }
186
+ }
187
+ } catch {
188
+ return undefined;
189
+ }
190
+ const total = gemini + other;
191
+ if (total === 0 || total < minSessions) return undefined;
192
+ return (gemini * 100) / total >= geminiShare ? "sonnet" : undefined;
193
+ }
194
+
195
+ function envNumber(name: string, fallback: number): number {
196
+ const raw = process.env[name];
197
+ if (raw === undefined || raw.trim() === "") return fallback;
198
+ const value = Number(raw);
199
+ return Number.isFinite(value) ? value : fallback;
200
+ }
201
+
202
+ /** Test helper — drop the cached default-model command result. */
203
+ function normalizeConfiguredModel(value: unknown): AgyModel | undefined {
204
+ if (value === "flash") return "flash-medium";
205
+ if (value === "pro") return "pro-high";
206
+ return isAgyModel(value) ? value : undefined;
207
+ }
208
+
209
+ export function resetDefaultModelCache(): void {
210
+ cachedCommandAliases.clear();
211
+ }
@@ -0,0 +1,263 @@
1
+ import { stat } from "node:fs/promises";
2
+
3
+ import {
4
+ buildAgyPrompt,
5
+ detectVerifyCommand,
6
+ getAgyConversationId,
7
+ isTransientAgyFailure,
8
+ resolveAgyModelAlias,
9
+ spawnAgyStream,
10
+ type AgyEffort,
11
+ type AgyModel,
12
+ } from "./cli.js";
13
+ import { loadAgyConfig, resolveDefaultModel } from "./config.js";
14
+ import type { AgyUsage } from "./stream.js";
15
+ import { withDirLock } from "./lock.js";
16
+ import {
17
+ captureGitBaseline,
18
+ summarizeGitDiffSince,
19
+ type GitBaseline,
20
+ } from "./postflight.js";
21
+ import { runPreflight } from "./preflight.js";
22
+ import { getSession, saveSession } from "./sessions.js";
23
+
24
+ export type AgyMode = "plan" | "accept-edits" | "sandbox";
25
+
26
+ export interface AgyExecutionOptions {
27
+ prompt: string;
28
+ model?: AgyModel;
29
+ tier?: "flash" | "flash-lo" | "pro";
30
+ effort?: AgyEffort;
31
+ mode: AgyMode;
32
+ dir: string;
33
+ digest?: boolean;
34
+ timeout_ms: number;
35
+ conversation_id?: string;
36
+ continue?: boolean;
37
+ new_session?: boolean;
38
+ stream?: boolean;
39
+ }
40
+
41
+ export interface AgyExecutionDetails {
42
+ mode: AgyMode;
43
+ model: AgyModel | "flash-medium";
44
+ dir: string;
45
+ conversation_id?: string;
46
+ verify_cmd: string | null;
47
+ permissions_skipped?: boolean;
48
+ effort?: AgyEffort;
49
+ usage?: AgyUsage;
50
+ duration_seconds?: number;
51
+ changed_files?: string[];
52
+ preexisting_files?: string[];
53
+ }
54
+
55
+ export interface AgyExecutionResult {
56
+ text: string;
57
+ details: AgyExecutionDetails;
58
+ }
59
+
60
+ export async function executeAgyTask(
61
+ options: AgyExecutionOptions,
62
+ signal: AbortSignal | undefined,
63
+ onProgress?: (message: string) => void,
64
+ ): Promise<AgyExecutionResult> {
65
+ validateAgyExecutionOptions(options);
66
+ const startedAt = Date.now();
67
+ const budgetController = new AbortController();
68
+ const abortSignal = signal
69
+ ? AbortSignal.any([signal, budgetController.signal])
70
+ : budgetController.signal;
71
+ const budgetTimer = setTimeout(
72
+ () => budgetController.abort(),
73
+ Math.max(options.timeout_ms, 0),
74
+ );
75
+ let effectiveModel: AgyModel | "flash-medium" = "flash-medium";
76
+
77
+ try {
78
+ const config = await loadAgyConfig(undefined, abortSignal);
79
+ // Explicit model → legacy tier → configured default → flash-medium.
80
+ const selectedModel = resolveAgyModelAlias(options.model, options.tier);
81
+ const model =
82
+ selectedModel ?? (await resolveDefaultModel(config, abortSignal));
83
+ effectiveModel = model ?? "flash-medium";
84
+ const skipPermissions = config.skipPermissions !== false;
85
+
86
+ return await withDirLock(
87
+ options.dir,
88
+ async () => {
89
+ remainingBudget(startedAt, options.timeout_ms);
90
+ if (!(await stat(options.dir)).isDirectory()) {
91
+ throw new Error(`Working directory is not a directory: ${options.dir}`);
92
+ }
93
+
94
+ let conversationId = options.conversation_id;
95
+ if (
96
+ !conversationId &&
97
+ !options.continue &&
98
+ options.new_session !== true
99
+ ) {
100
+ const prior = await getSession(options.dir);
101
+ if (prior?.last_conversation_id && options.new_session === false) {
102
+ conversationId = prior.last_conversation_id;
103
+ }
104
+ }
105
+
106
+ const useDigest = options.digest ?? options.mode !== "accept-edits";
107
+ const verifyCmd =
108
+ options.mode === "accept-edits"
109
+ ? await detectVerifyCommand(options.dir)
110
+ : null;
111
+ const baseline: GitBaseline =
112
+ options.mode === "accept-edits"
113
+ ? await captureGitBaseline(options.dir, abortSignal)
114
+ : { dirtyFiles: new Set(), unavailable: true };
115
+ remainingBudget(startedAt, options.timeout_ms);
116
+ const finalPrompt = buildAgyPrompt(
117
+ options.prompt,
118
+ options.mode,
119
+ useDigest,
120
+ verifyCmd,
121
+ );
122
+
123
+ const run = await runWithTransientRetry(async (trackProgress) => {
124
+ const remainingMs = remainingBudget(startedAt, options.timeout_ms);
125
+ await runPreflight(options.dir, abortSignal, remainingMs);
126
+ const runTimeoutMs = remainingBudget(startedAt, options.timeout_ms);
127
+ // Emitted via onProgress directly: progress tracking (and therefore
128
+ // retry eligibility) must only reflect activity from agy itself.
129
+ onProgress?.(
130
+ `agy: starting (${effectiveModel}, ${options.mode}${options.effort ? `, effort ${options.effort}` : ""})…`,
131
+ );
132
+
133
+ return spawnAgyStream(
134
+ {
135
+ prompt: finalPrompt,
136
+ model,
137
+ effort: options.effort,
138
+ mode: options.mode,
139
+ dir: options.dir,
140
+ timeout_ms: runTimeoutMs,
141
+ conversation_id: conversationId,
142
+ continue: options.continue,
143
+ stream: options.stream ?? true,
144
+ skipPermissions,
145
+ },
146
+ abortSignal,
147
+ trackProgress,
148
+ );
149
+ }, onProgress);
150
+
151
+ if (run.conversation_id) {
152
+ try {
153
+ await saveSession(options.dir, run.conversation_id, effectiveModel, abortSignal);
154
+ } catch (error) {
155
+ const reason = error instanceof Error ? error.message : String(error);
156
+ onProgress?.(`agy: warning — could not persist session: ${reason}`);
157
+ }
158
+ }
159
+ remainingBudget(startedAt, options.timeout_ms);
160
+
161
+ let text = run.response;
162
+ let changedFiles: string[] | undefined;
163
+ let preexistingFiles: string[] | undefined;
164
+ if (options.mode === "accept-edits") {
165
+ const diff = await summarizeGitDiffSince(baseline, options.dir, abortSignal);
166
+ if (diff.summary) text = `${text}\n\n${diff.summary}`;
167
+ changedFiles = diff.newFiles;
168
+ preexistingFiles = diff.preexistingFiles;
169
+ }
170
+ if (abortSignal.aborted) {
171
+ throw new Error(signal?.aborted ? "agy was cancelled" : "agy timed out");
172
+ }
173
+ remainingBudget(startedAt, options.timeout_ms);
174
+
175
+ return {
176
+ text,
177
+ details: {
178
+ mode: options.mode,
179
+ model: effectiveModel,
180
+ dir: options.dir,
181
+ conversation_id: run.conversation_id,
182
+ verify_cmd: verifyCmd,
183
+ permissions_skipped: options.mode === "accept-edits" ? skipPermissions : false,
184
+ effort: options.effort,
185
+ usage: run.usage,
186
+ duration_seconds: run.duration_seconds,
187
+ changed_files: changedFiles,
188
+ preexisting_files: preexistingFiles,
189
+ },
190
+ };
191
+ },
192
+ abortSignal,
193
+ remainingBudget(startedAt, options.timeout_ms),
194
+ );
195
+ } catch (error) {
196
+ const conversationId = getAgyConversationId(error);
197
+ if (conversationId) {
198
+ try {
199
+ await saveSession(options.dir, conversationId, effectiveModel, abortSignal);
200
+ } catch {
201
+ // Preserve the original agy failure; session persistence is best effort.
202
+ }
203
+ }
204
+ if (budgetController.signal.aborted && !signal?.aborted) {
205
+ throw new Error(`agy timed out after ${options.timeout_ms}ms`);
206
+ }
207
+ throw error;
208
+ } finally {
209
+ clearTimeout(budgetTimer);
210
+ }
211
+ }
212
+
213
+ export function validateAgyExecutionOptions(options: AgyExecutionOptions): void {
214
+ if (!options.prompt?.trim()) throw new Error("agy prompt must not be empty");
215
+ if (!Number.isFinite(options.timeout_ms) || options.timeout_ms <= 0) {
216
+ throw new Error("agy timeout_ms must be a positive finite number");
217
+ }
218
+ if (options.continue && options.conversation_id) {
219
+ throw new Error("agy cannot use --continue and --conversation together");
220
+ }
221
+ if (options.new_session === true && (options.continue || options.conversation_id)) {
222
+ throw new Error("agy new_session cannot be combined with a conversation to resume");
223
+ }
224
+ }
225
+
226
+ function remainingBudget(startedAt: number, timeoutMs: number): number {
227
+ const remaining = timeoutMs - (Date.now() - startedAt);
228
+ if (remaining <= 0) throw new Error("agy timed out");
229
+ return remaining;
230
+ }
231
+
232
+ /**
233
+ * Retry once when agy fails before emitting any activity (tool step or model
234
+ * response) with a transient error (rate limit, network blip). Zero activity
235
+ * means no tool steps ran, so the retry cannot double-apply edits.
236
+ */
237
+ async function runWithTransientRetry<T>(
238
+ attempt: (trackProgress: (message: string) => void) => Promise<T>,
239
+ onProgress?: (message: string) => void,
240
+ ): Promise<T> {
241
+ for (let tries = 0; ; tries++) {
242
+ let sawActivity = false;
243
+ const trackProgress = (message: string, kind?: "status" | "activity") => {
244
+ if (kind === "activity") sawActivity = true;
245
+ onProgress?.(message);
246
+ };
247
+ try {
248
+ return await attempt(trackProgress);
249
+ } catch (error) {
250
+ const message = error instanceof Error ? error.message : String(error);
251
+ if (
252
+ tries === 0 &&
253
+ !sawActivity &&
254
+ isTransientAgyFailure(message) &&
255
+ !/\b(?:ETIMEDOUT|timed out)\b/i.test(message)
256
+ ) {
257
+ onProgress?.("agy: transient failure before any work — retrying once…");
258
+ continue;
259
+ }
260
+ throw error;
261
+ }
262
+ }
263
+ }
@@ -0,0 +1,185 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import {
3
+ mkdir,
4
+ readFile,
5
+ realpath,
6
+ rm,
7
+ stat as statFile,
8
+ utimes,
9
+ writeFile,
10
+ } from "node:fs/promises";
11
+ import * as os from "node:os";
12
+ import * as path from "node:path";
13
+
14
+ const chains = new Map<string, Promise<void>>();
15
+ const LOCK_RETRY_MS = 25;
16
+ const LOCK_STALE_MS = 30_000;
17
+ // The lock is held for the whole agy run (minutes), far longer than the
18
+ // stale threshold — refresh mtime while held so a live holder is never
19
+ // mistaken for a crashed one.
20
+ const LOCK_HEARTBEAT_MS = 5_000;
21
+
22
+ /**
23
+ * Serialize agy_execute calls that share the same working directory.
24
+ * When `timeoutMs` is set, waiting for the lock counts against the budget
25
+ * so a call queued behind a long run cannot silently exceed its timeout.
26
+ * Combines an in-process queue with a filesystem lock so separate Pi
27
+ * processes cannot enter the same directory concurrently.
28
+ */
29
+ export async function canonicalDir(dir: string): Promise<string> {
30
+ try {
31
+ return await realpath(path.resolve(dir));
32
+ } catch {
33
+ return path.resolve(dir);
34
+ }
35
+ }
36
+
37
+ export function getDirLockPath(canonical: string): string {
38
+ const hash = createHash("sha256").update(canonical).digest("hex").slice(0, 32);
39
+ const base =
40
+ process.env.PI_CODING_AGENT_DIR?.trim() || path.join(os.homedir(), ".pi", "agent");
41
+ return path.join(base, "agy-dirlocks", `${hash}.lock`);
42
+ }
43
+
44
+ /** Refresh a held lock so the stale-lock recovery cannot steal it mid-run. */
45
+ export async function touchDirLock(lockPath: string): Promise<void> {
46
+ const now = new Date();
47
+ await utimes(lockPath, now, now);
48
+ }
49
+
50
+ async function withFileLock<T>(
51
+ lockPath: string,
52
+ fn: () => Promise<T>,
53
+ signal?: AbortSignal,
54
+ deadline?: number,
55
+ ): Promise<T> {
56
+ await mkdir(path.dirname(lockPath), { recursive: true });
57
+ while (true) {
58
+ if (signal?.aborted) throw new Error("agy was cancelled while waiting");
59
+ if (deadline !== undefined && Date.now() >= deadline) {
60
+ throw new Error("agy timed out waiting for a previous run in the same directory");
61
+ }
62
+ try {
63
+ await mkdir(lockPath);
64
+ break;
65
+ } catch (error) {
66
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
67
+ try {
68
+ const lockStat = await statFile(lockPath);
69
+ if (Date.now() - lockStat.mtimeMs > LOCK_STALE_MS) {
70
+ await rm(lockPath, { recursive: true, force: true });
71
+ continue;
72
+ }
73
+ } catch {
74
+ continue;
75
+ }
76
+ await new Promise<void>((resolve, reject) => {
77
+ const timer = setTimeout(() => {
78
+ signal?.removeEventListener("abort", onAbort);
79
+ resolve();
80
+ }, LOCK_RETRY_MS);
81
+ const onAbort = () => {
82
+ clearTimeout(timer);
83
+ reject(new Error("agy was cancelled while waiting"));
84
+ };
85
+ signal?.addEventListener("abort", onAbort, { once: true });
86
+ });
87
+ }
88
+ }
89
+ const owner = `${process.pid}.${randomUUID()}`;
90
+ try {
91
+ await writeFile(path.join(lockPath, "owner"), owner, {
92
+ encoding: "utf8",
93
+ mode: 0o600,
94
+ }).catch(() => undefined);
95
+ const heartbeat = setInterval(() => {
96
+ touchDirLock(lockPath).catch(() => undefined);
97
+ }, LOCK_HEARTBEAT_MS);
98
+ try {
99
+ return await fn();
100
+ } finally {
101
+ clearInterval(heartbeat);
102
+ }
103
+ } finally {
104
+ // Only remove our own lock — a stale recovery may have handed the
105
+ // directory to another process while we were suspended (e.g. sleep).
106
+ try {
107
+ if ((await readFile(path.join(lockPath, "owner"), "utf8")) === owner) {
108
+ await rm(lockPath, { recursive: true, force: true });
109
+ }
110
+ } catch {
111
+ // Lock already gone; nothing to clean up.
112
+ }
113
+ }
114
+ }
115
+
116
+ export async function withDirLock<T>(
117
+ dir: string,
118
+ fn: () => Promise<T>,
119
+ signal?: AbortSignal,
120
+ timeoutMs?: number,
121
+ ): Promise<T> {
122
+ // Normalize equivalent relative and absolute paths so the per-directory
123
+ // guarantee cannot be bypassed by path spelling.
124
+ const key = await canonicalDir(dir);
125
+ const deadline = timeoutMs !== undefined ? Date.now() + timeoutMs : undefined;
126
+ const prev = chains.get(key) ?? Promise.resolve();
127
+ let release!: () => void;
128
+ const gate = new Promise<void>((resolve) => {
129
+ release = resolve;
130
+ });
131
+ const tail = prev.then(() => gate);
132
+ chains.set(key, tail);
133
+ // Keep the tail registered until its predecessor and gate have both settled.
134
+ // Otherwise a cancelled waiter can delete the chain while an earlier run is
135
+ // still active, allowing a later caller to enter concurrently.
136
+ void tail.then(() => {
137
+ if (chains.get(key) === tail) chains.delete(key);
138
+ });
139
+
140
+ try {
141
+ await waitForTurn(prev, signal, deadline);
142
+ return await withFileLock(getDirLockPath(key), fn, signal, deadline);
143
+ } finally {
144
+ // A cancelled waiter still owns a gate in the chain. Release it so later
145
+ // calls are not stranded behind work that will never run.
146
+ release();
147
+ }
148
+ }
149
+
150
+ function waitForTurn(prev: Promise<void>, signal?: AbortSignal, deadline?: number): Promise<void> {
151
+ if (signal?.aborted) return Promise.reject(new Error("agy was cancelled while waiting"));
152
+ if (deadline !== undefined && Date.now() >= deadline) {
153
+ return Promise.reject(
154
+ new Error("agy timed out waiting for a previous run in the same directory"),
155
+ );
156
+ }
157
+ if (!signal && deadline === undefined) return prev;
158
+
159
+ return new Promise<void>((resolve, reject) => {
160
+ const onAbort = () => finish(() => reject(new Error("agy was cancelled while waiting")));
161
+ let timer: ReturnType<typeof setTimeout> | undefined;
162
+
163
+ const finish = (settle: () => void) => {
164
+ signal?.removeEventListener("abort", onAbort);
165
+ if (timer !== undefined) clearTimeout(timer);
166
+ settle();
167
+ };
168
+
169
+ if (deadline !== undefined) {
170
+ timer = setTimeout(
171
+ () =>
172
+ finish(() =>
173
+ reject(new Error("agy timed out waiting for a previous run in the same directory")),
174
+ ),
175
+ Math.max(deadline - Date.now(), 0),
176
+ );
177
+ }
178
+
179
+ signal?.addEventListener("abort", onAbort, { once: true });
180
+ prev.then(
181
+ () => finish(resolve),
182
+ (error) => finish(() => reject(error)),
183
+ );
184
+ });
185
+ }
@@ -0,0 +1,22 @@
1
+ const DEFAULT_MAX_OUTPUT_CHARS = 8000;
2
+
3
+ export function truncate(text: string, max = DEFAULT_MAX_OUTPUT_CHARS): string {
4
+ if (text.length <= max) return text;
5
+ if (max <= 0) return "";
6
+
7
+ const markerPrefix = "\n\n(Output truncated: ";
8
+ const markerSuffix = " chars omitted)\n\n";
9
+ let marker = `${markerPrefix}${text.length - max}${markerSuffix}`;
10
+ const available = max - marker.length;
11
+ if (available <= 0) return text.slice(0, max);
12
+
13
+ const headLength = Math.ceil(available / 2);
14
+ const tailLength = available - headLength;
15
+ const omitted = text.length - headLength - tailLength;
16
+ marker = `${markerPrefix}${omitted}${markerSuffix}`;
17
+ return (
18
+ text.slice(0, headLength) +
19
+ marker +
20
+ (tailLength > 0 ? text.slice(-tailLength) : "")
21
+ );
22
+ }
@@ -0,0 +1,13 @@
1
+ /** Parse agy --output-format json responses; fall back to raw on schema drift. */
2
+ export function parseJsonResponse(raw: string): string {
3
+ try {
4
+ const parsed: unknown = JSON.parse(raw);
5
+ if (typeof parsed === "object" && parsed !== null && "response" in parsed) {
6
+ const response = (parsed as { response?: unknown }).response;
7
+ if (typeof response === "string") return response;
8
+ }
9
+ } catch {
10
+ // Raw text is a valid fallback when the CLI schema changes.
11
+ }
12
+ return raw;
13
+ }