@juanbenjumea/pi-agy 0.6.1 → 0.6.3
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.
- package/CHANGELOG.md +16 -0
- package/README.md +35 -8
- package/extensions/commands.ts +111 -14
- package/extensions/index.ts +35 -1
- package/extensions/lib/cli.ts +50 -5
- package/extensions/lib/context.ts +103 -0
- package/extensions/lib/doctor.ts +288 -0
- package/extensions/lib/execute.ts +92 -19
- package/extensions/lib/render.ts +213 -0
- package/package.json +4 -2
- package/skills/agy/SKILL.md +6 -3
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
import { readFile, stat as statFile } from "node:fs/promises";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
checkAgyUsage,
|
|
6
|
+
inspectAgyModels,
|
|
7
|
+
inspectAgyVersion,
|
|
8
|
+
isAgyModel,
|
|
9
|
+
isAgyQuotaExhausted,
|
|
10
|
+
type AgyUsageSnapshot,
|
|
11
|
+
} from "./cli.js";
|
|
12
|
+
import { getDefaultConfigPath } from "./config.js";
|
|
13
|
+
import { canonicalDir, getDirLockPath } from "./lock.js";
|
|
14
|
+
import { getDefaultStorePath, getHistory } from "./sessions.js";
|
|
15
|
+
import { detectVerifyCommand } from "./verify.js";
|
|
16
|
+
|
|
17
|
+
export type AgyDoctorStatus = "ok" | "info" | "warn" | "error";
|
|
18
|
+
|
|
19
|
+
export interface AgyDoctorCheck {
|
|
20
|
+
name: string;
|
|
21
|
+
status: AgyDoctorStatus;
|
|
22
|
+
detail: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface AgyDoctorReport {
|
|
26
|
+
cwd: string;
|
|
27
|
+
checks: AgyDoctorCheck[];
|
|
28
|
+
text: string;
|
|
29
|
+
status: "ok" | "warn" | "error";
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const DOCTOR_TIMEOUT_MS = 10_000;
|
|
33
|
+
|
|
34
|
+
/** Inspect agy and local extension state without starting a model turn. */
|
|
35
|
+
export async function runAgyDoctor(
|
|
36
|
+
cwd: string,
|
|
37
|
+
signal?: AbortSignal,
|
|
38
|
+
): Promise<AgyDoctorReport> {
|
|
39
|
+
const resolvedCwd = path.resolve(cwd);
|
|
40
|
+
const checks: AgyDoctorCheck[] = [];
|
|
41
|
+
|
|
42
|
+
throwIfCancelled(signal);
|
|
43
|
+
let cliAvailable = false;
|
|
44
|
+
try {
|
|
45
|
+
const version = await inspectAgyVersion(resolvedCwd, signal, DOCTOR_TIMEOUT_MS);
|
|
46
|
+
checks.push({
|
|
47
|
+
name: "CLI",
|
|
48
|
+
status: "ok",
|
|
49
|
+
detail: version ? `agy ${version.replace(/^agy\s*/i, "")}` : "agy responded",
|
|
50
|
+
});
|
|
51
|
+
cliAvailable = true;
|
|
52
|
+
} catch (error) {
|
|
53
|
+
throwIfCancelled(signal);
|
|
54
|
+
checks.push({ name: "CLI", status: "error", detail: errorMessage(error) });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (cliAvailable) {
|
|
58
|
+
const [modelsResult, usageResult] = await Promise.allSettled([
|
|
59
|
+
inspectAgyModels(resolvedCwd, signal, DOCTOR_TIMEOUT_MS),
|
|
60
|
+
checkAgyUsage(resolvedCwd, signal, DOCTOR_TIMEOUT_MS),
|
|
61
|
+
]);
|
|
62
|
+
|
|
63
|
+
throwIfCancelled(signal);
|
|
64
|
+
if (modelsResult.status === "fulfilled") {
|
|
65
|
+
const entries = Object.entries(modelsResult.value);
|
|
66
|
+
checks.push({
|
|
67
|
+
name: "Models",
|
|
68
|
+
status: entries.length ? "ok" : "warn",
|
|
69
|
+
detail: entries.length
|
|
70
|
+
? `${entries.length} aliases discovered (${entries.map(([alias]) => alias).join(", ")})`
|
|
71
|
+
: "agy models returned no supported stable model aliases",
|
|
72
|
+
});
|
|
73
|
+
} else {
|
|
74
|
+
checks.push({ name: "Models", status: "error", detail: errorMessage(modelsResult.reason) });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (usageResult.status === "fulfilled") {
|
|
78
|
+
checks.push(quotaCheck(usageResult.value));
|
|
79
|
+
} else {
|
|
80
|
+
checks.push({ name: "Quota", status: "warn", detail: errorMessage(usageResult.reason) });
|
|
81
|
+
}
|
|
82
|
+
} else {
|
|
83
|
+
checks.push({ name: "Models", status: "info", detail: "skipped because the CLI check failed" });
|
|
84
|
+
checks.push({ name: "Quota", status: "info", detail: "skipped because the CLI check failed" });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
checks.push(await configCheck(signal));
|
|
88
|
+
throwIfCancelled(signal);
|
|
89
|
+
checks.push(await sessionsCheck(resolvedCwd, signal));
|
|
90
|
+
throwIfCancelled(signal);
|
|
91
|
+
checks.push(await lockCheck(resolvedCwd));
|
|
92
|
+
throwIfCancelled(signal);
|
|
93
|
+
|
|
94
|
+
try {
|
|
95
|
+
const verify = await detectVerifyCommand(resolvedCwd);
|
|
96
|
+
checks.push({
|
|
97
|
+
name: "Verify",
|
|
98
|
+
status: verify ? "ok" : "info",
|
|
99
|
+
detail: verify ?? "no supported repository gate detected",
|
|
100
|
+
});
|
|
101
|
+
} catch (error) {
|
|
102
|
+
checks.push({ name: "Verify", status: "warn", detail: errorMessage(error) });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const status = checks.some((check) => check.status === "error")
|
|
106
|
+
? "error"
|
|
107
|
+
: checks.some((check) => check.status === "warn")
|
|
108
|
+
? "warn"
|
|
109
|
+
: "ok";
|
|
110
|
+
return {
|
|
111
|
+
cwd: resolvedCwd,
|
|
112
|
+
checks,
|
|
113
|
+
status,
|
|
114
|
+
text: formatAgyDoctorReport(resolvedCwd, checks),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function formatAgyDoctorReport(cwd: string, checks: AgyDoctorCheck[]): string {
|
|
119
|
+
const icon: Record<AgyDoctorStatus, string> = {
|
|
120
|
+
ok: "✓",
|
|
121
|
+
info: "•",
|
|
122
|
+
warn: "!",
|
|
123
|
+
error: "✗",
|
|
124
|
+
};
|
|
125
|
+
return [
|
|
126
|
+
`agy doctor — ${cwd}`,
|
|
127
|
+
...checks.map((check) => `${icon[check.status]} ${check.name}: ${check.detail}`),
|
|
128
|
+
].join("\n");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function quotaCheck(snapshot: AgyUsageSnapshot | undefined): AgyDoctorCheck {
|
|
132
|
+
if (!snapshot) {
|
|
133
|
+
return { name: "Quota", status: "warn", detail: "usage information is unavailable" };
|
|
134
|
+
}
|
|
135
|
+
if (snapshot.error) {
|
|
136
|
+
return { name: "Quota", status: "warn", detail: snapshot.error };
|
|
137
|
+
}
|
|
138
|
+
if (snapshot.models.length === 0) {
|
|
139
|
+
return {
|
|
140
|
+
name: "Quota",
|
|
141
|
+
status: "warn",
|
|
142
|
+
detail: snapshot.raw_summary
|
|
143
|
+
? "usage command responded but no quota records were recognized"
|
|
144
|
+
: "usage command returned no quota records",
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
const groups = new Set(snapshot.models.map((entry) => entry.model));
|
|
148
|
+
const exhausted = snapshot.models.filter((entry) => isAgyQuotaExhausted(entry));
|
|
149
|
+
if (exhausted.length) {
|
|
150
|
+
const exhaustedGroups = new Set(exhausted.map((entry) => entry.model));
|
|
151
|
+
const affected = exhausted
|
|
152
|
+
.map((entry) => {
|
|
153
|
+
const window = entry.window ? ` ${entry.window}` : "";
|
|
154
|
+
const reset = entry.reset_at ? `; resets ${entry.reset_at}` : "";
|
|
155
|
+
return `${entry.model}${window}${reset}`;
|
|
156
|
+
})
|
|
157
|
+
.join(", ");
|
|
158
|
+
return {
|
|
159
|
+
name: "Quota",
|
|
160
|
+
status: exhaustedGroups.size === groups.size ? "error" : "warn",
|
|
161
|
+
detail: `exhausted: ${affected}`,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
name: "Quota",
|
|
166
|
+
status: "ok",
|
|
167
|
+
detail: `${snapshot.models.length} windows across ${groups.size} model groups`,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function configCheck(signal?: AbortSignal): Promise<AgyDoctorCheck> {
|
|
172
|
+
const configPath = getDefaultConfigPath();
|
|
173
|
+
try {
|
|
174
|
+
const raw = await readFile(configPath, { encoding: "utf8", signal });
|
|
175
|
+
const parsed: unknown = JSON.parse(raw);
|
|
176
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
177
|
+
return { name: "Config", status: "warn", detail: `${configPath} is not a JSON object` };
|
|
178
|
+
}
|
|
179
|
+
const record = parsed as Record<string, unknown>;
|
|
180
|
+
const invalid: string[] = [];
|
|
181
|
+
const rawModel = record.defaultModel;
|
|
182
|
+
const validModel =
|
|
183
|
+
typeof rawModel === "string" &&
|
|
184
|
+
(rawModel === "flash" || rawModel === "pro" || isAgyModel(rawModel));
|
|
185
|
+
if ("defaultModel" in record && typeof rawModel !== "string") {
|
|
186
|
+
invalid.push("defaultModel must be a string");
|
|
187
|
+
} else if (typeof rawModel === "string" && !validModel) {
|
|
188
|
+
invalid.push(`unknown defaultModel '${rawModel}'`);
|
|
189
|
+
}
|
|
190
|
+
if (
|
|
191
|
+
"defaultModelCommand" in record &&
|
|
192
|
+
typeof record.defaultModelCommand !== "string"
|
|
193
|
+
) {
|
|
194
|
+
invalid.push("defaultModelCommand must be a string");
|
|
195
|
+
}
|
|
196
|
+
if ("quotaBalancing" in record && typeof record.quotaBalancing !== "boolean") {
|
|
197
|
+
invalid.push("quotaBalancing must be boolean");
|
|
198
|
+
}
|
|
199
|
+
if ("skipPermissions" in record && typeof record.skipPermissions !== "boolean") {
|
|
200
|
+
invalid.push("skipPermissions must be boolean (fails closed)");
|
|
201
|
+
}
|
|
202
|
+
const model = validModel
|
|
203
|
+
? rawModel
|
|
204
|
+
: typeof record.defaultModelCommand === "string" && record.defaultModelCommand.trim()
|
|
205
|
+
? "command"
|
|
206
|
+
: record.quotaBalancing === true
|
|
207
|
+
? "quota-balanced"
|
|
208
|
+
: "built-in";
|
|
209
|
+
const permissions =
|
|
210
|
+
record.skipPermissions === false ||
|
|
211
|
+
("skipPermissions" in record && typeof record.skipPermissions !== "boolean")
|
|
212
|
+
? "permission bypass off"
|
|
213
|
+
: "permission bypass on";
|
|
214
|
+
return {
|
|
215
|
+
name: "Config",
|
|
216
|
+
status: invalid.length ? "warn" : "ok",
|
|
217
|
+
detail: invalid.length
|
|
218
|
+
? `${configPath} · ${invalid.join("; ")}`
|
|
219
|
+
: `${configPath} · default ${model} · ${permissions}`,
|
|
220
|
+
};
|
|
221
|
+
} catch (error) {
|
|
222
|
+
throwIfCancelled(signal);
|
|
223
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
224
|
+
return { name: "Config", status: "info", detail: `defaults (${configPath} not present)` };
|
|
225
|
+
}
|
|
226
|
+
if (error instanceof SyntaxError) {
|
|
227
|
+
return { name: "Config", status: "warn", detail: `${configPath} contains invalid JSON` };
|
|
228
|
+
}
|
|
229
|
+
return { name: "Config", status: "warn", detail: errorMessage(error) };
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function sessionsCheck(cwd: string, signal?: AbortSignal): Promise<AgyDoctorCheck> {
|
|
234
|
+
const storePath = getDefaultStorePath();
|
|
235
|
+
try {
|
|
236
|
+
const parsed: unknown = JSON.parse(
|
|
237
|
+
await readFile(storePath, { encoding: "utf8", signal }),
|
|
238
|
+
);
|
|
239
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
240
|
+
return { name: "Sessions", status: "warn", detail: `${storePath} has an invalid shape` };
|
|
241
|
+
}
|
|
242
|
+
const history = await getHistory(cwd);
|
|
243
|
+
return {
|
|
244
|
+
name: "Sessions",
|
|
245
|
+
status: "ok",
|
|
246
|
+
detail: `${history.length} recorded for this workspace · ${storePath}`,
|
|
247
|
+
};
|
|
248
|
+
} catch (error) {
|
|
249
|
+
throwIfCancelled(signal);
|
|
250
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
251
|
+
return { name: "Sessions", status: "info", detail: `none recorded (${storePath} not present)` };
|
|
252
|
+
}
|
|
253
|
+
if (error instanceof SyntaxError) {
|
|
254
|
+
return { name: "Sessions", status: "warn", detail: `${storePath} contains invalid JSON` };
|
|
255
|
+
}
|
|
256
|
+
return { name: "Sessions", status: "warn", detail: errorMessage(error) };
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async function lockCheck(cwd: string): Promise<AgyDoctorCheck> {
|
|
261
|
+
const canonical = await canonicalDir(cwd);
|
|
262
|
+
const lockPath = getDirLockPath(canonical);
|
|
263
|
+
try {
|
|
264
|
+
const lock = await statFile(lockPath);
|
|
265
|
+
const ageSeconds = Math.max(0, Math.round((Date.now() - lock.mtimeMs) / 1_000));
|
|
266
|
+
return {
|
|
267
|
+
name: "Workspace lock",
|
|
268
|
+
status: "warn",
|
|
269
|
+
detail:
|
|
270
|
+
ageSeconds > 30
|
|
271
|
+
? `stale (${ageSeconds}s old; auto-recovers on next run) · ${lockPath}`
|
|
272
|
+
: `active (${ageSeconds}s old) · ${lockPath}`,
|
|
273
|
+
};
|
|
274
|
+
} catch (error) {
|
|
275
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
276
|
+
return { name: "Workspace lock", status: "ok", detail: "free" };
|
|
277
|
+
}
|
|
278
|
+
return { name: "Workspace lock", status: "warn", detail: errorMessage(error) };
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function throwIfCancelled(signal?: AbortSignal): void {
|
|
283
|
+
if (signal?.aborted) throw new Error("agy doctor was cancelled");
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function errorMessage(error: unknown): string {
|
|
287
|
+
return error instanceof Error ? error.message : String(error);
|
|
288
|
+
}
|
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
type AgyUsageSnapshot,
|
|
17
17
|
} from "./cli.js";
|
|
18
18
|
import { loadAgyConfig, resolveDefaultModel } from "./config.js";
|
|
19
|
+
import type { AgyContextMode } from "./context.js";
|
|
19
20
|
import type { AgyUsage } from "./stream.js";
|
|
20
21
|
import { withDirLock } from "./lock.js";
|
|
21
22
|
import {
|
|
@@ -23,7 +24,7 @@ import {
|
|
|
23
24
|
summarizeGitDiffSince,
|
|
24
25
|
type GitBaseline,
|
|
25
26
|
} from "./postflight.js";
|
|
26
|
-
import { runPreflight } from "./preflight.js";
|
|
27
|
+
import { resetPreflightCache, runPreflight } from "./preflight.js";
|
|
27
28
|
import { getSession, saveSession, conversationSummary } from "./sessions.js";
|
|
28
29
|
|
|
29
30
|
export type AgyMode = "plan" | "accept-edits" | "sandbox";
|
|
@@ -41,6 +42,9 @@ export interface AgyExecutionOptions {
|
|
|
41
42
|
continue?: boolean;
|
|
42
43
|
new_session?: boolean;
|
|
43
44
|
stream?: boolean;
|
|
45
|
+
context?: AgyContextMode;
|
|
46
|
+
/** Pre-serialized bounded Pi context; supplied only when context is not none. */
|
|
47
|
+
context_text?: string;
|
|
44
48
|
}
|
|
45
49
|
|
|
46
50
|
export interface AgyExecutionDetails {
|
|
@@ -55,6 +59,8 @@ export interface AgyExecutionDetails {
|
|
|
55
59
|
duration_seconds?: number;
|
|
56
60
|
changed_files?: string[];
|
|
57
61
|
preexisting_files?: string[];
|
|
62
|
+
context_mode?: AgyContextMode;
|
|
63
|
+
context_chars?: number;
|
|
58
64
|
/** Model-specific quota information refreshed before the run, when supported. */
|
|
59
65
|
quota?: AgyUsageSnapshot;
|
|
60
66
|
quota_status?: "available" | "unknown";
|
|
@@ -86,9 +92,11 @@ export async function executeAgyTask(
|
|
|
86
92
|
const config = await loadAgyConfig(undefined, abortSignal);
|
|
87
93
|
// Explicit model → legacy tier → configured default → flash-medium.
|
|
88
94
|
const selectedModel = resolveAgyModelAlias(options.model, options.tier);
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
effectiveModel = model
|
|
95
|
+
const resolvedModel = selectedModel ?? (await resolveDefaultModel(config, abortSignal));
|
|
96
|
+
let model: AgyModel = resolvedModel ?? "flash-medium";
|
|
97
|
+
effectiveModel = model;
|
|
98
|
+
const autoModelSelection =
|
|
99
|
+
!selectedModel && !config.defaultModel && !config.defaultModelCommand;
|
|
92
100
|
const skipPermissions = config.skipPermissions !== false;
|
|
93
101
|
|
|
94
102
|
return await withDirLock(
|
|
@@ -126,6 +134,7 @@ export async function executeAgyTask(
|
|
|
126
134
|
options.mode,
|
|
127
135
|
useDigest,
|
|
128
136
|
verifyCmd,
|
|
137
|
+
options.context_text,
|
|
129
138
|
);
|
|
130
139
|
|
|
131
140
|
let quota: AgyUsageSnapshot | undefined;
|
|
@@ -143,20 +152,31 @@ export async function executeAgyTask(
|
|
|
143
152
|
const quotaSummary = quota ? formatAgyUsage(quota, selectedModelId) : undefined;
|
|
144
153
|
if (quotaSummary) onProgress?.(quotaSummary);
|
|
145
154
|
if (selectedQuotas.some((entry) => isAgyQuotaExhausted(entry))) {
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
.every((entry) => !isAgyQuotaExhausted(entry)),
|
|
155
|
+
const fallback = autoModelSelection
|
|
156
|
+
? findAvailableFallbackModel(quota, model)
|
|
157
|
+
: undefined;
|
|
158
|
+
if (fallback) {
|
|
159
|
+
onProgress?.(
|
|
160
|
+
`agy: ${selectedModelId} quota exhausted; falling back to ${resolveAgyModelId(fallback)}…`,
|
|
153
161
|
);
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
162
|
+
model = fallback;
|
|
163
|
+
effectiveModel = fallback;
|
|
164
|
+
} else {
|
|
165
|
+
const quotaEntries = quota?.models ?? [];
|
|
166
|
+
const alternatives = [...new Set(quotaEntries.map((entry) => entry.model))]
|
|
167
|
+
.filter((candidate) => candidate.toLowerCase() !== selectedModelId.toLowerCase())
|
|
168
|
+
.filter((candidate) =>
|
|
169
|
+
quotaEntries
|
|
170
|
+
.filter((entry) => entry.model === candidate)
|
|
171
|
+
.every((entry) => !isAgyQuotaExhausted(entry)),
|
|
172
|
+
);
|
|
173
|
+
const alternativeText = alternatives.length
|
|
174
|
+
? ` Available reported alternatives: ${alternatives.join(", ")}.`
|
|
175
|
+
: " No available alternative was reported.";
|
|
176
|
+
throw new Error(
|
|
177
|
+
`agy quota exhausted for ${selectedModelId}; choose another model or run agy_usage first.${alternativeText}\n${quotaSummary ?? ""}`,
|
|
178
|
+
);
|
|
179
|
+
}
|
|
160
180
|
}
|
|
161
181
|
const runTimeoutMs = remainingBudget(startedAt, options.timeout_ms);
|
|
162
182
|
// Emitted via onProgress directly: progress tracking (and therefore
|
|
@@ -181,7 +201,7 @@ export async function executeAgyTask(
|
|
|
181
201
|
abortSignal,
|
|
182
202
|
trackProgress,
|
|
183
203
|
);
|
|
184
|
-
}, onProgress);
|
|
204
|
+
}, onProgress, abortSignal);
|
|
185
205
|
|
|
186
206
|
if (run.conversation_id) {
|
|
187
207
|
try {
|
|
@@ -240,6 +260,8 @@ export async function executeAgyTask(
|
|
|
240
260
|
duration_seconds: run.duration_seconds,
|
|
241
261
|
changed_files: changedFiles,
|
|
242
262
|
preexisting_files: preexistingFiles,
|
|
263
|
+
context_mode: options.context ?? "none",
|
|
264
|
+
context_chars: options.context_text?.length ?? 0,
|
|
243
265
|
quota,
|
|
244
266
|
quota_status: quotaStatus,
|
|
245
267
|
},
|
|
@@ -295,6 +317,29 @@ function remainingBudget(startedAt: number, timeoutMs: number): number {
|
|
|
295
317
|
return remaining;
|
|
296
318
|
}
|
|
297
319
|
|
|
320
|
+
const FALLBACK_MODELS: readonly AgyModel[] = [
|
|
321
|
+
"flash-medium",
|
|
322
|
+
"flash-low",
|
|
323
|
+
"flash-high",
|
|
324
|
+
"pro-low",
|
|
325
|
+
"pro-high",
|
|
326
|
+
"gpt-oss",
|
|
327
|
+
"sonnet",
|
|
328
|
+
"opus",
|
|
329
|
+
];
|
|
330
|
+
|
|
331
|
+
function findAvailableFallbackModel(
|
|
332
|
+
snapshot: AgyUsageSnapshot | undefined,
|
|
333
|
+
current: AgyModel,
|
|
334
|
+
): AgyModel | undefined {
|
|
335
|
+
if (!snapshot) return undefined;
|
|
336
|
+
return FALLBACK_MODELS.find((candidate) => {
|
|
337
|
+
if (candidate === current) return false;
|
|
338
|
+
const entries = findAgyQuotaEntries(snapshot, resolveAgyModelId(candidate));
|
|
339
|
+
return entries.length > 0 && entries.every((entry) => !isAgyQuotaExhausted(entry));
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
|
|
298
343
|
/**
|
|
299
344
|
* Retry once when agy fails before emitting any activity (tool step or model
|
|
300
345
|
* response) with a transient error (rate limit, network blip). Zero activity
|
|
@@ -303,6 +348,7 @@ function remainingBudget(startedAt: number, timeoutMs: number): number {
|
|
|
303
348
|
async function runWithTransientRetry<T>(
|
|
304
349
|
attempt: (trackProgress: (message: string) => void) => Promise<T>,
|
|
305
350
|
onProgress?: (message: string) => void,
|
|
351
|
+
signal?: AbortSignal,
|
|
306
352
|
): Promise<T> {
|
|
307
353
|
for (let tries = 0; ; tries++) {
|
|
308
354
|
let sawActivity = false;
|
|
@@ -320,10 +366,37 @@ async function runWithTransientRetry<T>(
|
|
|
320
366
|
isTransientAgyFailure(message) &&
|
|
321
367
|
!/\b(?:ETIMEDOUT|timed out)\b/i.test(message)
|
|
322
368
|
) {
|
|
323
|
-
|
|
369
|
+
const quotaMayHaveChanged = /resource[_ -]?exhausted|429/i.test(message);
|
|
370
|
+
if (quotaMayHaveChanged) resetPreflightCache();
|
|
371
|
+
onProgress?.(
|
|
372
|
+
quotaMayHaveChanged
|
|
373
|
+
? "agy: quota request was rejected before any work — refreshing quota and retrying once…"
|
|
374
|
+
: "agy: transient failure before any work — retrying once…",
|
|
375
|
+
);
|
|
376
|
+
await delayBeforeRetry(signal);
|
|
324
377
|
continue;
|
|
325
378
|
}
|
|
326
379
|
throw error;
|
|
327
380
|
}
|
|
328
381
|
}
|
|
329
382
|
}
|
|
383
|
+
|
|
384
|
+
function delayBeforeRetry(signal?: AbortSignal): Promise<void> {
|
|
385
|
+
return new Promise((resolve, reject) => {
|
|
386
|
+
const timer = setTimeout(resolve, 1_000);
|
|
387
|
+
if (!signal) return;
|
|
388
|
+
if (signal.aborted) {
|
|
389
|
+
clearTimeout(timer);
|
|
390
|
+
reject(signal.reason ?? new Error("agy retry cancelled"));
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
signal.addEventListener(
|
|
394
|
+
"abort",
|
|
395
|
+
() => {
|
|
396
|
+
clearTimeout(timer);
|
|
397
|
+
reject(signal.reason ?? new Error("agy retry cancelled"));
|
|
398
|
+
},
|
|
399
|
+
{ once: true },
|
|
400
|
+
);
|
|
401
|
+
});
|
|
402
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { keyHint, type Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { stripTerminalSequences, Text, truncateToWidth } from "@earendil-works/pi-tui";
|
|
3
|
+
|
|
4
|
+
import type { AgyExecutionDetails } from "./execute.js";
|
|
5
|
+
|
|
6
|
+
export const AGY_RUN_ENTRY_TYPE = "agy-run-receipt";
|
|
7
|
+
|
|
8
|
+
export interface AgyRunReceipt {
|
|
9
|
+
task: string;
|
|
10
|
+
text: string;
|
|
11
|
+
details: AgyExecutionDetails;
|
|
12
|
+
completed_at: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
interface RenderResultLike {
|
|
16
|
+
content: unknown;
|
|
17
|
+
details?: unknown;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface RenderOptions {
|
|
21
|
+
expanded: boolean;
|
|
22
|
+
isPartial?: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface RenderContext {
|
|
26
|
+
isError?: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function oneLine(value: unknown, max: number): string {
|
|
30
|
+
const text = stripTerminalSequences(String(value ?? ""))
|
|
31
|
+
.replace(/\s+/g, " ")
|
|
32
|
+
.trim();
|
|
33
|
+
return truncateToWidth(text, max, "…");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function firstText(content: unknown): string {
|
|
37
|
+
if (!Array.isArray(content)) return "";
|
|
38
|
+
const part = content.find(
|
|
39
|
+
(item) =>
|
|
40
|
+
typeof item === "object" &&
|
|
41
|
+
item !== null &&
|
|
42
|
+
(item as { type?: unknown }).type === "text" &&
|
|
43
|
+
typeof (item as { text?: unknown }).text === "string",
|
|
44
|
+
) as { text?: string } | undefined;
|
|
45
|
+
return part?.text ?? "";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function stripSyntheticResultSections(value: string): string {
|
|
49
|
+
const markers = [
|
|
50
|
+
"\n\n## agy quota snapshot",
|
|
51
|
+
"\n\n## git diff --stat",
|
|
52
|
+
"\n\n## git diff --cached --stat",
|
|
53
|
+
"\n\nagy made no newly-dirty files",
|
|
54
|
+
];
|
|
55
|
+
const indexes = markers
|
|
56
|
+
.map((marker) => value.indexOf(marker))
|
|
57
|
+
.filter((index) => index >= 0);
|
|
58
|
+
const end = indexes.length ? Math.min(...indexes) : value.length;
|
|
59
|
+
return value.slice(0, end).trimEnd();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function renderAgyCall(
|
|
63
|
+
args: {
|
|
64
|
+
model?: unknown;
|
|
65
|
+
tier?: unknown;
|
|
66
|
+
mode?: unknown;
|
|
67
|
+
context?: unknown;
|
|
68
|
+
prompt?: unknown;
|
|
69
|
+
} | undefined,
|
|
70
|
+
theme: Theme,
|
|
71
|
+
): Text {
|
|
72
|
+
const callArgs = args ?? {};
|
|
73
|
+
const model = callArgs.model ?? callArgs.tier ?? "default";
|
|
74
|
+
const mode = callArgs.mode ?? "accept-edits";
|
|
75
|
+
const contextMode = callArgs.context ?? "none";
|
|
76
|
+
const header =
|
|
77
|
+
theme.fg("toolTitle", theme.bold("agy ")) +
|
|
78
|
+
theme.fg("accent", String(model)) +
|
|
79
|
+
theme.fg(
|
|
80
|
+
"dim",
|
|
81
|
+
` · ${String(mode)}${contextMode === "none" ? "" : ` · context ${String(contextMode)}`}`,
|
|
82
|
+
);
|
|
83
|
+
const promptLine = oneLine(callArgs.prompt, 180);
|
|
84
|
+
return new Text(
|
|
85
|
+
promptLine ? `${header}\n${theme.fg("muted", promptLine)}` : header,
|
|
86
|
+
0,
|
|
87
|
+
0,
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function formatAgyResult(
|
|
92
|
+
result: RenderResultLike,
|
|
93
|
+
{ expanded, isPartial }: RenderOptions,
|
|
94
|
+
theme: Theme,
|
|
95
|
+
context: RenderContext,
|
|
96
|
+
): string {
|
|
97
|
+
const body = firstText(result.content);
|
|
98
|
+
if (isPartial) {
|
|
99
|
+
return theme.fg("warning", "◌ ") + theme.fg("muted", oneLine(body || "agy: working…", 180));
|
|
100
|
+
}
|
|
101
|
+
if (context.isError) {
|
|
102
|
+
const errorBody = expanded ? stripTerminalSequences(body) : oneLine(body, 300);
|
|
103
|
+
return (
|
|
104
|
+
theme.fg("error", "✗ agy failed") +
|
|
105
|
+
(errorBody ? `\n${theme.fg("toolOutput", errorBody)}` : "")
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const details = result.details as AgyExecutionDetails | undefined;
|
|
110
|
+
if (!details) {
|
|
111
|
+
const displayBody = stripSyntheticResultSections(body);
|
|
112
|
+
const bodyLines = displayBody.split("\n");
|
|
113
|
+
const shown = expanded ? bodyLines : bodyLines.slice(0, 4);
|
|
114
|
+
if (!expanded && bodyLines.length > shown.length) {
|
|
115
|
+
shown.push(`… ${bodyLines.length - shown.length} more lines`);
|
|
116
|
+
}
|
|
117
|
+
return shown.join("\n");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const duration =
|
|
121
|
+
typeof details.duration_seconds === "number"
|
|
122
|
+
? ` · ${details.duration_seconds.toFixed(1)}s`
|
|
123
|
+
: "";
|
|
124
|
+
const lines = [
|
|
125
|
+
theme.fg("success", "✓ agy") +
|
|
126
|
+
theme.fg("muted", ` · ${details.model} · ${details.mode}${duration}`),
|
|
127
|
+
];
|
|
128
|
+
|
|
129
|
+
const metadata: string[] = [];
|
|
130
|
+
if (details.quota_status) metadata.push(`quota ${details.quota_status}`);
|
|
131
|
+
if (details.verify_cmd) metadata.push(`verify requested: ${details.verify_cmd}`);
|
|
132
|
+
if (details.context_mode && details.context_mode !== "none") {
|
|
133
|
+
metadata.push(`context ${details.context_mode} (${details.context_chars ?? 0} chars)`);
|
|
134
|
+
}
|
|
135
|
+
if (metadata.length) lines.push(theme.fg("dim", metadata.join(" · ")));
|
|
136
|
+
|
|
137
|
+
const changed = details.changed_files ?? [];
|
|
138
|
+
const preexisting = details.preexisting_files ?? [];
|
|
139
|
+
if (changed.length || preexisting.length) {
|
|
140
|
+
lines.push(
|
|
141
|
+
theme.fg(
|
|
142
|
+
"muted",
|
|
143
|
+
`${changed.length} changed by agy · ${preexisting.length} pre-existing`,
|
|
144
|
+
),
|
|
145
|
+
);
|
|
146
|
+
if (expanded) {
|
|
147
|
+
for (const file of changed) lines.push(theme.fg("toolDiffAdded", `+ ${file}`));
|
|
148
|
+
for (const file of preexisting) {
|
|
149
|
+
lines.push(theme.fg("toolDiffContext", `~ ${file} (pre-existing)`));
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
} else if (details.mode === "accept-edits") {
|
|
153
|
+
lines.push(theme.fg("muted", "0 files changed by agy"));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const displayBody = stripSyntheticResultSections(body);
|
|
157
|
+
if (displayBody) {
|
|
158
|
+
const bodyLines = displayBody.split("\n");
|
|
159
|
+
const shown = expanded ? bodyLines : bodyLines.slice(0, 4);
|
|
160
|
+
lines.push(...shown.map((line) => theme.fg("toolOutput", line)));
|
|
161
|
+
if (!expanded && bodyLines.length > shown.length) {
|
|
162
|
+
lines.push(
|
|
163
|
+
theme.fg(
|
|
164
|
+
"dim",
|
|
165
|
+
`… ${bodyLines.length - shown.length} more lines (${keyHint("app.tools.expand", "to expand")})`,
|
|
166
|
+
),
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return lines.join("\n");
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function renderAgyResult(
|
|
174
|
+
result: RenderResultLike,
|
|
175
|
+
options: RenderOptions,
|
|
176
|
+
theme: Theme,
|
|
177
|
+
context: RenderContext,
|
|
178
|
+
): Text {
|
|
179
|
+
return new Text(formatAgyResult(result, options, theme, context), 0, 0);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function isAgyRunReceipt(value: unknown): value is AgyRunReceipt {
|
|
183
|
+
if (typeof value !== "object" || value === null) return false;
|
|
184
|
+
const data = value as Partial<AgyRunReceipt>;
|
|
185
|
+
return (
|
|
186
|
+
typeof data.task === "string" &&
|
|
187
|
+
typeof data.text === "string" &&
|
|
188
|
+
typeof data.completed_at === "string" &&
|
|
189
|
+
typeof data.details === "object" &&
|
|
190
|
+
data.details !== null
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function renderAgyRunReceipt(
|
|
195
|
+
value: unknown,
|
|
196
|
+
options: { expanded: boolean },
|
|
197
|
+
theme: Theme,
|
|
198
|
+
): Text {
|
|
199
|
+
if (!isAgyRunReceipt(value)) {
|
|
200
|
+
return new Text(theme.fg("error", "Invalid agy run receipt"), 0, 0);
|
|
201
|
+
}
|
|
202
|
+
const task = options.expanded
|
|
203
|
+
? stripTerminalSequences(value.task)
|
|
204
|
+
: oneLine(value.task, 180);
|
|
205
|
+
const result = formatAgyResult(
|
|
206
|
+
{ content: [{ type: "text", text: value.text }], details: value.details },
|
|
207
|
+
{ expanded: options.expanded },
|
|
208
|
+
theme,
|
|
209
|
+
{},
|
|
210
|
+
);
|
|
211
|
+
const taskLine = task ? `${theme.fg("dim", "task: ")}${theme.fg("muted", task)}\n` : "";
|
|
212
|
+
return new Text(taskLine + result, 0, 0);
|
|
213
|
+
}
|