@pymodel/antigravity-mcp 0.0.0-stage → 0.1.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.
- package/AGENTS.md +54 -0
- package/CLAUDE.md +7 -0
- package/LICENSE +21 -0
- package/README.md +501 -2
- package/assets/banner.svg +70 -0
- package/assets/benchmarks.svg +80 -0
- package/dist/index.js +3913 -0
- package/docs/multi-client-support.md +323 -0
- package/package.json +75 -4
- package/scripts/install-skills.mjs +281 -0
- package/skills/antigravity-mcp/SKILL.md +226 -0
- package/skills/antigravity-mcp/references/dispatch-and-poll.md +229 -0
- package/skills/antigravity-mcp/references/multi-task-queues.md +77 -0
- package/skills/antigravity-mcp/references/review-and-land.md +154 -0
- package/skills/antigravity-mcp/references/writing-the-brief.md +126 -0
- package/skills/antigravity-mcp/scripts/model-selection.mjs +93 -0
- package/skills/antigravity-mcp/scripts/relay.mjs +898 -0
- package/skills/antigravity-mcp/scripts/workspace.mjs +161 -0
- package/skills/antigravity-mcp-routing/SKILL.md +94 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,3913 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
|
+
|
|
6
|
+
// src/server.ts
|
|
7
|
+
import { randomBytes } from "node:crypto";
|
|
8
|
+
import { readFileSync as readFileSync3 } from "node:fs";
|
|
9
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
10
|
+
|
|
11
|
+
// src/capabilities.ts
|
|
12
|
+
import { execFile } from "node:child_process";
|
|
13
|
+
import { promisify } from "node:util";
|
|
14
|
+
var execFileAsync = promisify(execFile);
|
|
15
|
+
var WANTED_FLAGS = [
|
|
16
|
+
"--output-format",
|
|
17
|
+
"--input-format",
|
|
18
|
+
"--json-schema",
|
|
19
|
+
"--mode",
|
|
20
|
+
"--effort",
|
|
21
|
+
"--disable-slash-commands",
|
|
22
|
+
"--add-dir",
|
|
23
|
+
"--conversation",
|
|
24
|
+
"--print-timeout",
|
|
25
|
+
"--log-file",
|
|
26
|
+
"--sandbox",
|
|
27
|
+
"--dangerously-skip-permissions"
|
|
28
|
+
];
|
|
29
|
+
function parseFlags(help) {
|
|
30
|
+
const flags = /* @__PURE__ */ new Set();
|
|
31
|
+
for (const m of help.matchAll(/(^|\s)(--[a-z0-9-]+)/gi)) flags.add(m[2]);
|
|
32
|
+
return flags;
|
|
33
|
+
}
|
|
34
|
+
function parseVersion(out) {
|
|
35
|
+
return out.trim().split("\n")[0]?.trim() ?? "unknown";
|
|
36
|
+
}
|
|
37
|
+
var realExec = (agyPath) => async (args) => {
|
|
38
|
+
const promise = execFileAsync(agyPath, args, { timeout: 15e3, maxBuffer: 1024 * 1024 });
|
|
39
|
+
promise.child.stdin?.end();
|
|
40
|
+
return promise.then(
|
|
41
|
+
({ stdout, stderr }) => stdout || stderr,
|
|
42
|
+
(err) => {
|
|
43
|
+
if (err.code === "ENOENT") throw err;
|
|
44
|
+
return err.stdout || err.stderr || "";
|
|
45
|
+
}
|
|
46
|
+
);
|
|
47
|
+
};
|
|
48
|
+
function degradedCapabilities(reason, notInstalled = false) {
|
|
49
|
+
const flags = /* @__PURE__ */ new Set(["--print-timeout", "--log-file", "--add-dir", "--conversation"]);
|
|
50
|
+
return {
|
|
51
|
+
version: `unknown (${reason})`,
|
|
52
|
+
flags,
|
|
53
|
+
has: (f) => flags.has(f),
|
|
54
|
+
missing: WANTED_FLAGS.filter((f) => !flags.has(f)),
|
|
55
|
+
...notInstalled ? { notInstalled } : {}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
async function probeCapabilities(agyPath, exec2 = realExec(agyPath)) {
|
|
59
|
+
try {
|
|
60
|
+
const [version, help] = await Promise.all([exec2(["--version"]), exec2(["--help"])]);
|
|
61
|
+
const flags = parseFlags(help);
|
|
62
|
+
if (flags.size === 0) return degradedCapabilities("agy --help produced no flags");
|
|
63
|
+
return {
|
|
64
|
+
version: parseVersion(version),
|
|
65
|
+
flags,
|
|
66
|
+
has: (f) => flags.has(f),
|
|
67
|
+
missing: WANTED_FLAGS.filter((f) => !flags.has(f))
|
|
68
|
+
};
|
|
69
|
+
} catch (err) {
|
|
70
|
+
return degradedCapabilities(
|
|
71
|
+
err.message,
|
|
72
|
+
err.code === "ENOENT"
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// src/confine.ts
|
|
78
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
79
|
+
import { existsSync, mkdtempSync, realpathSync, rmSync } from "node:fs";
|
|
80
|
+
import { homedir, tmpdir } from "node:os";
|
|
81
|
+
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
82
|
+
var SANDBOX_EXEC = "/usr/bin/sandbox-exec";
|
|
83
|
+
var AGY_STATE_DIR = join(homedir(), ".gemini");
|
|
84
|
+
function sandboxProfile(shape2) {
|
|
85
|
+
const rules = [
|
|
86
|
+
...Array.from(
|
|
87
|
+
{ length: shape2.roots },
|
|
88
|
+
(_, i) => `(deny file-write* (subpath (param "ROOT_${i}")))`
|
|
89
|
+
),
|
|
90
|
+
...Array.from(
|
|
91
|
+
{ length: shape2.ancestors },
|
|
92
|
+
(_, i) => `(deny file-write-unlink (literal (param "ANCESTOR_${i}")))`
|
|
93
|
+
),
|
|
94
|
+
...Array.from(
|
|
95
|
+
{ length: shape2.carveOuts },
|
|
96
|
+
(_, i) => `(allow file-write* (subpath (param "CARVE_${i}")))`
|
|
97
|
+
)
|
|
98
|
+
];
|
|
99
|
+
return ["(version 1)", "(allow default)", ...rules].join("\n");
|
|
100
|
+
}
|
|
101
|
+
function resolvedSpelling(abs) {
|
|
102
|
+
let head = abs;
|
|
103
|
+
const tail = [];
|
|
104
|
+
while (!existsSync(head)) {
|
|
105
|
+
const up = dirname(head);
|
|
106
|
+
if (up === head) return abs;
|
|
107
|
+
tail.unshift(basename(head));
|
|
108
|
+
head = up;
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
return join(realpathSync(head), ...tail);
|
|
112
|
+
} catch {
|
|
113
|
+
return abs;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function confinedRoots(roots) {
|
|
117
|
+
const out = /* @__PURE__ */ new Set();
|
|
118
|
+
for (const root of roots) {
|
|
119
|
+
const abs = resolve(root);
|
|
120
|
+
out.add(abs);
|
|
121
|
+
out.add(resolvedSpelling(abs));
|
|
122
|
+
}
|
|
123
|
+
return [...out];
|
|
124
|
+
}
|
|
125
|
+
function rootAncestors(roots) {
|
|
126
|
+
const out = /* @__PURE__ */ new Set();
|
|
127
|
+
for (const root of roots) {
|
|
128
|
+
for (let dir = dirname(root); dir !== dirname(dir); dir = dirname(dir)) out.add(dir);
|
|
129
|
+
}
|
|
130
|
+
return [...out];
|
|
131
|
+
}
|
|
132
|
+
var strictlyInside = (child, parent) => {
|
|
133
|
+
const rel = relative(parent, child);
|
|
134
|
+
return rel !== "" && !rel.startsWith("..") && !rel.startsWith("/");
|
|
135
|
+
};
|
|
136
|
+
function rootInsideState(roots, stateDirs = [AGY_STATE_DIR]) {
|
|
137
|
+
const state = confinedRoots(stateDirs);
|
|
138
|
+
return confinedRoots(roots).some(
|
|
139
|
+
(root) => state.some((dir) => root === dir || strictlyInside(root, dir))
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
function carveOuts(roots, stateDirs) {
|
|
143
|
+
const out = /* @__PURE__ */ new Set();
|
|
144
|
+
for (const dir of confinedRoots(stateDirs)) {
|
|
145
|
+
if (roots.some((root) => strictlyInside(dir, root))) out.add(dir);
|
|
146
|
+
}
|
|
147
|
+
return [...out];
|
|
148
|
+
}
|
|
149
|
+
function sandboxConfinement(stateDirs = [AGY_STATE_DIR]) {
|
|
150
|
+
return {
|
|
151
|
+
available: true,
|
|
152
|
+
wrap(file, args, roots) {
|
|
153
|
+
const resolved = confinedRoots(roots);
|
|
154
|
+
if (!resolved.length) throw new Error("confinement needs at least one root");
|
|
155
|
+
const ancestors = rootAncestors(resolved);
|
|
156
|
+
const carved = carveOuts(resolved, stateDirs);
|
|
157
|
+
const defines = [
|
|
158
|
+
...resolved.flatMap((p, i) => ["-D", `ROOT_${i}=${p}`]),
|
|
159
|
+
...ancestors.flatMap((p, i) => ["-D", `ANCESTOR_${i}=${p}`]),
|
|
160
|
+
...carved.flatMap((p, i) => ["-D", `CARVE_${i}=${p}`])
|
|
161
|
+
];
|
|
162
|
+
const profile = sandboxProfile({
|
|
163
|
+
roots: resolved.length,
|
|
164
|
+
ancestors: ancestors.length,
|
|
165
|
+
carveOuts: carved.length
|
|
166
|
+
});
|
|
167
|
+
return { file: SANDBOX_EXEC, args: [...defines, "-p", profile, file, ...args] };
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function unavailableConfinement(reason) {
|
|
172
|
+
return {
|
|
173
|
+
available: false,
|
|
174
|
+
reason,
|
|
175
|
+
wrap() {
|
|
176
|
+
throw new Error(`read-only confinement is unavailable: ${reason}`);
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
var realRun = (file, args) => new Promise((ok, fail) => {
|
|
181
|
+
execFile2(file, args, { timeout: 1e4 }, (err) => err ? fail(err) : ok());
|
|
182
|
+
});
|
|
183
|
+
async function probeConfinement(platform = process.platform, run = realRun) {
|
|
184
|
+
if (platform !== "darwin") {
|
|
185
|
+
return unavailableConfinement(`no write confinement is implemented for ${platform}`);
|
|
186
|
+
}
|
|
187
|
+
const confinement = sandboxConfinement();
|
|
188
|
+
const root = mkdtempSync(join(tmpdir(), "agy-confine-probe-"));
|
|
189
|
+
const target = join(root, "probe");
|
|
190
|
+
try {
|
|
191
|
+
const ok = confinement.wrap("/usr/bin/true", [], [root]);
|
|
192
|
+
await run(ok.file, ok.args);
|
|
193
|
+
const write = confinement.wrap("/usr/bin/touch", [target], [root]);
|
|
194
|
+
const refused = await run(write.file, write.args).then(
|
|
195
|
+
() => false,
|
|
196
|
+
(err) => err.code === 1 && !err.killed && !err.signal
|
|
197
|
+
);
|
|
198
|
+
if (!refused || existsSync(target)) {
|
|
199
|
+
return unavailableConfinement(`${SANDBOX_EXEC} did not block a write in its probe`);
|
|
200
|
+
}
|
|
201
|
+
return confinement;
|
|
202
|
+
} catch (err) {
|
|
203
|
+
return unavailableConfinement(`${SANDBOX_EXEC} failed its probe: ${err.message}`);
|
|
204
|
+
} finally {
|
|
205
|
+
rmSync(root, { recursive: true, force: true });
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// src/config.ts
|
|
210
|
+
import path2 from "node:path";
|
|
211
|
+
|
|
212
|
+
// src/tools.ts
|
|
213
|
+
import path from "node:path";
|
|
214
|
+
import { z } from "zod";
|
|
215
|
+
|
|
216
|
+
// src/models.ts
|
|
217
|
+
import { execFile as execFile3 } from "node:child_process";
|
|
218
|
+
import { promisify as promisify2 } from "node:util";
|
|
219
|
+
var execFileAsync2 = promisify2(execFile3);
|
|
220
|
+
var EFFORTS = ["low", "medium", "high", "xhigh", "max"];
|
|
221
|
+
function isEffort(value) {
|
|
222
|
+
return typeof value === "string" && EFFORTS.includes(value);
|
|
223
|
+
}
|
|
224
|
+
function listModels(agyPath) {
|
|
225
|
+
const promise = execFileAsync2(agyPath, ["models"], {
|
|
226
|
+
cwd: process.cwd(),
|
|
227
|
+
timeout: 3e4,
|
|
228
|
+
maxBuffer: 1024 * 1024
|
|
229
|
+
});
|
|
230
|
+
promise.child.stdin?.end();
|
|
231
|
+
return promise.then(({ stdout }) => stdout);
|
|
232
|
+
}
|
|
233
|
+
var VERSION_TOKEN = /^\d+(?:\.\d+)*$/;
|
|
234
|
+
function describeModel(id, name) {
|
|
235
|
+
const paren = /\(([^)]*)\)\s*$/.exec(name);
|
|
236
|
+
const suffix = paren?.[1]?.trim().toLowerCase();
|
|
237
|
+
const effort2 = isEffort(suffix) || suffix === "thinking" ? suffix : void 0;
|
|
238
|
+
const head = effort2 && paren ? name.slice(0, paren.index) : name;
|
|
239
|
+
const version = [];
|
|
240
|
+
const familyWords = [];
|
|
241
|
+
for (const word of head.trim().split(/\s+/)) {
|
|
242
|
+
if (!word) continue;
|
|
243
|
+
if (VERSION_TOKEN.test(word) && version.length === 0) {
|
|
244
|
+
version.push(...word.split(".").map(Number));
|
|
245
|
+
} else {
|
|
246
|
+
familyWords.push(word.toLowerCase());
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return {
|
|
250
|
+
id,
|
|
251
|
+
name,
|
|
252
|
+
family: familyWords.join("-"),
|
|
253
|
+
version,
|
|
254
|
+
...effort2 ? { effort: effort2 } : {}
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
function parseListing(output) {
|
|
258
|
+
const rows = [];
|
|
259
|
+
const seen = /* @__PURE__ */ new Set();
|
|
260
|
+
for (const line of output.split("\n")) {
|
|
261
|
+
const parts = line.split(" ").map((s) => s.trim().replace(/\s*\(current\)$/, ""));
|
|
262
|
+
if (parts.length < 2) continue;
|
|
263
|
+
const [id, name] = parts;
|
|
264
|
+
if (!id || !name || seen.has(id)) continue;
|
|
265
|
+
seen.add(id);
|
|
266
|
+
rows.push(describeModel(id, name));
|
|
267
|
+
}
|
|
268
|
+
return rows;
|
|
269
|
+
}
|
|
270
|
+
var SELECTOR = /^([a-z0-9-]+)@(latest|\d+(?:\.\d+)*)(?:-(high|medium|low|xhigh|max|thinking))?$/i;
|
|
271
|
+
function newerThan(a, b) {
|
|
272
|
+
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
|
273
|
+
const x = a[i] ?? 0;
|
|
274
|
+
const y = b[i] ?? 0;
|
|
275
|
+
if (x !== y) return x > y;
|
|
276
|
+
}
|
|
277
|
+
return false;
|
|
278
|
+
}
|
|
279
|
+
function resolveEntry(entry, available) {
|
|
280
|
+
const exactId = available.find((m) => m.id === entry);
|
|
281
|
+
if (exactId) return exactId.id;
|
|
282
|
+
const exactNames = available.filter((m) => m.name === entry);
|
|
283
|
+
if (exactNames.length === 1) return exactNames[0].id;
|
|
284
|
+
if (exactNames.length > 1) return void 0;
|
|
285
|
+
const sel = SELECTOR.exec(entry);
|
|
286
|
+
if (!sel) return void 0;
|
|
287
|
+
const [, family, versionSpec, effort2] = sel;
|
|
288
|
+
const wantVersion = versionSpec.toLowerCase() === "latest" ? null : versionSpec.split(".").map(Number);
|
|
289
|
+
let best;
|
|
290
|
+
for (const m of available) {
|
|
291
|
+
if (m.family !== family.toLowerCase()) continue;
|
|
292
|
+
if (effort2 && m.effort !== effort2.toLowerCase()) continue;
|
|
293
|
+
if (wantVersion && m.version.join(".") !== wantVersion.join(".")) continue;
|
|
294
|
+
if (!best || newerThan(m.version, best.version) || !newerThan(best.version, m.version) && stableVariantOrder(m, best) < 0)
|
|
295
|
+
best = m;
|
|
296
|
+
}
|
|
297
|
+
return best?.id;
|
|
298
|
+
}
|
|
299
|
+
function stableVariantOrder(a, b) {
|
|
300
|
+
const order = ["medium", "high", "low", "xhigh", "max", "thinking", void 0];
|
|
301
|
+
return order.indexOf(a.effort) - order.indexOf(b.effort) || a.id.localeCompare(b.id);
|
|
302
|
+
}
|
|
303
|
+
function pickTier(name, effort2, available) {
|
|
304
|
+
const exactId = available.find((m) => m.id === name);
|
|
305
|
+
const labels = exactId ? [] : available.filter((m) => m.name === name);
|
|
306
|
+
const info = exactId ?? (labels.length === 1 ? labels[0] : void 0);
|
|
307
|
+
if (!info) throw new Error(`Model "${name}" is not in the current agy inventory.`);
|
|
308
|
+
if (!effort2 || effort2 === info.effort) return { model: info.id };
|
|
309
|
+
const sibling = available.filter(
|
|
310
|
+
(m) => m.family === info.family && m.version.join(".") === info.version.join(".") && m.effort === effort2
|
|
311
|
+
).sort(stableVariantOrder)[0];
|
|
312
|
+
if (sibling) return { model: sibling.id };
|
|
313
|
+
const offered = available.filter((m) => m.family === info.family && m.version.join(".") === info.version.join(".")).map((m) => m.effort).filter((v) => v !== void 0);
|
|
314
|
+
throw new Error(
|
|
315
|
+
`Model "${info.name}" does not offer effort "${effort2}". Available efforts: ${[...new Set(offered)].join(", ") || "fixed; omit effort"}.`
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
var ModelSkewError = class extends Error {
|
|
319
|
+
constructor(chain, available) {
|
|
320
|
+
super(
|
|
321
|
+
`None of this tool's models are offered by agy any more.
|
|
322
|
+
Wanted: ${chain.join(", ")}
|
|
323
|
+
Available: ${available.map((m) => m.name).join(", ")}
|
|
324
|
+
This is a version-skew signal, not a preference \u2014 update the tool's chain.`
|
|
325
|
+
);
|
|
326
|
+
this.name = "ModelSkewError";
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
var ModelRegistry = class {
|
|
330
|
+
constructor(fetchListing, cache = {}) {
|
|
331
|
+
this.fetchListing = fetchListing;
|
|
332
|
+
this.cache = cache;
|
|
333
|
+
}
|
|
334
|
+
fetchListing;
|
|
335
|
+
cache;
|
|
336
|
+
listing = null;
|
|
337
|
+
pending = null;
|
|
338
|
+
generation = 0;
|
|
339
|
+
freshUntil = 0;
|
|
340
|
+
/**
|
|
341
|
+
* Discards the cached listing so the next call re-reads `agy models`.
|
|
342
|
+
*
|
|
343
|
+
* Listings otherwise expire after five minutes. Invalidation also prevents
|
|
344
|
+
* an older in-flight fetch from replacing a newer account inventory.
|
|
345
|
+
*/
|
|
346
|
+
invalidate() {
|
|
347
|
+
this.listing = null;
|
|
348
|
+
this.pending = null;
|
|
349
|
+
this.freshUntil = 0;
|
|
350
|
+
this.generation++;
|
|
351
|
+
}
|
|
352
|
+
async available() {
|
|
353
|
+
const now = this.cache.now ?? Date.now;
|
|
354
|
+
if (this.listing && now() < this.freshUntil) return this.listing;
|
|
355
|
+
this.pending ??= this.fetchListing().then(parseListing).catch(() => null);
|
|
356
|
+
const pending = this.pending;
|
|
357
|
+
const generation = this.generation;
|
|
358
|
+
const result = await pending;
|
|
359
|
+
if (generation !== this.generation) return this.available();
|
|
360
|
+
if (this.pending === pending) this.pending = null;
|
|
361
|
+
if (result && result.length) {
|
|
362
|
+
this.listing = result;
|
|
363
|
+
this.freshUntil = now() + (this.cache.ttlMs ?? 3e5);
|
|
364
|
+
} else {
|
|
365
|
+
this.listing = null;
|
|
366
|
+
}
|
|
367
|
+
return result && result.length ? result : null;
|
|
368
|
+
}
|
|
369
|
+
/** Verify effort against the inventory; never invent a tier during an outage. */
|
|
370
|
+
async forEffort(name, effort2) {
|
|
371
|
+
if (!name) return void 0;
|
|
372
|
+
const available = await this.available();
|
|
373
|
+
if (available === null) {
|
|
374
|
+
if (effort2)
|
|
375
|
+
throw new Error("Cannot verify the requested effort because `agy models` is unavailable.");
|
|
376
|
+
return { model: name };
|
|
377
|
+
}
|
|
378
|
+
return pickTier(name, effort2, available);
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Every viable model in preference order for selection before dispatch.
|
|
382
|
+
* `[undefined]` means "let agy pick", and is only returned when the listing
|
|
383
|
+
* itself could not be read — an unreadable listing is a degraded environment,
|
|
384
|
+
* whereas an empty resolved chain is stale configuration and throws.
|
|
385
|
+
*/
|
|
386
|
+
async resolveChain(opts) {
|
|
387
|
+
const available = await this.available();
|
|
388
|
+
if (opts.explicit) {
|
|
389
|
+
if (available === null) {
|
|
390
|
+
return {
|
|
391
|
+
models: [opts.explicit],
|
|
392
|
+
note: "could not list agy models; passing model through unvalidated"
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
const resolved = resolveEntry(opts.explicit, available);
|
|
396
|
+
if (resolved) return { models: [resolved] };
|
|
397
|
+
throw new Error(
|
|
398
|
+
`Model "${opts.explicit}" is not available. Available models:
|
|
399
|
+
` + available.map((m) => m.name).join("\n")
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
if (available === null) {
|
|
403
|
+
return {
|
|
404
|
+
models: [void 0],
|
|
405
|
+
note: "could not list agy models; using agy's own default model"
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
const wanted = [...opts.chain, ...opts.defaultModel ? [opts.defaultModel] : []];
|
|
409
|
+
const models = [];
|
|
410
|
+
for (const entry of wanted) {
|
|
411
|
+
const name = resolveEntry(entry, available);
|
|
412
|
+
if (name && !models.includes(name)) models.push(name);
|
|
413
|
+
}
|
|
414
|
+
if (models.length === 0) throw new ModelSkewError(wanted, available);
|
|
415
|
+
return { models };
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
// src/tools.ts
|
|
420
|
+
var OUTPUT_RULES = "Answer directly with no preamble or closing remarks. Be thorough but concise. Cite file:line for every code-level finding.";
|
|
421
|
+
function resolveFiles(files, cwd) {
|
|
422
|
+
return files.map((f) => path.isAbsolute(f) ? f : path.resolve(cwd, f));
|
|
423
|
+
}
|
|
424
|
+
var MAX_FANOUT = 8;
|
|
425
|
+
var text = () => z.string().regex(/\S/, "must not be empty or whitespace");
|
|
426
|
+
var flagValue = () => z.string().trim().min(1).max(512).regex(/^[^-]/, "must not start with '-'");
|
|
427
|
+
var paths = () => z.array(z.string().min(1)).max(256);
|
|
428
|
+
var commonShape = {
|
|
429
|
+
cwd: z.string().min(1).optional().describe(
|
|
430
|
+
"Absolute path to the working directory / project root. Defaults to the server's cwd."
|
|
431
|
+
),
|
|
432
|
+
dirs: paths().optional().describe(
|
|
433
|
+
"Extra directories to add to agy's workspace, for cross-repo or worktree-vs-base analysis."
|
|
434
|
+
),
|
|
435
|
+
model: flagValue().optional().describe(
|
|
436
|
+
'Override the model. Accepts a display name ("Gemini 4 Neon (High)"), an id ("gemini-4-neon-high"), or a family selector ("gemini-neon@latest-high"). Normally omit \u2014 the tool routes automatically.'
|
|
437
|
+
),
|
|
438
|
+
effort: z.enum(EFFORTS).optional().describe(
|
|
439
|
+
"Reasoning tier supported by the selected model in `agy models`. A family selector can choose its listed sibling at this tier. An exact model ID or label fixes the variant: a conflicting effort is rejected. xhigh/max require a listed variant."
|
|
440
|
+
),
|
|
441
|
+
slash_commands: z.boolean().optional().describe(
|
|
442
|
+
"Let agy expand your slash commands and skills into the prompt. Off by default: a hostile file in the workspace can otherwise steer the delegated model."
|
|
443
|
+
)
|
|
444
|
+
};
|
|
445
|
+
var structuredShape = {
|
|
446
|
+
schema: z.string().optional().describe(
|
|
447
|
+
"JSON Schema (as a string) constraining the answer. Returns structuredContent as well as text. Costs noticeably more latency and tokens, so use it only when you will parse the result."
|
|
448
|
+
)
|
|
449
|
+
};
|
|
450
|
+
var ROUTING_ARGS = z.object({
|
|
451
|
+
...commonShape,
|
|
452
|
+
...structuredShape,
|
|
453
|
+
session_id: flagValue().optional(),
|
|
454
|
+
write: z.boolean().optional(),
|
|
455
|
+
sandbox: z.boolean().optional()
|
|
456
|
+
});
|
|
457
|
+
function modeFor(tool, write) {
|
|
458
|
+
if (tool.privilege === "read-only") return "plan";
|
|
459
|
+
return write ? "accept-edits" : "plan";
|
|
460
|
+
}
|
|
461
|
+
function defineTool(def) {
|
|
462
|
+
const { prompt, paths: paths2, kind, ...rest } = def;
|
|
463
|
+
const pathsOf = (args, cwd) => paths2?.(def.schema.parse(args), cwd) ?? [];
|
|
464
|
+
return {
|
|
465
|
+
...rest,
|
|
466
|
+
kind: kind ?? "delegate",
|
|
467
|
+
buildPrompt: (args, cwd) => prompt(def.schema.parse(args), cwd),
|
|
468
|
+
extraDirs: (args, cwd) => [...new Set(pathsOf(args, cwd).map((p) => path.dirname(p)))],
|
|
469
|
+
touchedPaths: pathsOf
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
var TOOLS = [
|
|
473
|
+
defineTool({
|
|
474
|
+
name: "analyze_files",
|
|
475
|
+
description: "Delegate file analysis to the Antigravity CLI (Gemini) instead of reading files yourself. USE THIS whenever a file is large (>200 lines) or the task spans more than 3 files: logs, database dumps, generated code, cross-file reviews, comparisons. The files never enter your context \u2014 only the answer does.",
|
|
476
|
+
schema: z.object({
|
|
477
|
+
files: paths().min(1).describe("File paths to analyze (relative to cwd or absolute)."),
|
|
478
|
+
question: text().describe("What you want to know about these files."),
|
|
479
|
+
...commonShape,
|
|
480
|
+
...structuredShape
|
|
481
|
+
}),
|
|
482
|
+
chain: ["gemini-flash@latest-high", "gemini-pro@latest-low"],
|
|
483
|
+
privilege: "read-only",
|
|
484
|
+
paths: (args, cwd) => resolveFiles(args.files, cwd),
|
|
485
|
+
prompt(args, cwd) {
|
|
486
|
+
const files = resolveFiles(args.files, cwd);
|
|
487
|
+
return `Read and analyze these files:
|
|
488
|
+
${files.map((f) => `- ${f}`).join("\n")}
|
|
489
|
+
|
|
490
|
+
Question: ${args.question}
|
|
491
|
+
|
|
492
|
+
${OUTPUT_RULES}`;
|
|
493
|
+
}
|
|
494
|
+
}),
|
|
495
|
+
defineTool({
|
|
496
|
+
name: "deep_search",
|
|
497
|
+
description: "Delegate codebase archaeology to the Antigravity CLI: git log/diff/blame spelunking, wide greps across a repo, 'when/why did X change', 'where is Y used'. USE THIS instead of running many search commands yourself \u2014 it saves your context.",
|
|
498
|
+
schema: z.object({
|
|
499
|
+
query: text().describe(
|
|
500
|
+
"What to find, e.g. 'when was the auth middleware refactored and why'."
|
|
501
|
+
),
|
|
502
|
+
...commonShape,
|
|
503
|
+
...structuredShape
|
|
504
|
+
}),
|
|
505
|
+
chain: ["gemini-flash@latest-high", "gemini-flash@latest-medium"],
|
|
506
|
+
privilege: "read-only",
|
|
507
|
+
prompt(args) {
|
|
508
|
+
return `Search this repository to answer the following. Use git log, git diff, git blame, and grep as needed.
|
|
509
|
+
|
|
510
|
+
Query: ${args.query}
|
|
511
|
+
|
|
512
|
+
Report findings with commit hashes where relevant. ${OUTPUT_RULES}`;
|
|
513
|
+
}
|
|
514
|
+
}),
|
|
515
|
+
defineTool({
|
|
516
|
+
name: "web_lookup",
|
|
517
|
+
description: "Delegate a web/documentation lookup to the Antigravity CLI (Gemini with web access): library docs, API references, error messages, current versions, external knowledge. USE THIS when you need information you don't have or that may be newer than your training data.",
|
|
518
|
+
schema: z.object({
|
|
519
|
+
query: text().describe("What to look up on the web."),
|
|
520
|
+
...commonShape,
|
|
521
|
+
...structuredShape
|
|
522
|
+
}),
|
|
523
|
+
chain: ["gemini-flash@latest-high", "gemini-flash@latest-medium"],
|
|
524
|
+
privilege: "read-only",
|
|
525
|
+
prompt(args) {
|
|
526
|
+
return `Look up on the web: ${args.query}
|
|
527
|
+
|
|
528
|
+
Include source URLs for key claims. ${OUTPUT_RULES}`;
|
|
529
|
+
}
|
|
530
|
+
}),
|
|
531
|
+
defineTool({
|
|
532
|
+
name: "adversarial_review",
|
|
533
|
+
description: "Get an adversarial review using the selected model or the tool's available route. Use this for plan critiques, design reviews, and pre-merge code review: it hunts for flaws, edge cases, security issues, and unstated assumptions. Pin a different model explicitly when independent model-family review is needed. Pass either `content` or `files` \u2014 a call with neither is rejected. Pass `schema` to get ranked findings back as data instead of prose.",
|
|
534
|
+
schema: z.object({
|
|
535
|
+
content: z.string().optional().describe("Inline content to review (plan, diff, code snippet)."),
|
|
536
|
+
files: paths().optional().describe("File paths to review instead of inline content."),
|
|
537
|
+
focus: z.string().optional().describe("Optional focus area, e.g. 'security', 'concurrency'."),
|
|
538
|
+
...commonShape,
|
|
539
|
+
...structuredShape
|
|
540
|
+
}).refine((a) => Boolean(a.content?.trim()) || Boolean(a.files?.length), {
|
|
541
|
+
message: "adversarial_review requires either `content` or `files`."
|
|
542
|
+
}),
|
|
543
|
+
chain: ["gemini-flash@latest-high", "gemini-pro@latest-high", "claude-opus@latest"],
|
|
544
|
+
privilege: "read-only",
|
|
545
|
+
paths: (args, cwd) => resolveFiles(args.files ?? [], cwd),
|
|
546
|
+
prompt(args, cwd) {
|
|
547
|
+
const subject = args.content ? `Review the following:
|
|
548
|
+
|
|
549
|
+
${args.content}` : `Read and review these files:
|
|
550
|
+
${resolveFiles(args.files ?? [], cwd).map((f) => `- ${f}`).join("\n")}`;
|
|
551
|
+
const focus = args.focus ? `
|
|
552
|
+
Focus especially on: ${args.focus}.` : "";
|
|
553
|
+
return `You are an adversarial reviewer. Find real flaws: bugs, edge cases, security issues, performance traps, unstated assumptions, and simpler alternatives.${focus}
|
|
554
|
+
|
|
555
|
+
${subject}
|
|
556
|
+
|
|
557
|
+
Rank findings by severity (critical/major/minor) and justify each. Do not pad with praise or restate the input. ${OUTPUT_RULES}`;
|
|
558
|
+
}
|
|
559
|
+
}),
|
|
560
|
+
defineTool({
|
|
561
|
+
name: "follow_up",
|
|
562
|
+
description: "Continue a previous Antigravity session by session_id (returned by every other tool). USE THIS for follow-up questions about a prior delegation \u2014 the full prior context is already on agy's side, so you don't resend anything. Pass `model` to get a second opinion on the same history from a different model without re-sending it. Read-only by default; pass `write: true` to rework a delegation that edited files.",
|
|
563
|
+
schema: z.object({
|
|
564
|
+
session_id: flagValue().describe(
|
|
565
|
+
"The session id returned by a previous Antigravity MCP call."
|
|
566
|
+
),
|
|
567
|
+
question: text().describe("The follow-up question."),
|
|
568
|
+
write: z.boolean().optional().describe("Allow file edits and command execution. Off by default."),
|
|
569
|
+
...commonShape,
|
|
570
|
+
...structuredShape
|
|
571
|
+
}),
|
|
572
|
+
// The rework path for a write delegation runs through here, so it has to be
|
|
573
|
+
// able to write. It was pinned read-only, and only appeared to work because
|
|
574
|
+
// plan mode is advisory under the default permission grant.
|
|
575
|
+
privilege: "caller-chooses",
|
|
576
|
+
prompt(args) {
|
|
577
|
+
return args.question;
|
|
578
|
+
}
|
|
579
|
+
}),
|
|
580
|
+
defineTool({
|
|
581
|
+
name: "delegate",
|
|
582
|
+
description: "Raw delegation to the Antigravity CLI for heavy tasks that don't fit the other tools. Read-only by default; pass `write: true` to let agy edit files, `sandbox: true` to confine it. Anything it was refused comes back as a denied-actions note.",
|
|
583
|
+
schema: z.object({
|
|
584
|
+
prompt: text().describe("The complete task prompt for agy."),
|
|
585
|
+
write: z.boolean().optional().describe("Allow file edits and command execution. Off by default."),
|
|
586
|
+
sandbox: z.boolean().optional().describe("Run agy with terminal restrictions enabled."),
|
|
587
|
+
...commonShape,
|
|
588
|
+
...structuredShape
|
|
589
|
+
}),
|
|
590
|
+
chain: ["gemini-flash@latest-high", "gemini-pro@latest-low"],
|
|
591
|
+
privilege: "caller-chooses",
|
|
592
|
+
prompt(args) {
|
|
593
|
+
return args.prompt;
|
|
594
|
+
}
|
|
595
|
+
}),
|
|
596
|
+
defineTool({
|
|
597
|
+
name: "delegate_many",
|
|
598
|
+
description: "Fan one question out to several models at once (a council, with a disagreement report), or fan several sub-tasks out to one model. Runs behind the same concurrency cap as everything else, so it queues rather than stampedes the shared quota.",
|
|
599
|
+
schema: z.object({
|
|
600
|
+
prompt: text().optional().describe("One prompt to send to every model in `models`."),
|
|
601
|
+
tasks: z.array(text()).min(1).max(MAX_FANOUT).optional().describe(`Several prompts to run, each as its own delegation (at most ${MAX_FANOUT}).`),
|
|
602
|
+
models: z.array(flagValue()).min(1).max(MAX_FANOUT).refine((m) => new Set(m).size === m.length, "must not list a model twice").optional().describe(
|
|
603
|
+
`Models to ask with \`prompt\` (at most ${MAX_FANOUT}). Defaults to a Flash/Pro/Opus council.`
|
|
604
|
+
),
|
|
605
|
+
...commonShape
|
|
606
|
+
}).refine((a) => Boolean(a.prompt) !== Boolean(a.tasks), {
|
|
607
|
+
message: "delegate_many requires exactly one of `prompt` or `tasks`."
|
|
608
|
+
}).refine((a) => !(a.tasks && a.models), {
|
|
609
|
+
message: "delegate_many runs `tasks` on the automatic route; pass `models` only with `prompt`."
|
|
610
|
+
}).refine((a) => !(a.model && a.models), {
|
|
611
|
+
message: "delegate_many accepts either singular `model` or `models`, not both."
|
|
612
|
+
}),
|
|
613
|
+
chain: ["gemini-flash@latest-high", "gemini-pro@latest-high", "claude-opus@latest"],
|
|
614
|
+
privilege: "read-only",
|
|
615
|
+
kind: "fanout",
|
|
616
|
+
prompt(args) {
|
|
617
|
+
return args.prompt ?? (args.tasks ?? []).join("\n\n");
|
|
618
|
+
}
|
|
619
|
+
}),
|
|
620
|
+
defineTool({
|
|
621
|
+
name: "set_model",
|
|
622
|
+
description: 'Choose the model and reasoning tier every tool uses from now on, on this machine. Ask the user first \u2014 "proceed with the default, or change model or effort?" \u2014 then call this once: with no arguments to accept the default, or with what they chose. The choice is saved and no tool asks again. An explicit `model` argument on a call still wins for that call. Set AGY_ASK_MODEL=false to skip the gate and route on the built-in chains.',
|
|
623
|
+
schema: z.object({
|
|
624
|
+
model: z.string().min(1).optional().describe(
|
|
625
|
+
'The model the user chose: a display name ("Gemini 4 Neon (High)"), an id ("gemini-4-neon-high"), or a family selector ("gemini-neon@latest-high"). Omit to accept the default (AGY_DEFAULT_MODEL, Gemini Flash High out of the box).'
|
|
626
|
+
),
|
|
627
|
+
effort: z.enum(EFFORTS).optional().describe("The tier the user chose. Omit to take the tier the model name carries.")
|
|
628
|
+
}),
|
|
629
|
+
privilege: "read-only",
|
|
630
|
+
kind: "configure",
|
|
631
|
+
prompt() {
|
|
632
|
+
return "";
|
|
633
|
+
}
|
|
634
|
+
}),
|
|
635
|
+
defineTool({
|
|
636
|
+
name: "agy_status",
|
|
637
|
+
description: "What this bridge has spent and what it can still do: tokens by model, live quota cooldowns, runs in flight, the resolved model chain per tool, the user's set_model choice, the models agy offers, warm sessions, and the agy version and flags detected at startup. Check this before a large fan-out, or to list models before set_model.",
|
|
638
|
+
schema: z.object({}),
|
|
639
|
+
privilege: "read-only",
|
|
640
|
+
kind: "status",
|
|
641
|
+
prompt() {
|
|
642
|
+
return "";
|
|
643
|
+
}
|
|
644
|
+
})
|
|
645
|
+
];
|
|
646
|
+
var TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
|
|
647
|
+
|
|
648
|
+
// src/config.ts
|
|
649
|
+
var ConfigError = class extends Error {
|
|
650
|
+
constructor(variable, value, expected) {
|
|
651
|
+
super(`${variable}="${value}" is not valid. Expected ${expected}.`);
|
|
652
|
+
this.variable = variable;
|
|
653
|
+
this.value = value;
|
|
654
|
+
this.name = "ConfigError";
|
|
655
|
+
}
|
|
656
|
+
variable;
|
|
657
|
+
value;
|
|
658
|
+
};
|
|
659
|
+
function unset(raw) {
|
|
660
|
+
return raw === void 0 || raw === "";
|
|
661
|
+
}
|
|
662
|
+
var MAX_DURATION_SEC = 7 * 24 * 3600;
|
|
663
|
+
var DECIMAL = /^[0-9]+$/;
|
|
664
|
+
function positiveInt(name, raw, fallback, max = Number.MAX_SAFE_INTEGER) {
|
|
665
|
+
if (unset(raw)) return fallback;
|
|
666
|
+
const n = DECIMAL.test(raw) ? Number(raw) : NaN;
|
|
667
|
+
if (!Number.isSafeInteger(n) || n <= 0) {
|
|
668
|
+
throw new ConfigError(name, raw, "a positive integer");
|
|
669
|
+
}
|
|
670
|
+
if (n > max)
|
|
671
|
+
throw new ConfigError(name, raw, `a positive integer no larger than ${max}`);
|
|
672
|
+
return n;
|
|
673
|
+
}
|
|
674
|
+
function durationSec(name, raw, fallback) {
|
|
675
|
+
return positiveInt(name, raw, fallback, MAX_DURATION_SEC);
|
|
676
|
+
}
|
|
677
|
+
function optionalPositiveInt(name, raw) {
|
|
678
|
+
if (unset(raw)) return void 0;
|
|
679
|
+
return positiveInt(name, raw, 0);
|
|
680
|
+
}
|
|
681
|
+
var TRUE = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
|
|
682
|
+
var FALSE = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
|
|
683
|
+
function bool(name, raw, fallback) {
|
|
684
|
+
if (unset(raw)) return fallback;
|
|
685
|
+
const v = raw.trim().toLowerCase();
|
|
686
|
+
if (TRUE.has(v)) return true;
|
|
687
|
+
if (FALSE.has(v)) return false;
|
|
688
|
+
throw new ConfigError(name, raw, "one of true/false/1/0/yes/no/on/off");
|
|
689
|
+
}
|
|
690
|
+
function oneOf(name, raw, allowed) {
|
|
691
|
+
const v = raw.trim().toLowerCase();
|
|
692
|
+
const hit = allowed.find((a) => a === v);
|
|
693
|
+
if (hit === void 0) throw new ConfigError(name, raw, `one of ${allowed.join("/")}`);
|
|
694
|
+
return hit;
|
|
695
|
+
}
|
|
696
|
+
function effort(raw) {
|
|
697
|
+
if (unset(raw)) return void 0;
|
|
698
|
+
return oneOf("AGY_EFFORT", raw, EFFORTS);
|
|
699
|
+
}
|
|
700
|
+
function parseRoots(raw, delimiter = path2.delimiter) {
|
|
701
|
+
if (!raw) return [];
|
|
702
|
+
return raw.split(new RegExp(`[${delimiter},]`)).map((s) => s.trim()).filter((s) => s.length > 0);
|
|
703
|
+
}
|
|
704
|
+
function readOnlyEnforcement(raw) {
|
|
705
|
+
if (unset(raw)) return "auto";
|
|
706
|
+
return oneOf("AGY_READ_ONLY_ENFORCEMENT", raw, ["auto", "require", "off"]);
|
|
707
|
+
}
|
|
708
|
+
function onFailure(raw) {
|
|
709
|
+
if (unset(raw)) return "fallback";
|
|
710
|
+
return oneOf("AGY_ON_FAILURE", raw, ["strict", "fallback"]);
|
|
711
|
+
}
|
|
712
|
+
function loadPerToolTimeouts(env) {
|
|
713
|
+
const out = {};
|
|
714
|
+
for (const [key, raw] of Object.entries(env)) {
|
|
715
|
+
if (!key.startsWith("AGY_TIMEOUT_")) continue;
|
|
716
|
+
const tool = key.slice("AGY_TIMEOUT_".length).toLowerCase();
|
|
717
|
+
if (!tool) continue;
|
|
718
|
+
if (unset(raw)) continue;
|
|
719
|
+
if (!TOOLS_BY_NAME.has(tool)) {
|
|
720
|
+
throw new ConfigError(
|
|
721
|
+
key,
|
|
722
|
+
raw,
|
|
723
|
+
`AGY_TIMEOUT_<TOOL> for a tool this server has (${[...TOOLS_BY_NAME.keys()].join(", ")})`
|
|
724
|
+
);
|
|
725
|
+
}
|
|
726
|
+
out[tool] = durationSec(key, raw, 0);
|
|
727
|
+
}
|
|
728
|
+
return out;
|
|
729
|
+
}
|
|
730
|
+
function timeoutFor(cfg, toolName) {
|
|
731
|
+
return cfg.perToolTimeouts[toolName] ?? cfg.defaultTimeoutSec;
|
|
732
|
+
}
|
|
733
|
+
function delegationDepth(env = process.env) {
|
|
734
|
+
const raw = env.AGY_DELEGATION_DEPTH;
|
|
735
|
+
if (unset(raw)) return 0;
|
|
736
|
+
if (!DECIMAL.test(raw)) {
|
|
737
|
+
throw new ConfigError("AGY_DELEGATION_DEPTH", raw, "a non-negative integer");
|
|
738
|
+
}
|
|
739
|
+
return Number(raw);
|
|
740
|
+
}
|
|
741
|
+
function loadConfig(env = process.env) {
|
|
742
|
+
return {
|
|
743
|
+
agyPath: env.AGY_PATH || "agy",
|
|
744
|
+
defaultTimeoutSec: durationSec(
|
|
745
|
+
"AGY_TIMEOUT",
|
|
746
|
+
env.AGY_TIMEOUT,
|
|
747
|
+
durationSec("AGY_MAX_RUNTIME", env.AGY_MAX_RUNTIME, 3600)
|
|
748
|
+
),
|
|
749
|
+
perToolTimeouts: loadPerToolTimeouts(env),
|
|
750
|
+
maxOutputChars: positiveInt("AGY_MAX_OUTPUT_CHARS", env.AGY_MAX_OUTPUT_CHARS, 5e4),
|
|
751
|
+
defaultModel: env.AGY_DEFAULT_MODEL || "gemini-flash@latest-high",
|
|
752
|
+
defaultEffort: effort(env.AGY_EFFORT),
|
|
753
|
+
askModel: bool("AGY_ASK_MODEL", env.AGY_ASK_MODEL, true),
|
|
754
|
+
skipPermissions: bool("AGY_SKIP_PERMISSIONS", env.AGY_SKIP_PERMISSIONS, true),
|
|
755
|
+
sandbox: bool("AGY_SANDBOX", env.AGY_SANDBOX, false),
|
|
756
|
+
onFailure: onFailure(env.AGY_ON_FAILURE),
|
|
757
|
+
maxConcurrency: positiveInt("AGY_MAX_CONCURRENCY", env.AGY_MAX_CONCURRENCY, 2),
|
|
758
|
+
budgetTokens: optionalPositiveInt("AGY_BUDGET_TOKENS", env.AGY_BUDGET_TOKENS),
|
|
759
|
+
allowedRoots: parseRoots(env.AGY_ALLOWED_ROOTS),
|
|
760
|
+
redact: bool("AGY_REDACT", env.AGY_REDACT, true),
|
|
761
|
+
maxDelegationDepth: positiveInt("AGY_MAX_DELEGATION_DEPTH", env.AGY_MAX_DELEGATION_DEPTH, 1),
|
|
762
|
+
warmSessions: bool("AGY_WARM_SESSIONS", env.AGY_WARM_SESSIONS, true),
|
|
763
|
+
warmMax: positiveInt("AGY_WARM_MAX", env.AGY_WARM_MAX, 2),
|
|
764
|
+
warmIdleSec: durationSec("AGY_WARM_IDLE_SEC", env.AGY_WARM_IDLE_SEC, 300),
|
|
765
|
+
readOnlyEnforcement: readOnlyEnforcement(env.AGY_READ_ONLY_ENFORCEMENT)
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
// src/cooldown-store.ts
|
|
770
|
+
import {
|
|
771
|
+
existsSync as existsSync2,
|
|
772
|
+
mkdirSync,
|
|
773
|
+
readdirSync,
|
|
774
|
+
readFileSync,
|
|
775
|
+
renameSync,
|
|
776
|
+
rmSync as rmSync2,
|
|
777
|
+
writeFileSync
|
|
778
|
+
} from "node:fs";
|
|
779
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
780
|
+
import { homedir as homedir2 } from "node:os";
|
|
781
|
+
import path3 from "node:path";
|
|
782
|
+
|
|
783
|
+
// src/identity.ts
|
|
784
|
+
var SERVER_NAME = "antigravity-mcp";
|
|
785
|
+
var SERVER_TITLE = "Antigravity MCP";
|
|
786
|
+
var LEGACY_SERVER_NAME = "claude-agy-mcp";
|
|
787
|
+
|
|
788
|
+
// src/cooldown-store.ts
|
|
789
|
+
function cacheDir(env = process.env) {
|
|
790
|
+
return path3.join(env.XDG_CACHE_HOME || path3.join(homedir2(), ".cache"), SERVER_NAME);
|
|
791
|
+
}
|
|
792
|
+
function legacyCacheDir(env = process.env) {
|
|
793
|
+
return path3.join(env.XDG_CACHE_HOME || path3.join(homedir2(), ".cache"), LEGACY_SERVER_NAME);
|
|
794
|
+
}
|
|
795
|
+
function parse(raw) {
|
|
796
|
+
const v = JSON.parse(raw);
|
|
797
|
+
if (typeof v !== "object" || v === null) return {};
|
|
798
|
+
return Object.fromEntries(
|
|
799
|
+
Object.entries(v).filter(
|
|
800
|
+
(e) => typeof e[1] === "number" && Number.isFinite(e[1])
|
|
801
|
+
)
|
|
802
|
+
);
|
|
803
|
+
}
|
|
804
|
+
function merge(a, b) {
|
|
805
|
+
const out = { ...a };
|
|
806
|
+
for (const [model, until] of Object.entries(b)) {
|
|
807
|
+
if (until > (out[model] ?? 0)) out[model] = until;
|
|
808
|
+
}
|
|
809
|
+
return out;
|
|
810
|
+
}
|
|
811
|
+
var FileCooldownStore = class {
|
|
812
|
+
readDirs;
|
|
813
|
+
recordsDir;
|
|
814
|
+
own = {};
|
|
815
|
+
constructor(dir, legacyDir) {
|
|
816
|
+
const currentDir = dir ?? cacheDir();
|
|
817
|
+
const previousDir = legacyDir ?? (dir === void 0 ? legacyCacheDir() : void 0);
|
|
818
|
+
this.readDirs = [.../* @__PURE__ */ new Set([currentDir, ...previousDir === void 0 ? [] : [previousDir]])];
|
|
819
|
+
this.recordsDir = path3.join(currentDir, "cooldowns.d");
|
|
820
|
+
}
|
|
821
|
+
read(file) {
|
|
822
|
+
try {
|
|
823
|
+
return parse(readFileSync(file, "utf8"));
|
|
824
|
+
} catch {
|
|
825
|
+
return {};
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
records(dir = this.recordsDir) {
|
|
829
|
+
try {
|
|
830
|
+
return readdirSync(dir).filter((file) => /^[a-f0-9]{64}\.[\d.e+-]+\.json$/.test(file));
|
|
831
|
+
} catch {
|
|
832
|
+
return [];
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
fromDisk() {
|
|
836
|
+
let entries = {};
|
|
837
|
+
for (const dir of this.readDirs) {
|
|
838
|
+
entries = merge(entries, this.read(path3.join(dir, "cooldowns.json")));
|
|
839
|
+
const recordsDir = path3.join(dir, "cooldowns.d");
|
|
840
|
+
for (const file of this.records(recordsDir))
|
|
841
|
+
entries = merge(entries, this.read(path3.join(recordsDir, file)));
|
|
842
|
+
}
|
|
843
|
+
return entries;
|
|
844
|
+
}
|
|
845
|
+
load() {
|
|
846
|
+
return merge(this.fromDisk(), this.own);
|
|
847
|
+
}
|
|
848
|
+
save(entries, now) {
|
|
849
|
+
this.own = merge(this.own, entries);
|
|
850
|
+
for (const [model, until] of Object.entries(this.own)) {
|
|
851
|
+
if (!Number.isFinite(until) || until <= now) delete this.own[model];
|
|
852
|
+
}
|
|
853
|
+
try {
|
|
854
|
+
mkdirSync(this.recordsDir, { recursive: true, mode: 448 });
|
|
855
|
+
} catch {
|
|
856
|
+
return;
|
|
857
|
+
}
|
|
858
|
+
for (const [model, until] of Object.entries(this.own)) this.write(model, until);
|
|
859
|
+
for (const file of this.records()) {
|
|
860
|
+
const fullPath = path3.join(this.recordsDir, file);
|
|
861
|
+
const stored = Object.values(this.read(fullPath));
|
|
862
|
+
if (stored.length && stored.every((until) => until <= now)) {
|
|
863
|
+
try {
|
|
864
|
+
rmSync2(fullPath, { force: true });
|
|
865
|
+
} catch {
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
write(model, until) {
|
|
871
|
+
const key = createHash("sha256").update(model).digest("hex");
|
|
872
|
+
const file = path3.join(this.recordsDir, `${key}.${until}.json`);
|
|
873
|
+
if (existsSync2(file)) return;
|
|
874
|
+
const tmp = `${file}.${process.pid}.${randomUUID()}.tmp`;
|
|
875
|
+
try {
|
|
876
|
+
writeFileSync(tmp, JSON.stringify({ [model]: until }), {
|
|
877
|
+
encoding: "utf8",
|
|
878
|
+
mode: 384,
|
|
879
|
+
flag: "wx"
|
|
880
|
+
});
|
|
881
|
+
renameSync(tmp, file);
|
|
882
|
+
} catch {
|
|
883
|
+
try {
|
|
884
|
+
rmSync2(tmp, { force: true });
|
|
885
|
+
} catch {
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
};
|
|
890
|
+
|
|
891
|
+
// src/preferences.ts
|
|
892
|
+
import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "node:fs";
|
|
893
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
894
|
+
import { homedir as homedir3 } from "node:os";
|
|
895
|
+
import path4 from "node:path";
|
|
896
|
+
function configDir(env = process.env) {
|
|
897
|
+
return path4.join(env.XDG_CONFIG_HOME || path4.join(homedir3(), ".config"), SERVER_NAME);
|
|
898
|
+
}
|
|
899
|
+
function legacyConfigDir(env = process.env) {
|
|
900
|
+
return path4.join(env.XDG_CONFIG_HOME || path4.join(homedir3(), ".config"), LEGACY_SERVER_NAME);
|
|
901
|
+
}
|
|
902
|
+
var FilePreferenceStore = class {
|
|
903
|
+
file;
|
|
904
|
+
legacyFile;
|
|
905
|
+
constructor(dir, legacyDir) {
|
|
906
|
+
this.file = path4.join(dir ?? configDir(), "preferences.json");
|
|
907
|
+
const previousDir = legacyDir ?? (dir === void 0 ? legacyConfigDir() : void 0);
|
|
908
|
+
if (previousDir !== void 0) this.legacyFile = path4.join(previousDir, "preferences.json");
|
|
909
|
+
}
|
|
910
|
+
load() {
|
|
911
|
+
let contents;
|
|
912
|
+
try {
|
|
913
|
+
contents = readFileSync2(this.file, "utf8");
|
|
914
|
+
} catch (err) {
|
|
915
|
+
if (err.code !== "ENOENT" || !this.legacyFile) return null;
|
|
916
|
+
try {
|
|
917
|
+
contents = readFileSync2(this.legacyFile, "utf8");
|
|
918
|
+
} catch {
|
|
919
|
+
return null;
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
try {
|
|
923
|
+
const raw = JSON.parse(contents);
|
|
924
|
+
if (typeof raw !== "object" || raw === null) return null;
|
|
925
|
+
const o = raw;
|
|
926
|
+
if (typeof o.model !== "string" || !o.model.trim()) return null;
|
|
927
|
+
return {
|
|
928
|
+
model: o.model,
|
|
929
|
+
...isEffort(o.effort) ? { effort: o.effort } : {},
|
|
930
|
+
setAt: typeof o.setAt === "string" ? o.setAt : ""
|
|
931
|
+
};
|
|
932
|
+
} catch {
|
|
933
|
+
return null;
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
save(pref) {
|
|
937
|
+
mkdirSync2(path4.dirname(this.file), { recursive: true });
|
|
938
|
+
const tmp = `${this.file}.${process.pid}.${randomUUID2()}.tmp`;
|
|
939
|
+
try {
|
|
940
|
+
writeFileSync2(tmp, JSON.stringify(pref ?? {}, null, 2), "utf8");
|
|
941
|
+
renameSync2(tmp, this.file);
|
|
942
|
+
} catch (err) {
|
|
943
|
+
rmSync3(tmp, { force: true });
|
|
944
|
+
throw err;
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
};
|
|
948
|
+
var MemoryPreferenceStore = class {
|
|
949
|
+
pref = null;
|
|
950
|
+
load() {
|
|
951
|
+
return this.pref ? { ...this.pref } : null;
|
|
952
|
+
}
|
|
953
|
+
save(pref) {
|
|
954
|
+
this.pref = pref ? { ...pref } : null;
|
|
955
|
+
}
|
|
956
|
+
};
|
|
957
|
+
|
|
958
|
+
// src/concurrency.ts
|
|
959
|
+
var AbortError = class extends Error {
|
|
960
|
+
constructor() {
|
|
961
|
+
super("agy run cancelled by client.");
|
|
962
|
+
this.name = "AbortError";
|
|
963
|
+
}
|
|
964
|
+
};
|
|
965
|
+
var Semaphore = class {
|
|
966
|
+
constructor(limit) {
|
|
967
|
+
this.limit = limit;
|
|
968
|
+
}
|
|
969
|
+
limit;
|
|
970
|
+
active = 0;
|
|
971
|
+
waiting = [];
|
|
972
|
+
get inFlight() {
|
|
973
|
+
return this.active;
|
|
974
|
+
}
|
|
975
|
+
get queued() {
|
|
976
|
+
return this.waiting.length;
|
|
977
|
+
}
|
|
978
|
+
async acquire(signal) {
|
|
979
|
+
if (signal?.aborted) throw new AbortError();
|
|
980
|
+
if (this.active < this.limit) {
|
|
981
|
+
this.active++;
|
|
982
|
+
return this.releaseOnce();
|
|
983
|
+
}
|
|
984
|
+
await new Promise((resolve2, reject) => {
|
|
985
|
+
const waiter = () => {
|
|
986
|
+
signal?.removeEventListener("abort", onAbort);
|
|
987
|
+
resolve2();
|
|
988
|
+
};
|
|
989
|
+
const onAbort = () => {
|
|
990
|
+
const i = this.waiting.indexOf(waiter);
|
|
991
|
+
if (i >= 0) this.waiting.splice(i, 1);
|
|
992
|
+
reject(new AbortError());
|
|
993
|
+
};
|
|
994
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
995
|
+
this.waiting.push(waiter);
|
|
996
|
+
});
|
|
997
|
+
return this.releaseOnce();
|
|
998
|
+
}
|
|
999
|
+
releaseOnce() {
|
|
1000
|
+
let released = false;
|
|
1001
|
+
return () => {
|
|
1002
|
+
if (released) return;
|
|
1003
|
+
released = true;
|
|
1004
|
+
const next = this.waiting.shift();
|
|
1005
|
+
if (next) next();
|
|
1006
|
+
else this.active--;
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
1009
|
+
async run(fn, signal) {
|
|
1010
|
+
const release = await this.acquire(signal);
|
|
1011
|
+
try {
|
|
1012
|
+
return await fn();
|
|
1013
|
+
} finally {
|
|
1014
|
+
release();
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
};
|
|
1018
|
+
function abortOf(signal) {
|
|
1019
|
+
let onAbort = () => {
|
|
1020
|
+
};
|
|
1021
|
+
const promise = new Promise((_, reject) => {
|
|
1022
|
+
onAbort = () => reject(new AbortError());
|
|
1023
|
+
if (signal.aborted) onAbort();
|
|
1024
|
+
else signal.addEventListener("abort", onAbort, { once: true });
|
|
1025
|
+
});
|
|
1026
|
+
promise.catch(() => {
|
|
1027
|
+
});
|
|
1028
|
+
return { promise, dispose: () => signal.removeEventListener("abort", onAbort) };
|
|
1029
|
+
}
|
|
1030
|
+
var KeyedMutex = class {
|
|
1031
|
+
chains = /* @__PURE__ */ new Map();
|
|
1032
|
+
get held() {
|
|
1033
|
+
return this.chains.size;
|
|
1034
|
+
}
|
|
1035
|
+
async run(key, fn, signal) {
|
|
1036
|
+
const previous = this.chains.get(key) ?? Promise.resolve();
|
|
1037
|
+
const mine = previous.catch(() => {
|
|
1038
|
+
}).then(() => {
|
|
1039
|
+
if (signal?.aborted) throw new AbortError();
|
|
1040
|
+
return fn();
|
|
1041
|
+
});
|
|
1042
|
+
const cancelled = signal ? abortOf(signal) : void 0;
|
|
1043
|
+
this.chains.set(
|
|
1044
|
+
key,
|
|
1045
|
+
mine.catch(() => {
|
|
1046
|
+
})
|
|
1047
|
+
);
|
|
1048
|
+
try {
|
|
1049
|
+
return await (cancelled ? Promise.race([mine, cancelled.promise]) : mine);
|
|
1050
|
+
} finally {
|
|
1051
|
+
cancelled?.dispose();
|
|
1052
|
+
if (this.chains.get(key) !== void 0) {
|
|
1053
|
+
const current = this.chains.get(key);
|
|
1054
|
+
void Promise.resolve(current).then(() => {
|
|
1055
|
+
if (this.chains.get(key) === current) this.chains.delete(key);
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
};
|
|
1061
|
+
var Admission = class {
|
|
1062
|
+
semaphore;
|
|
1063
|
+
mutex = new KeyedMutex();
|
|
1064
|
+
constructor(limit) {
|
|
1065
|
+
this.semaphore = new Semaphore(limit);
|
|
1066
|
+
}
|
|
1067
|
+
get inFlight() {
|
|
1068
|
+
return this.semaphore.inFlight;
|
|
1069
|
+
}
|
|
1070
|
+
get queued() {
|
|
1071
|
+
return this.semaphore.queued;
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* Note that a fan-out whose legs share one `conversationId` runs strictly
|
|
1075
|
+
* sequentially, whatever `AGY_MAX_CONCURRENCY` says. That is intended, not a
|
|
1076
|
+
* throughput bug: agy keeps a per-conversation presence lock, so two
|
|
1077
|
+
* simultaneous turns against one conversation corrupt it rather than finishing
|
|
1078
|
+
* sooner. Fan out across conversations to get parallelism.
|
|
1079
|
+
*/
|
|
1080
|
+
run(conversationId, fn, signal) {
|
|
1081
|
+
const guarded = () => this.semaphore.run(fn, signal);
|
|
1082
|
+
return conversationId ? this.mutex.run(conversationId, guarded, signal) : guarded();
|
|
1083
|
+
}
|
|
1084
|
+
};
|
|
1085
|
+
|
|
1086
|
+
// src/egress.ts
|
|
1087
|
+
import { realpathSync as realpathSync2 } from "node:fs";
|
|
1088
|
+
import path5 from "node:path";
|
|
1089
|
+
|
|
1090
|
+
// src/quota.ts
|
|
1091
|
+
var DEFAULT_COOLDOWN_SEC = 15 * 60;
|
|
1092
|
+
var MIN_COOLDOWN_SEC = 60;
|
|
1093
|
+
var QUOTA_RE = /RESOURCE_EXHAUSTED|ResourceExhausted|\b(?:code|status|HTTP)[\s:=]*429\b|\b429 Too Many Requests\b|quota (?:exceeded|reached|exhausted)/im;
|
|
1094
|
+
var RESET_RE = /Resets in ((?:\d+d)?(?:\d+h)?(?:\d+m)?(?:\d+s)?)/;
|
|
1095
|
+
function parseResetDuration(text2) {
|
|
1096
|
+
const m = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(text2.trim());
|
|
1097
|
+
if (!m || !m.slice(1).some(Boolean)) return void 0;
|
|
1098
|
+
const seconds = Number(m[1] ?? 0) * 86400 + Number(m[2] ?? 0) * 3600 + Number(m[3] ?? 0) * 60 + Number(m[4] ?? 0);
|
|
1099
|
+
return Number.isFinite(seconds) ? seconds : void 0;
|
|
1100
|
+
}
|
|
1101
|
+
function formatDuration(totalSeconds) {
|
|
1102
|
+
const s = Math.max(0, Math.floor(totalSeconds));
|
|
1103
|
+
const h = Math.floor(s / 3600);
|
|
1104
|
+
const m = Math.floor(s % 3600 / 60);
|
|
1105
|
+
const sec = s % 60;
|
|
1106
|
+
let out = "";
|
|
1107
|
+
if (h) out += `${h}h`;
|
|
1108
|
+
if (m) out += `${m}m`;
|
|
1109
|
+
if (sec || !out) out += `${sec}s`;
|
|
1110
|
+
return out;
|
|
1111
|
+
}
|
|
1112
|
+
function detectQuota(log) {
|
|
1113
|
+
if (!QUOTA_RE.test(log)) return null;
|
|
1114
|
+
const reset = RESET_RE.exec(log)?.[1];
|
|
1115
|
+
const resetSeconds = reset ? parseResetDuration(reset) : void 0;
|
|
1116
|
+
return { resetText: resetSeconds !== void 0 ? reset : void 0, resetSeconds };
|
|
1117
|
+
}
|
|
1118
|
+
var QuotaError = class extends Error {
|
|
1119
|
+
constructor(model, info) {
|
|
1120
|
+
const who = model ?? "agy's default model";
|
|
1121
|
+
const when = info.resetText ? ` Quota resets in ${info.resetText}.` : "";
|
|
1122
|
+
super(`Quota exhausted for ${who} (RESOURCE_EXHAUSTED 429).${when}`);
|
|
1123
|
+
this.model = model;
|
|
1124
|
+
this.name = "QuotaError";
|
|
1125
|
+
this.resetSeconds = info.resetSeconds;
|
|
1126
|
+
this.resetText = info.resetText;
|
|
1127
|
+
}
|
|
1128
|
+
model;
|
|
1129
|
+
resetSeconds;
|
|
1130
|
+
resetText;
|
|
1131
|
+
/** Tokens the exhausted run still spent, when agy reported them. */
|
|
1132
|
+
usage;
|
|
1133
|
+
usageKnown;
|
|
1134
|
+
details;
|
|
1135
|
+
partialOutput;
|
|
1136
|
+
conversationId;
|
|
1137
|
+
finishedReason;
|
|
1138
|
+
numTurns;
|
|
1139
|
+
deniedActions;
|
|
1140
|
+
structuredOutput;
|
|
1141
|
+
};
|
|
1142
|
+
var MemoryCooldownStore = class {
|
|
1143
|
+
entries = {};
|
|
1144
|
+
load() {
|
|
1145
|
+
return { ...this.entries };
|
|
1146
|
+
}
|
|
1147
|
+
save(entries) {
|
|
1148
|
+
this.entries = { ...entries };
|
|
1149
|
+
}
|
|
1150
|
+
};
|
|
1151
|
+
var CooldownRegistry = class {
|
|
1152
|
+
constructor(store = new MemoryCooldownStore(), now = Date.now) {
|
|
1153
|
+
this.store = store;
|
|
1154
|
+
this.now = now;
|
|
1155
|
+
}
|
|
1156
|
+
store;
|
|
1157
|
+
now;
|
|
1158
|
+
/** Entries that have not yet expired, as model -> epoch ms. */
|
|
1159
|
+
live() {
|
|
1160
|
+
const t = this.now();
|
|
1161
|
+
return Object.fromEntries(Object.entries(this.store.load()).filter(([, until]) => until > t));
|
|
1162
|
+
}
|
|
1163
|
+
set(model, resetSeconds) {
|
|
1164
|
+
const entries = this.live();
|
|
1165
|
+
const t = this.now();
|
|
1166
|
+
const duration = Number.isFinite(resetSeconds) ? resetSeconds : DEFAULT_COOLDOWN_SEC;
|
|
1167
|
+
entries[model] = Math.max(entries[model] ?? 0, t + Math.max(duration, MIN_COOLDOWN_SEC) * 1e3);
|
|
1168
|
+
this.store.save(entries, t);
|
|
1169
|
+
}
|
|
1170
|
+
cooling(model) {
|
|
1171
|
+
return this.live()[model] !== void 0;
|
|
1172
|
+
}
|
|
1173
|
+
describe(model) {
|
|
1174
|
+
const until = this.live()[model];
|
|
1175
|
+
return formatDuration(until === void 0 ? 0 : (until - this.now()) / 1e3);
|
|
1176
|
+
}
|
|
1177
|
+
/** Every active cooldown, for the status tool. */
|
|
1178
|
+
active() {
|
|
1179
|
+
const t = this.now();
|
|
1180
|
+
return Object.entries(this.live()).map(([model, until]) => ({ model, secondsLeft: Math.round((until - t) / 1e3) })).sort((a, b) => b.secondsLeft - a.secondsLeft);
|
|
1181
|
+
}
|
|
1182
|
+
};
|
|
1183
|
+
|
|
1184
|
+
// src/failure.ts
|
|
1185
|
+
var POLICY = {
|
|
1186
|
+
quota: { failover: true, retryOnce: false },
|
|
1187
|
+
invalid_model: { failover: false, retryOnce: false },
|
|
1188
|
+
unauthenticated: { failover: false, retryOnce: false },
|
|
1189
|
+
network: { failover: false, retryOnce: false },
|
|
1190
|
+
empty: { failover: false, retryOnce: false },
|
|
1191
|
+
agy_error: { failover: false, retryOnce: false },
|
|
1192
|
+
not_installed: { failover: false, retryOnce: false }
|
|
1193
|
+
};
|
|
1194
|
+
function policyFor(kind) {
|
|
1195
|
+
return POLICY[kind];
|
|
1196
|
+
}
|
|
1197
|
+
var PATTERNS = [
|
|
1198
|
+
["invalid_model", /invalid model selection|is not recognized as a known model/i],
|
|
1199
|
+
["quota", QUOTA_RE],
|
|
1200
|
+
[
|
|
1201
|
+
"unauthenticated",
|
|
1202
|
+
/unauthenticated|not logged in|authentication failed|please (re-?)?login|invalid credentials|PERMISSION_DENIED|UNAUTHENTICATED|\b(?:code|status|HTTP)[\s:=]*401\b|\b401 Unauthorized\b|\bauth\w*\s+(has\s+)?expired|\btoken\s+(has\s+)?expired|re-authenticate/i
|
|
1203
|
+
],
|
|
1204
|
+
[
|
|
1205
|
+
"network",
|
|
1206
|
+
/dial tcp|no such host|connection refused|connection reset|network is unreachable|i\/o timeout|TLS handshake|:\s*EOF\s*$|ENOTFOUND|ECONNRESET|ETIMEDOUT/im
|
|
1207
|
+
]
|
|
1208
|
+
];
|
|
1209
|
+
function classifyMessage(text2) {
|
|
1210
|
+
for (const [kind, re] of PATTERNS) if (re.test(text2)) return kind;
|
|
1211
|
+
return void 0;
|
|
1212
|
+
}
|
|
1213
|
+
function parseAgyError(stderr) {
|
|
1214
|
+
for (const line of stderr.split("\n").reverse()) {
|
|
1215
|
+
const diagnostic = line.trimStart();
|
|
1216
|
+
if (!diagnostic.startsWith("AGY_ERROR:")) continue;
|
|
1217
|
+
try {
|
|
1218
|
+
const value = JSON.parse(diagnostic.slice("AGY_ERROR:".length).trim());
|
|
1219
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) continue;
|
|
1220
|
+
const o = value;
|
|
1221
|
+
const id = o.error_id ?? o.errorId ?? o.id;
|
|
1222
|
+
return {
|
|
1223
|
+
...typeof o.status === "string" ? { status: o.status } : {},
|
|
1224
|
+
...typeof o.code === "string" || typeof o.code === "number" ? { code: o.code } : {},
|
|
1225
|
+
...typeof o.retryable === "boolean" ? { retryable: o.retryable } : {},
|
|
1226
|
+
...typeof id === "string" ? { errorId: id } : {}
|
|
1227
|
+
};
|
|
1228
|
+
} catch {
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
return void 0;
|
|
1232
|
+
}
|
|
1233
|
+
function kindOfDetails(details) {
|
|
1234
|
+
if (!details) return void 0;
|
|
1235
|
+
const code = Number(details.code);
|
|
1236
|
+
if (details.status === "RESOURCE_EXHAUSTED" || [8, 429].includes(code)) return "quota";
|
|
1237
|
+
if (details.status === "UNAUTHENTICATED" || details.status === "PERMISSION_DENIED" || [7, 16, 401, 403].includes(code))
|
|
1238
|
+
return "unauthenticated";
|
|
1239
|
+
if (details.status === "UNAVAILABLE" || details.status === "DEADLINE_EXCEEDED" || [4, 14, 502, 503, 504].includes(code))
|
|
1240
|
+
return "network";
|
|
1241
|
+
return void 0;
|
|
1242
|
+
}
|
|
1243
|
+
function classifyRun(input) {
|
|
1244
|
+
const { envelope, exitCode, stderr } = input;
|
|
1245
|
+
const structuredKind = kindOfDetails(parseAgyError(stderr));
|
|
1246
|
+
if (envelope) {
|
|
1247
|
+
if (envelope.status !== "SUCCESS" || envelope.finishedReason) {
|
|
1248
|
+
const text3 = envelope.error || (envelope.finishedReason ? `agy ended early (${envelope.finishedReason}).` : envelope.response) || `agy status ${envelope.status}`;
|
|
1249
|
+
return { kind: structuredKind ?? classifyMessage(text3) ?? "agy_error", message: text3.trim() };
|
|
1250
|
+
}
|
|
1251
|
+
if (exitCode !== 0) {
|
|
1252
|
+
return {
|
|
1253
|
+
kind: structuredKind ?? classifyMessage(stderr) ?? "agy_error",
|
|
1254
|
+
message: stderr.trim() || `agy exited with code ${exitCode} after reporting a response.`
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
if (!envelope.response.trim()) {
|
|
1258
|
+
return {
|
|
1259
|
+
kind: "empty",
|
|
1260
|
+
message: "agy reported SUCCESS with an empty response \u2014 the turn produced no answer (usually its print-timeout elapsed mid-run)."
|
|
1261
|
+
};
|
|
1262
|
+
}
|
|
1263
|
+
return null;
|
|
1264
|
+
}
|
|
1265
|
+
const text2 = stderr.trim();
|
|
1266
|
+
if (exitCode !== 0) {
|
|
1267
|
+
return {
|
|
1268
|
+
kind: structuredKind ?? classifyMessage(text2) ?? "agy_error",
|
|
1269
|
+
message: text2 || `agy exited with code ${exitCode}.`
|
|
1270
|
+
};
|
|
1271
|
+
}
|
|
1272
|
+
return null;
|
|
1273
|
+
}
|
|
1274
|
+
var InvalidRequestError = class extends Error {
|
|
1275
|
+
constructor(message) {
|
|
1276
|
+
super(message);
|
|
1277
|
+
this.name = "InvalidRequestError";
|
|
1278
|
+
}
|
|
1279
|
+
};
|
|
1280
|
+
var AgyFailure = class extends Error {
|
|
1281
|
+
constructor(kind, message, model) {
|
|
1282
|
+
super(message);
|
|
1283
|
+
this.kind = kind;
|
|
1284
|
+
this.model = model;
|
|
1285
|
+
this.name = "AgyFailure";
|
|
1286
|
+
}
|
|
1287
|
+
kind;
|
|
1288
|
+
model;
|
|
1289
|
+
/** Tokens the failed run still spent, when agy reported them. */
|
|
1290
|
+
usage;
|
|
1291
|
+
usageKnown;
|
|
1292
|
+
/** Provider retryability is diagnostic; it never proves an agent turn is safe to replay. */
|
|
1293
|
+
details;
|
|
1294
|
+
partialOutput;
|
|
1295
|
+
conversationId;
|
|
1296
|
+
finishedReason;
|
|
1297
|
+
numTurns;
|
|
1298
|
+
deniedActions;
|
|
1299
|
+
structuredOutput;
|
|
1300
|
+
get policy() {
|
|
1301
|
+
return policyFor(this.kind);
|
|
1302
|
+
}
|
|
1303
|
+
};
|
|
1304
|
+
var MAX_RAW_OUTPUT_BYTES = 64 * 1024 * 1024;
|
|
1305
|
+
var OutputLimitError = class extends AgyFailure {
|
|
1306
|
+
constructor(source, limitBytes, model) {
|
|
1307
|
+
super(
|
|
1308
|
+
"agy_error",
|
|
1309
|
+
`agy ${source} exceeded the bridge's ${limitBytes}-byte raw output limit. The turn was stopped and its output is incomplete; actions may already have run. Ask a narrower question or have agy write large artifacts to workspace files. AGY_MAX_OUTPUT_CHARS controls returned text and does not raise this safety limit.`,
|
|
1310
|
+
model
|
|
1311
|
+
);
|
|
1312
|
+
this.source = source;
|
|
1313
|
+
this.limitBytes = limitBytes;
|
|
1314
|
+
this.name = "OutputLimitError";
|
|
1315
|
+
this.finishedReason = "output_limit";
|
|
1316
|
+
this.usageKnown = false;
|
|
1317
|
+
}
|
|
1318
|
+
source;
|
|
1319
|
+
limitBytes;
|
|
1320
|
+
};
|
|
1321
|
+
|
|
1322
|
+
// src/egress.ts
|
|
1323
|
+
var PathNotAllowedError = class extends InvalidRequestError {
|
|
1324
|
+
constructor(offending, roots) {
|
|
1325
|
+
super(
|
|
1326
|
+
`Path "${offending}" is outside the allowed roots.
|
|
1327
|
+
Allowed: ${roots.join(", ")}
|
|
1328
|
+
Set AGY_ALLOWED_ROOTS to change this.`
|
|
1329
|
+
);
|
|
1330
|
+
this.offending = offending;
|
|
1331
|
+
this.name = "PathNotAllowedError";
|
|
1332
|
+
}
|
|
1333
|
+
offending;
|
|
1334
|
+
};
|
|
1335
|
+
function within(candidate, root) {
|
|
1336
|
+
const rel = path5.relative(root, candidate);
|
|
1337
|
+
return rel === "" || rel !== ".." && !rel.startsWith(`..${path5.sep}`) && !path5.isAbsolute(rel);
|
|
1338
|
+
}
|
|
1339
|
+
function canonical(p) {
|
|
1340
|
+
const absolute = path5.isAbsolute(p) ? p : `${process.cwd()}${path5.sep}${p}`;
|
|
1341
|
+
const parts = absolute.split(path5.sep);
|
|
1342
|
+
for (let cut = parts.length; cut > 0; cut--) {
|
|
1343
|
+
const head = parts.slice(0, cut).join(path5.sep) || path5.sep;
|
|
1344
|
+
try {
|
|
1345
|
+
return path5.resolve(realpathSync2.native(head), ...parts.slice(cut));
|
|
1346
|
+
} catch {
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
return path5.resolve(absolute);
|
|
1350
|
+
}
|
|
1351
|
+
function assertWithinRoots(paths2, roots) {
|
|
1352
|
+
if (roots.length === 0) return;
|
|
1353
|
+
const resolvedRoots = roots.map(canonical);
|
|
1354
|
+
for (const p of paths2) {
|
|
1355
|
+
const resolved = canonical(p);
|
|
1356
|
+
if (!resolvedRoots.some((r) => within(resolved, r))) {
|
|
1357
|
+
throw new PathNotAllowedError(p, resolvedRoots);
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
var KNOWN_SECRETS = [
|
|
1362
|
+
["openai key", /\bsk-[A-Za-z0-9_-]{20,}\b/g],
|
|
1363
|
+
// Stripe and friends use an underscore, so the hyphenated `sk-` rule above
|
|
1364
|
+
// never matched them. Live keys are the ones worth catching.
|
|
1365
|
+
["stripe key", /\b[srp]k_(?:live|test)_[A-Za-z0-9]{16,}\b/g],
|
|
1366
|
+
["github token", /\bgh[pousr]_[A-Za-z0-9]{20,}\b/g],
|
|
1367
|
+
["gitlab token", /\bglpat-[A-Za-z0-9_-]{20,}\b/g],
|
|
1368
|
+
["npm token", /\bnpm_[A-Za-z0-9]{30,}\b/g],
|
|
1369
|
+
["aws access key", /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g],
|
|
1370
|
+
["google api key", /\bAIza[0-9A-Za-z_-]{30,}\b/g],
|
|
1371
|
+
["slack token", /\bxox[abprs]-[0-9A-Za-z-]{10,}\b/g],
|
|
1372
|
+
["jwt", /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g],
|
|
1373
|
+
[
|
|
1374
|
+
"private key block",
|
|
1375
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g
|
|
1376
|
+
]
|
|
1377
|
+
];
|
|
1378
|
+
var URL_CREDENTIALS = /\b([a-z][a-z0-9+.-]*:\/\/)([^\s/:@]+):([^\s/@]+)@/gi;
|
|
1379
|
+
var ASSIGNED_SECRET = /\b([A-Za-z_][A-Za-z0-9_]{0,48}?(?:SECRET|TOKEN|PASSWORD|PASSWD|APIKEY|API_KEY|ACCESS_KEY|PRIVATE_KEY)[A-Za-z0-9_]{0,48})(\s*[:=]\s*"?)([^\s"']{8,})/gi;
|
|
1380
|
+
function redact(text2) {
|
|
1381
|
+
let count = 0;
|
|
1382
|
+
let out = text2;
|
|
1383
|
+
for (const [label, re] of KNOWN_SECRETS) {
|
|
1384
|
+
out = out.replace(re, () => {
|
|
1385
|
+
count++;
|
|
1386
|
+
return `[redacted ${label}]`;
|
|
1387
|
+
});
|
|
1388
|
+
}
|
|
1389
|
+
out = out.replace(URL_CREDENTIALS, (_m, scheme, user) => {
|
|
1390
|
+
count++;
|
|
1391
|
+
return `${scheme}${user}:[redacted]@`;
|
|
1392
|
+
});
|
|
1393
|
+
out = out.replace(ASSIGNED_SECRET, (_m, name, sep) => {
|
|
1394
|
+
count++;
|
|
1395
|
+
return `${name}${sep}[redacted]`;
|
|
1396
|
+
});
|
|
1397
|
+
return { text: out, count };
|
|
1398
|
+
}
|
|
1399
|
+
function redactDeep(value) {
|
|
1400
|
+
let count = 0;
|
|
1401
|
+
const walk2 = (v) => {
|
|
1402
|
+
if (typeof v === "string") {
|
|
1403
|
+
const r = redact(v);
|
|
1404
|
+
count += r.count;
|
|
1405
|
+
return r.text;
|
|
1406
|
+
}
|
|
1407
|
+
if (Array.isArray(v)) return v.map(walk2);
|
|
1408
|
+
if (v && typeof v === "object") {
|
|
1409
|
+
const entries = Object.entries(v).map(([key, x]) => {
|
|
1410
|
+
const safe = redact(key);
|
|
1411
|
+
count += safe.count;
|
|
1412
|
+
return { original: key, key: safe.text, value: walk2(x) };
|
|
1413
|
+
});
|
|
1414
|
+
const frequencies = /* @__PURE__ */ new Map();
|
|
1415
|
+
for (const { key } of entries) frequencies.set(key, (frequencies.get(key) ?? 0) + 1);
|
|
1416
|
+
const reserved = new Set(entries.map(({ key }) => key));
|
|
1417
|
+
let collision = 0;
|
|
1418
|
+
return Object.fromEntries(
|
|
1419
|
+
entries.map(({ original, key, value: value2 }) => {
|
|
1420
|
+
if (key !== original && frequencies.get(key) > 1) {
|
|
1421
|
+
let unique;
|
|
1422
|
+
do {
|
|
1423
|
+
unique = `${key} [redacted field ${++collision}]`;
|
|
1424
|
+
} while (reserved.has(unique));
|
|
1425
|
+
reserved.add(unique);
|
|
1426
|
+
return [unique, value2];
|
|
1427
|
+
}
|
|
1428
|
+
return [key, value2];
|
|
1429
|
+
})
|
|
1430
|
+
);
|
|
1431
|
+
}
|
|
1432
|
+
return v;
|
|
1433
|
+
};
|
|
1434
|
+
const out = walk2(value);
|
|
1435
|
+
return { value: out, count };
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
// src/worktree.ts
|
|
1439
|
+
import { execFile as execFile4, spawn } from "node:child_process";
|
|
1440
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
1441
|
+
import { lstat, readdir } from "node:fs/promises";
|
|
1442
|
+
import path6 from "node:path";
|
|
1443
|
+
import { promisify as promisify3 } from "node:util";
|
|
1444
|
+
var exec = promisify3(execFile4);
|
|
1445
|
+
var insideState = (full) => confinedRoots([AGY_STATE_DIR]).some((dir) => full === dir || full.startsWith(dir + path6.sep));
|
|
1446
|
+
var ALWAYS_SKIP = /* @__PURE__ */ new Set([".git"]);
|
|
1447
|
+
var TOP_SKIP = /* @__PURE__ */ new Set(["node_modules", ".venv", "venv", "__pycache__", ".next", "dist"]);
|
|
1448
|
+
var MAX_ENTRIES = 2e4;
|
|
1449
|
+
var IGNORED_DIR_ENTRIES = 1e3;
|
|
1450
|
+
var DEADLINE_MS = 1e4;
|
|
1451
|
+
var GIT_TIMEOUT_MS = DEADLINE_MS;
|
|
1452
|
+
function hashGit(cwd, args, hash) {
|
|
1453
|
+
return new Promise((resolve2) => {
|
|
1454
|
+
const child = spawn("git", ["--no-optional-locks", ...args], {
|
|
1455
|
+
cwd,
|
|
1456
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
1457
|
+
});
|
|
1458
|
+
const timer = setTimeout(() => child.kill("SIGKILL"), GIT_TIMEOUT_MS);
|
|
1459
|
+
child.stdout.on("data", (d) => hash.update(d));
|
|
1460
|
+
child.on("error", () => {
|
|
1461
|
+
clearTimeout(timer);
|
|
1462
|
+
resolve2(false);
|
|
1463
|
+
});
|
|
1464
|
+
child.on("close", (code, signal) => {
|
|
1465
|
+
clearTimeout(timer);
|
|
1466
|
+
resolve2(code === 0 && signal === null);
|
|
1467
|
+
});
|
|
1468
|
+
});
|
|
1469
|
+
}
|
|
1470
|
+
function overBudget(budget) {
|
|
1471
|
+
if (++budget.seen > budget.max) return "entries";
|
|
1472
|
+
if (Date.now() > budget.deadline) return "deadline";
|
|
1473
|
+
return void 0;
|
|
1474
|
+
}
|
|
1475
|
+
var describe = (stop) => stop === "entries" ? `more than ${MAX_ENTRIES} entries` : stop === "unreadable" ? "a workspace path could not be read" : `scan exceeded ${DEADLINE_MS / 1e3}s`;
|
|
1476
|
+
async function hashMeta(hash, full) {
|
|
1477
|
+
hash.update(full).update("\0");
|
|
1478
|
+
try {
|
|
1479
|
+
const st = await lstat(full);
|
|
1480
|
+
hash.update(`${st.mode}:${st.size}:${st.mtimeMs}`);
|
|
1481
|
+
} catch {
|
|
1482
|
+
return false;
|
|
1483
|
+
}
|
|
1484
|
+
hash.update("\0");
|
|
1485
|
+
return true;
|
|
1486
|
+
}
|
|
1487
|
+
async function walk(hash, dir, budget, top) {
|
|
1488
|
+
let entries;
|
|
1489
|
+
try {
|
|
1490
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
1491
|
+
} catch {
|
|
1492
|
+
return "unreadable";
|
|
1493
|
+
}
|
|
1494
|
+
for (const e of entries.sort((a, b) => a.name < b.name ? -1 : 1)) {
|
|
1495
|
+
if (ALWAYS_SKIP.has(e.name) || top && TOP_SKIP.has(e.name)) continue;
|
|
1496
|
+
const over = overBudget(budget);
|
|
1497
|
+
if (over) return over;
|
|
1498
|
+
const full = path6.join(dir, e.name);
|
|
1499
|
+
if (insideState(full)) continue;
|
|
1500
|
+
if (!await hashMeta(hash, full)) return "unreadable";
|
|
1501
|
+
if (e.isDirectory()) {
|
|
1502
|
+
const incomplete = await walk(hash, full, budget, false);
|
|
1503
|
+
if (incomplete) return incomplete;
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
return void 0;
|
|
1507
|
+
}
|
|
1508
|
+
async function hashListed(hash, root, rels, budget) {
|
|
1509
|
+
for (const rel of rels) {
|
|
1510
|
+
const over = overBudget(budget);
|
|
1511
|
+
if (over) return over;
|
|
1512
|
+
const full = path6.join(root, rel);
|
|
1513
|
+
if (insideState(full.replace(/\/$/, ""))) continue;
|
|
1514
|
+
if (!await hashMeta(hash, full)) return "unreadable";
|
|
1515
|
+
if (!rel.endsWith("/")) continue;
|
|
1516
|
+
if (TOP_SKIP.has(path6.basename(full)) && path6.dirname(full) === root) continue;
|
|
1517
|
+
const inner = { seen: 0, max: IGNORED_DIR_ENTRIES, deadline: budget.deadline };
|
|
1518
|
+
const stop = await walk(hash, full, inner, false);
|
|
1519
|
+
budget.seen += inner.seen;
|
|
1520
|
+
if (stop === "deadline" || stop === "unreadable") return stop;
|
|
1521
|
+
if (stop === "entries") hash.update("truncated\0");
|
|
1522
|
+
}
|
|
1523
|
+
return void 0;
|
|
1524
|
+
}
|
|
1525
|
+
function stateExclusion(root) {
|
|
1526
|
+
for (const dir of confinedRoots([AGY_STATE_DIR])) {
|
|
1527
|
+
const rel = path6.relative(root, dir);
|
|
1528
|
+
if (rel && !rel.startsWith("..") && !path6.isAbsolute(rel)) {
|
|
1529
|
+
return ["--", ".", `:(exclude,top,literal)${rel}`];
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
return [];
|
|
1533
|
+
}
|
|
1534
|
+
async function listOthers(root, selectors) {
|
|
1535
|
+
const { stdout } = await exec(
|
|
1536
|
+
"git",
|
|
1537
|
+
["--no-optional-locks", "ls-files", "--others", "--exclude-standard", "-z", ...selectors],
|
|
1538
|
+
{ cwd: root, timeout: GIT_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024 }
|
|
1539
|
+
);
|
|
1540
|
+
return stdout.split("\0").filter(Boolean);
|
|
1541
|
+
}
|
|
1542
|
+
function hashContents(root, files, hash) {
|
|
1543
|
+
return new Promise((resolve2) => {
|
|
1544
|
+
const child = spawn("git", ["--no-optional-locks", "hash-object", "--stdin-paths"], {
|
|
1545
|
+
cwd: root,
|
|
1546
|
+
stdio: ["pipe", "pipe", "ignore"]
|
|
1547
|
+
});
|
|
1548
|
+
const timer = setTimeout(() => child.kill("SIGKILL"), GIT_TIMEOUT_MS);
|
|
1549
|
+
child.stdin.on("error", () => {
|
|
1550
|
+
});
|
|
1551
|
+
child.stdout.on("data", (d) => hash.update(d));
|
|
1552
|
+
child.on("error", () => {
|
|
1553
|
+
clearTimeout(timer);
|
|
1554
|
+
resolve2(false);
|
|
1555
|
+
});
|
|
1556
|
+
child.on("close", (code, signal) => {
|
|
1557
|
+
clearTimeout(timer);
|
|
1558
|
+
resolve2(code === 0 && signal === null);
|
|
1559
|
+
});
|
|
1560
|
+
child.stdin.end(`${files.join("\n")}
|
|
1561
|
+
`);
|
|
1562
|
+
});
|
|
1563
|
+
}
|
|
1564
|
+
async function gitSnapshot(cwd) {
|
|
1565
|
+
try {
|
|
1566
|
+
const budget = { seen: 0, max: MAX_ENTRIES, deadline: Date.now() + DEADLINE_MS };
|
|
1567
|
+
const { stdout: top } = await exec("git", ["rev-parse", "--show-toplevel"], {
|
|
1568
|
+
cwd,
|
|
1569
|
+
timeout: GIT_TIMEOUT_MS
|
|
1570
|
+
});
|
|
1571
|
+
const root = top.trim();
|
|
1572
|
+
const hash = createHash2("sha256");
|
|
1573
|
+
const head = await exec("git", ["rev-parse", "HEAD"], { cwd: root, timeout: GIT_TIMEOUT_MS }).then((r) => r.stdout).catch(() => "");
|
|
1574
|
+
hash.update(head).update("\0");
|
|
1575
|
+
const skip = stateExclusion(root);
|
|
1576
|
+
const diff = head ? ["diff", "HEAD", "--binary", "--no-ext-diff", "--no-color", ...skip] : ["diff", "--cached", "--binary", "--no-ext-diff", "--no-color", ...skip];
|
|
1577
|
+
if (!await hashGit(root, diff, hash)) return void 0;
|
|
1578
|
+
hash.update("\0");
|
|
1579
|
+
const status = ["status", "--porcelain=v1", "-z", "--untracked-files=all", ...skip];
|
|
1580
|
+
if (!await hashGit(root, status, hash)) {
|
|
1581
|
+
return void 0;
|
|
1582
|
+
}
|
|
1583
|
+
hash.update("\0");
|
|
1584
|
+
const untracked = await listOthers(root, skip);
|
|
1585
|
+
const byMeta = untracked.filter((f) => f.endsWith("/") || f.includes("\n"));
|
|
1586
|
+
const byContent = untracked.filter((f) => !byMeta.includes(f));
|
|
1587
|
+
if (byContent.length > MAX_ENTRIES) return void 0;
|
|
1588
|
+
if (byContent.length && !await hashContents(root, byContent, hash)) return void 0;
|
|
1589
|
+
hash.update("\0");
|
|
1590
|
+
if (await hashListed(hash, root, byMeta, budget)) return void 0;
|
|
1591
|
+
hash.update("\0");
|
|
1592
|
+
const ignored = await listOthers(root, ["--ignored", "--directory", ...skip]);
|
|
1593
|
+
if (await hashListed(hash, root, ignored, budget)) return void 0;
|
|
1594
|
+
return { method: "git", digest: hash.digest("hex") };
|
|
1595
|
+
} catch {
|
|
1596
|
+
return void 0;
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
async function scanSnapshot(cwd) {
|
|
1600
|
+
const hash = createHash2("sha256");
|
|
1601
|
+
const budget = { seen: 0, max: MAX_ENTRIES, deadline: Date.now() + DEADLINE_MS };
|
|
1602
|
+
const stop = await walk(hash, cwd, budget, true);
|
|
1603
|
+
if (stop) return { method: "none", reason: `${describe(stop)}; not fingerprinted` };
|
|
1604
|
+
return { method: "scan", digest: hash.digest("hex") };
|
|
1605
|
+
}
|
|
1606
|
+
async function snapshotTree(given) {
|
|
1607
|
+
const cwd = path6.resolve(given);
|
|
1608
|
+
if (insideState(cwd)) {
|
|
1609
|
+
return { method: "none", reason: "inside agy's own state directory; not fingerprinted" };
|
|
1610
|
+
}
|
|
1611
|
+
return await gitSnapshot(cwd) ?? await scanSnapshot(cwd);
|
|
1612
|
+
}
|
|
1613
|
+
function combineSnapshots(snaps) {
|
|
1614
|
+
const uncovered = snaps.find((s) => !s.digest);
|
|
1615
|
+
if (uncovered) {
|
|
1616
|
+
return { method: "none", ...uncovered.reason ? { reason: uncovered.reason } : {} };
|
|
1617
|
+
}
|
|
1618
|
+
if (snaps.length === 1) return snaps[0];
|
|
1619
|
+
const hash = createHash2("sha256");
|
|
1620
|
+
for (const s of snaps) hash.update(s.method).update(":").update(s.digest).update("\0");
|
|
1621
|
+
return {
|
|
1622
|
+
method: snaps[0].method,
|
|
1623
|
+
methods: snaps.map((s) => s.method).join(","),
|
|
1624
|
+
digest: hash.digest("hex")
|
|
1625
|
+
};
|
|
1626
|
+
}
|
|
1627
|
+
function treeChanged(before, after) {
|
|
1628
|
+
if (!before.digest || !after.digest) return void 0;
|
|
1629
|
+
if ((before.methods ?? before.method) !== (after.methods ?? after.method)) return void 0;
|
|
1630
|
+
return before.digest !== after.digest;
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
// src/envelope.ts
|
|
1634
|
+
var EMPTY_USAGE = {
|
|
1635
|
+
inputTokens: 0,
|
|
1636
|
+
outputTokens: 0,
|
|
1637
|
+
thinkingTokens: 0,
|
|
1638
|
+
cacheReadTokens: 0,
|
|
1639
|
+
totalTokens: 0
|
|
1640
|
+
};
|
|
1641
|
+
function num(v) {
|
|
1642
|
+
return typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : 0;
|
|
1643
|
+
}
|
|
1644
|
+
function hasUsage(raw) {
|
|
1645
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
|
|
1646
|
+
const u = raw;
|
|
1647
|
+
return [
|
|
1648
|
+
"input_tokens",
|
|
1649
|
+
"output_tokens",
|
|
1650
|
+
"thinking_tokens",
|
|
1651
|
+
"cache_read_tokens",
|
|
1652
|
+
"total_tokens"
|
|
1653
|
+
].every(
|
|
1654
|
+
(key) => typeof u[key] === "number" && Number.isFinite(u[key]) && u[key] >= 0
|
|
1655
|
+
);
|
|
1656
|
+
}
|
|
1657
|
+
function str(v) {
|
|
1658
|
+
return typeof v === "string" ? v : "";
|
|
1659
|
+
}
|
|
1660
|
+
function usageOf(raw) {
|
|
1661
|
+
const u = raw ?? {};
|
|
1662
|
+
return {
|
|
1663
|
+
inputTokens: num(u.input_tokens),
|
|
1664
|
+
outputTokens: num(u.output_tokens),
|
|
1665
|
+
thinkingTokens: num(u.thinking_tokens),
|
|
1666
|
+
cacheReadTokens: num(u.cache_read_tokens),
|
|
1667
|
+
totalTokens: num(u.total_tokens)
|
|
1668
|
+
};
|
|
1669
|
+
}
|
|
1670
|
+
function deniedOf(raw) {
|
|
1671
|
+
if (!Array.isArray(raw)) return [];
|
|
1672
|
+
return raw.map((d) => {
|
|
1673
|
+
const o = d ?? {};
|
|
1674
|
+
return { action: str(o.action), displayName: str(o.display_name) || str(o.action) };
|
|
1675
|
+
});
|
|
1676
|
+
}
|
|
1677
|
+
function shape(o) {
|
|
1678
|
+
if (typeof o.status !== "string") return null;
|
|
1679
|
+
const conversationId = str(o.conversation_id);
|
|
1680
|
+
return {
|
|
1681
|
+
...conversationId ? { conversationId } : {},
|
|
1682
|
+
status: o.status,
|
|
1683
|
+
...str(o.finished_reason) ? { finishedReason: str(o.finished_reason) } : {},
|
|
1684
|
+
response: str(o.response),
|
|
1685
|
+
...str(o.error) ? { error: str(o.error) } : {},
|
|
1686
|
+
numTurns: num(o.num_turns),
|
|
1687
|
+
durationSeconds: num(o.duration_seconds),
|
|
1688
|
+
usage: usageOf(o.usage),
|
|
1689
|
+
usageKnown: hasUsage(o.usage),
|
|
1690
|
+
deniedActions: deniedOf(o.denied_actions),
|
|
1691
|
+
...o.structured_output !== void 0 ? { structuredOutput: o.structured_output } : {}
|
|
1692
|
+
};
|
|
1693
|
+
}
|
|
1694
|
+
function decodeObject(line) {
|
|
1695
|
+
const trimmed = line.trim();
|
|
1696
|
+
if (!trimmed.startsWith("{")) return null;
|
|
1697
|
+
try {
|
|
1698
|
+
const v = JSON.parse(trimmed);
|
|
1699
|
+
return typeof v === "object" && v !== null ? v : null;
|
|
1700
|
+
} catch {
|
|
1701
|
+
return null;
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
function parseEnvelope(stdout) {
|
|
1705
|
+
const lines = stdout.split("\n");
|
|
1706
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
1707
|
+
const o = decodeObject(lines[i]);
|
|
1708
|
+
if (!o) continue;
|
|
1709
|
+
const env = str(o.event) === "result" ? resultEnvelope(o) : shape(o);
|
|
1710
|
+
if (env) return env;
|
|
1711
|
+
}
|
|
1712
|
+
return null;
|
|
1713
|
+
}
|
|
1714
|
+
function resultEnvelope(o) {
|
|
1715
|
+
const r = o.result;
|
|
1716
|
+
return typeof r === "object" && r !== null ? shape(r) : null;
|
|
1717
|
+
}
|
|
1718
|
+
function streamEvent(o) {
|
|
1719
|
+
const event = str(o.event);
|
|
1720
|
+
if (!event) return null;
|
|
1721
|
+
if (event === "init") {
|
|
1722
|
+
const init = o.init ?? {};
|
|
1723
|
+
const conversationId = str(o.conversation_id) || str(init.conversation_id);
|
|
1724
|
+
return {
|
|
1725
|
+
kind: "init",
|
|
1726
|
+
...conversationId ? { conversationId } : {},
|
|
1727
|
+
...str(init.cwd) ? { cwd: str(init.cwd) } : {},
|
|
1728
|
+
tools: Array.isArray(init.tools) ? init.tools.filter((t) => typeof t === "string") : [],
|
|
1729
|
+
...str(init.permission_mode) ? { permissionMode: str(init.permission_mode) } : {}
|
|
1730
|
+
};
|
|
1731
|
+
}
|
|
1732
|
+
if (event === "step_update") {
|
|
1733
|
+
const s = o.step_update ?? {};
|
|
1734
|
+
return {
|
|
1735
|
+
kind: "step",
|
|
1736
|
+
stepIndex: num(s.step_index),
|
|
1737
|
+
state: str(s.state),
|
|
1738
|
+
stepType: str(s.step_type),
|
|
1739
|
+
textDelta: str(s.text_delta),
|
|
1740
|
+
...s.usage ? { usage: usageOf(s.usage) } : {}
|
|
1741
|
+
};
|
|
1742
|
+
}
|
|
1743
|
+
if (event === "result") {
|
|
1744
|
+
const env = resultEnvelope(o);
|
|
1745
|
+
return env ? { kind: "result", envelope: env } : null;
|
|
1746
|
+
}
|
|
1747
|
+
return { kind: "other", event };
|
|
1748
|
+
}
|
|
1749
|
+
function parseStreamEvents(chunk) {
|
|
1750
|
+
const lines = chunk.split("\n");
|
|
1751
|
+
const rest = lines.pop() ?? "";
|
|
1752
|
+
const events = [];
|
|
1753
|
+
for (const line of lines) {
|
|
1754
|
+
const o = decodeObject(line);
|
|
1755
|
+
const ev = o && streamEvent(o);
|
|
1756
|
+
if (ev) events.push(ev);
|
|
1757
|
+
}
|
|
1758
|
+
return { events, rest };
|
|
1759
|
+
}
|
|
1760
|
+
|
|
1761
|
+
// src/runner.ts
|
|
1762
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
1763
|
+
import { mkdtempSync as mkdtempSync2, readdirSync as readdirSync2, rmSync as rmSync4, statSync } from "node:fs";
|
|
1764
|
+
import { rm, stat } from "node:fs/promises";
|
|
1765
|
+
import { StringDecoder as StringDecoder2 } from "node:string_decoder";
|
|
1766
|
+
import { tmpdir as tmpdir2 } from "node:os";
|
|
1767
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
1768
|
+
import path7 from "node:path";
|
|
1769
|
+
|
|
1770
|
+
// src/logtail.ts
|
|
1771
|
+
import { open } from "node:fs/promises";
|
|
1772
|
+
import { StringDecoder } from "node:string_decoder";
|
|
1773
|
+
var READ_BYTES = 1024 * 1024;
|
|
1774
|
+
var LogTail = class {
|
|
1775
|
+
constructor(path8, maxBytes = MAX_RAW_OUTPUT_BYTES) {
|
|
1776
|
+
this.path = path8;
|
|
1777
|
+
this.maxBytes = maxBytes;
|
|
1778
|
+
}
|
|
1779
|
+
path;
|
|
1780
|
+
maxBytes;
|
|
1781
|
+
offset = 0;
|
|
1782
|
+
carry = "";
|
|
1783
|
+
decoder = new StringDecoder("utf8");
|
|
1784
|
+
bytesRead = 0;
|
|
1785
|
+
pending = Promise.resolve();
|
|
1786
|
+
/** Reads a fixed-size block; the file's size never becomes an allocation size. */
|
|
1787
|
+
async append() {
|
|
1788
|
+
let handle;
|
|
1789
|
+
try {
|
|
1790
|
+
handle = await open(this.path, "r");
|
|
1791
|
+
} catch {
|
|
1792
|
+
return false;
|
|
1793
|
+
}
|
|
1794
|
+
try {
|
|
1795
|
+
const { size } = await handle.stat();
|
|
1796
|
+
if (size < this.offset) {
|
|
1797
|
+
this.offset = 0;
|
|
1798
|
+
this.carry = "";
|
|
1799
|
+
this.decoder = new StringDecoder("utf8");
|
|
1800
|
+
}
|
|
1801
|
+
if (size <= this.offset) return false;
|
|
1802
|
+
if (this.bytesRead + size - this.offset > this.maxBytes)
|
|
1803
|
+
throw new OutputLimitError("run log", this.maxBytes);
|
|
1804
|
+
const length = Math.min(size - this.offset, READ_BYTES);
|
|
1805
|
+
const buf = Buffer.allocUnsafe(length);
|
|
1806
|
+
const { bytesRead } = await handle.read(buf, 0, length, this.offset);
|
|
1807
|
+
this.offset += bytesRead;
|
|
1808
|
+
this.bytesRead += bytesRead;
|
|
1809
|
+
this.carry += this.decoder.write(buf.subarray(0, bytesRead));
|
|
1810
|
+
return bytesRead > 0 && this.offset < size;
|
|
1811
|
+
} catch (error) {
|
|
1812
|
+
if (error instanceof OutputLimitError) throw error;
|
|
1813
|
+
return false;
|
|
1814
|
+
} finally {
|
|
1815
|
+
await handle.close().catch(() => {
|
|
1816
|
+
});
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
serial(fn) {
|
|
1820
|
+
const result = this.pending.then(fn);
|
|
1821
|
+
this.pending = result.catch(() => {
|
|
1822
|
+
});
|
|
1823
|
+
return result;
|
|
1824
|
+
}
|
|
1825
|
+
/** Complete lines appended since the previous call. */
|
|
1826
|
+
async read() {
|
|
1827
|
+
return this.serial(async () => {
|
|
1828
|
+
await this.append();
|
|
1829
|
+
const cut = this.carry.lastIndexOf("\n");
|
|
1830
|
+
if (cut === -1) return "";
|
|
1831
|
+
const out = this.carry.slice(0, cut + 1);
|
|
1832
|
+
this.carry = this.carry.slice(cut + 1);
|
|
1833
|
+
return out;
|
|
1834
|
+
});
|
|
1835
|
+
}
|
|
1836
|
+
/** Everything still unread, including a final line with no newline. */
|
|
1837
|
+
async flush() {
|
|
1838
|
+
return this.serial(async () => {
|
|
1839
|
+
while (await this.append()) {
|
|
1840
|
+
}
|
|
1841
|
+
const out = this.carry;
|
|
1842
|
+
this.carry = "";
|
|
1843
|
+
return out;
|
|
1844
|
+
});
|
|
1845
|
+
}
|
|
1846
|
+
};
|
|
1847
|
+
|
|
1848
|
+
// src/runner.ts
|
|
1849
|
+
var MAX_STDERR_BYTES = 1024 * 1024;
|
|
1850
|
+
var MAX_PARTIAL_OUTPUT_CHARS = 1024 * 1024;
|
|
1851
|
+
var MAX_TRAILING_LOG_CHARS = 1024 * 1024;
|
|
1852
|
+
function appendTail(buf, chunk, max) {
|
|
1853
|
+
const next = buf + chunk;
|
|
1854
|
+
if (next.length <= max + max / 4) return { text: next, dropped: 0 };
|
|
1855
|
+
return { text: next.slice(next.length - max), dropped: next.length - max };
|
|
1856
|
+
}
|
|
1857
|
+
var MAX_PROMPT_BYTES = 128 * 1024 - 1;
|
|
1858
|
+
var spawnDetached = (file, args, opts) => {
|
|
1859
|
+
const child = spawn2(file, args, {
|
|
1860
|
+
cwd: opts.cwd,
|
|
1861
|
+
detached: true,
|
|
1862
|
+
...opts.env ? { env: { ...process.env, ...opts.env } } : {}
|
|
1863
|
+
});
|
|
1864
|
+
child.stdin?.on("error", () => {
|
|
1865
|
+
});
|
|
1866
|
+
child.stdin?.end();
|
|
1867
|
+
let out = "";
|
|
1868
|
+
let err = "";
|
|
1869
|
+
let outBytes = 0;
|
|
1870
|
+
let errBytes = 0;
|
|
1871
|
+
let outputLimit;
|
|
1872
|
+
const stopAtLimit = (source, limitBytes) => {
|
|
1873
|
+
outputLimit ??= { source, limitBytes };
|
|
1874
|
+
if (child.pid === void 0) return;
|
|
1875
|
+
try {
|
|
1876
|
+
process.kill(-child.pid, "SIGTERM");
|
|
1877
|
+
} catch {
|
|
1878
|
+
child.kill("SIGTERM");
|
|
1879
|
+
}
|
|
1880
|
+
};
|
|
1881
|
+
const outDecoder = new StringDecoder2("utf8");
|
|
1882
|
+
const errDecoder = new StringDecoder2("utf8");
|
|
1883
|
+
child.stdout?.on("data", (d) => {
|
|
1884
|
+
if (outputLimit) return;
|
|
1885
|
+
const room = MAX_RAW_OUTPUT_BYTES - outBytes;
|
|
1886
|
+
out += outDecoder.write(d.subarray(0, room));
|
|
1887
|
+
outBytes += Math.min(d.length, room);
|
|
1888
|
+
if (d.length > room) stopAtLimit("stdout", MAX_RAW_OUTPUT_BYTES);
|
|
1889
|
+
});
|
|
1890
|
+
child.stderr?.on("data", (d) => {
|
|
1891
|
+
if (outputLimit) return;
|
|
1892
|
+
const room = MAX_STDERR_BYTES - errBytes;
|
|
1893
|
+
err += errDecoder.write(d.subarray(0, room));
|
|
1894
|
+
errBytes += Math.min(d.length, room);
|
|
1895
|
+
if (d.length > room) stopAtLimit("stderr", MAX_STDERR_BYTES);
|
|
1896
|
+
});
|
|
1897
|
+
const flush = () => {
|
|
1898
|
+
out += outDecoder.end();
|
|
1899
|
+
err += errDecoder.end();
|
|
1900
|
+
};
|
|
1901
|
+
const done = new Promise((resolve2) => {
|
|
1902
|
+
let exitCode = null;
|
|
1903
|
+
let closeFallback;
|
|
1904
|
+
child.on("exit", (code) => {
|
|
1905
|
+
exitCode = code;
|
|
1906
|
+
if (child.pid !== void 0) {
|
|
1907
|
+
try {
|
|
1908
|
+
process.kill(-child.pid, "SIGKILL");
|
|
1909
|
+
} catch {
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
closeFallback = setTimeout(() => {
|
|
1913
|
+
flush();
|
|
1914
|
+
resolve2({ code: exitCode });
|
|
1915
|
+
}, 2e3);
|
|
1916
|
+
closeFallback.unref();
|
|
1917
|
+
});
|
|
1918
|
+
child.on("close", (code) => {
|
|
1919
|
+
if (closeFallback) clearTimeout(closeFallback);
|
|
1920
|
+
flush();
|
|
1921
|
+
resolve2({ code: code ?? exitCode });
|
|
1922
|
+
});
|
|
1923
|
+
child.on("error", (e) => {
|
|
1924
|
+
flush();
|
|
1925
|
+
resolve2({ code: null, error: e });
|
|
1926
|
+
});
|
|
1927
|
+
});
|
|
1928
|
+
return {
|
|
1929
|
+
stdout: () => out,
|
|
1930
|
+
stderr: () => err,
|
|
1931
|
+
outputLimit: () => outputLimit,
|
|
1932
|
+
wait: () => done,
|
|
1933
|
+
kill: (signal) => {
|
|
1934
|
+
if (child.pid === void 0) return;
|
|
1935
|
+
try {
|
|
1936
|
+
process.kill(-child.pid, signal);
|
|
1937
|
+
} catch (err2) {
|
|
1938
|
+
if (err2.code === "ESRCH") return;
|
|
1939
|
+
try {
|
|
1940
|
+
child.kill(signal);
|
|
1941
|
+
} catch {
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
};
|
|
1946
|
+
};
|
|
1947
|
+
var LOG_DIR_PREFIX = `${SERVER_NAME}-`;
|
|
1948
|
+
var LOG_DIR_PATTERN = new RegExp(`^(?:${SERVER_NAME}|${LEGACY_SERVER_NAME})-(\\d+)-`);
|
|
1949
|
+
var logDir;
|
|
1950
|
+
function makeLogPath() {
|
|
1951
|
+
logDir ??= mkdtempSync2(path7.join(tmpdir2(), `${LOG_DIR_PREFIX}${process.pid}-`));
|
|
1952
|
+
return path7.join(logDir, `${randomUUID3()}.log`);
|
|
1953
|
+
}
|
|
1954
|
+
function removeLogDir() {
|
|
1955
|
+
if (logDir) rmSync4(logDir, { recursive: true, force: true });
|
|
1956
|
+
logDir = void 0;
|
|
1957
|
+
}
|
|
1958
|
+
function sweepStaleLogs(dir = tmpdir2()) {
|
|
1959
|
+
let names;
|
|
1960
|
+
try {
|
|
1961
|
+
names = readdirSync2(dir);
|
|
1962
|
+
} catch {
|
|
1963
|
+
return;
|
|
1964
|
+
}
|
|
1965
|
+
for (const name of names) {
|
|
1966
|
+
const pid = LOG_DIR_PATTERN.exec(name)?.[1];
|
|
1967
|
+
if (!pid || Number(pid) === process.pid || isRunning(Number(pid))) continue;
|
|
1968
|
+
const full = path7.join(dir, name);
|
|
1969
|
+
try {
|
|
1970
|
+
if (statSync(full).uid !== process.getuid?.()) continue;
|
|
1971
|
+
rmSync4(full, { recursive: true, force: true });
|
|
1972
|
+
} catch {
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
function isRunning(pid) {
|
|
1977
|
+
try {
|
|
1978
|
+
process.kill(pid, 0);
|
|
1979
|
+
return true;
|
|
1980
|
+
} catch (err) {
|
|
1981
|
+
return err.code === "EPERM";
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1984
|
+
function assertPromptIsNotFlagLike(prompt) {
|
|
1985
|
+
if (/^\s*-/.test(prompt)) {
|
|
1986
|
+
throw new InvalidRequestError(
|
|
1987
|
+
"Prompt starts with '-', which agy's argument parser would read as a flag. Rephrase it, or quote the leading dash."
|
|
1988
|
+
);
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
function assertPromptIsSendable(prompt) {
|
|
1992
|
+
assertPromptIsNotFlagLike(prompt);
|
|
1993
|
+
if (prompt.includes("\0")) {
|
|
1994
|
+
throw new InvalidRequestError(
|
|
1995
|
+
"Prompt contains a NUL byte, which cannot be passed to agy as a command-line argument."
|
|
1996
|
+
);
|
|
1997
|
+
}
|
|
1998
|
+
const bytes = Buffer.byteLength(prompt, "utf8");
|
|
1999
|
+
if (bytes > MAX_PROMPT_BYTES) {
|
|
2000
|
+
throw new InvalidRequestError(
|
|
2001
|
+
`Prompt is ${bytes} bytes; agy takes it as one command-line argument, limited to ${MAX_PROMPT_BYTES} bytes. Pass file paths instead of inlining the content.`
|
|
2002
|
+
);
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
async function spawnFailure(error, cwd, agyPath) {
|
|
2006
|
+
if (error.code !== "ENOENT" && error.code !== "ENOTDIR") {
|
|
2007
|
+
return new AgyFailure("agy_error", `agy failed: ${error.message}`);
|
|
2008
|
+
}
|
|
2009
|
+
const dir = await stat(cwd).catch(() => void 0);
|
|
2010
|
+
if (!dir) return new InvalidRequestError(`Working directory "${cwd}" does not exist.`);
|
|
2011
|
+
if (!dir.isDirectory())
|
|
2012
|
+
return new InvalidRequestError(`Working directory "${cwd}" is not a directory.`);
|
|
2013
|
+
return new AgyFailure(
|
|
2014
|
+
"not_installed",
|
|
2015
|
+
`agy CLI not found at "${agyPath}". Install the Antigravity CLI (https://antigravity.google/docs/cli-getting-started) or set AGY_PATH.`
|
|
2016
|
+
);
|
|
2017
|
+
}
|
|
2018
|
+
function report(onProgress, p) {
|
|
2019
|
+
try {
|
|
2020
|
+
onProgress?.(p);
|
|
2021
|
+
} catch {
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
function permissionArgs(req, cfg, caps) {
|
|
2025
|
+
const args = [];
|
|
2026
|
+
const push = (flag, ...values) => {
|
|
2027
|
+
if (caps.has(flag)) args.push(flag, ...values);
|
|
2028
|
+
};
|
|
2029
|
+
const require2 = (flag, ...values) => {
|
|
2030
|
+
if (!caps.has(flag)) {
|
|
2031
|
+
throw new AgyFailure(
|
|
2032
|
+
"agy_error",
|
|
2033
|
+
`agy ${caps.version} does not support ${flag}, which this call needs in order to restrict the run. Refusing rather than running with more authority than requested. Upgrade the Antigravity CLI, or set AGY_PATH to a build that supports it.`
|
|
2034
|
+
);
|
|
2035
|
+
}
|
|
2036
|
+
args.push(flag, ...values);
|
|
2037
|
+
};
|
|
2038
|
+
if (cfg.skipPermissions) push("--dangerously-skip-permissions");
|
|
2039
|
+
if (req.sandbox ?? cfg.sandbox) require2("--sandbox");
|
|
2040
|
+
if (req.mode === "plan") require2("--mode", req.mode);
|
|
2041
|
+
else if (req.mode) push("--mode", req.mode);
|
|
2042
|
+
if (!req.slashCommands) push("--disable-slash-commands");
|
|
2043
|
+
return args;
|
|
2044
|
+
}
|
|
2045
|
+
function buildArgs(req, cfg, opts) {
|
|
2046
|
+
const { caps, logPath } = opts;
|
|
2047
|
+
const args = permissionArgs(req, cfg, caps);
|
|
2048
|
+
const push = (flag, ...values) => {
|
|
2049
|
+
if (caps.has(flag)) args.push(flag, ...values);
|
|
2050
|
+
};
|
|
2051
|
+
args.push("--add-dir", req.cwd);
|
|
2052
|
+
for (const dir of req.dirs ?? []) if (dir !== req.cwd) args.push("--add-dir", dir);
|
|
2053
|
+
args.push("--log-file", logPath);
|
|
2054
|
+
if (req.conversationId) args.push("--conversation", req.conversationId);
|
|
2055
|
+
if (req.model) args.push("--model", req.model);
|
|
2056
|
+
if (req.effort) push("--effort", req.effort);
|
|
2057
|
+
if (req.jsonSchema) push("--json-schema", req.jsonSchema);
|
|
2058
|
+
if (opts.outputFormat) push("--output-format", opts.outputFormat);
|
|
2059
|
+
args.push("--print-timeout", `${req.timeoutSec}s`, "-p", req.prompt);
|
|
2060
|
+
return args;
|
|
2061
|
+
}
|
|
2062
|
+
function truncate(text2, max) {
|
|
2063
|
+
if (text2.length <= max) return { text: text2 };
|
|
2064
|
+
const head = Math.floor(max * 0.6);
|
|
2065
|
+
const tail = max - head;
|
|
2066
|
+
const dropped = text2.length - max;
|
|
2067
|
+
return {
|
|
2068
|
+
text: `${text2.slice(0, head)}
|
|
2069
|
+
|
|
2070
|
+
[${SERVER_NAME}: ${dropped} chars omitted here \u2014 output was ${text2.length} chars, limit ${max}. Ask a narrower question or raise AGY_MAX_OUTPUT_CHARS. The end of the output follows.]
|
|
2071
|
+
|
|
2072
|
+
${text2.slice(-tail)}`,
|
|
2073
|
+
from: text2.length
|
|
2074
|
+
};
|
|
2075
|
+
}
|
|
2076
|
+
function clipPartialOutput(text2, scrub = false) {
|
|
2077
|
+
if (scrub) text2 = redact(text2).text;
|
|
2078
|
+
if (text2.length <= MAX_PARTIAL_OUTPUT_CHARS) return text2;
|
|
2079
|
+
const half = MAX_PARTIAL_OUTPUT_CHARS / 2;
|
|
2080
|
+
return `${text2.slice(0, half)}
|
|
2081
|
+
|
|
2082
|
+
[${SERVER_NAME}: partial output clipped; ${text2.length - MAX_PARTIAL_OUTPUT_CHARS} characters omitted.]
|
|
2083
|
+
|
|
2084
|
+
${text2.slice(-half)}`;
|
|
2085
|
+
}
|
|
2086
|
+
function outputLimitOf(proc) {
|
|
2087
|
+
if (proc.outputLimit) return proc.outputLimit();
|
|
2088
|
+
if ((proc.stdoutDropped?.() ?? 0) > 0 || Buffer.byteLength(proc.stdout()) > MAX_RAW_OUTPUT_BYTES)
|
|
2089
|
+
return { source: "stdout", limitBytes: MAX_RAW_OUTPUT_BYTES };
|
|
2090
|
+
if (Buffer.byteLength(proc.stderr()) > MAX_STDERR_BYTES)
|
|
2091
|
+
return { source: "stderr", limitBytes: MAX_STDERR_BYTES };
|
|
2092
|
+
return void 0;
|
|
2093
|
+
}
|
|
2094
|
+
function answerOf(envelope, stdout, format, streamed) {
|
|
2095
|
+
if (envelope) return envelope.response.trim();
|
|
2096
|
+
if (format === "stream-json") return streamed.trim();
|
|
2097
|
+
return stdout.trim();
|
|
2098
|
+
}
|
|
2099
|
+
var delay = (ms) => new Promise((r) => setTimeout(r, ms).unref?.());
|
|
2100
|
+
function outputFormatFor(req, caps) {
|
|
2101
|
+
if (!caps.has("--output-format")) return void 0;
|
|
2102
|
+
return req.onProgress ? "stream-json" : "json";
|
|
2103
|
+
}
|
|
2104
|
+
function commandFor(confineTo, agyPath, args, confinement) {
|
|
2105
|
+
if (!confineTo) return { file: agyPath, args };
|
|
2106
|
+
if (!confinement?.available) {
|
|
2107
|
+
throw new AgyFailure(
|
|
2108
|
+
"agy_error",
|
|
2109
|
+
`This run asked to be confined against writes, but confinement is unavailable${confinement?.reason ? ` (${confinement.reason})` : ""}. Refusing rather than running with more authority than requested.`
|
|
2110
|
+
);
|
|
2111
|
+
}
|
|
2112
|
+
return confinement.wrap(agyPath, args, confineTo);
|
|
2113
|
+
}
|
|
2114
|
+
async function runAgy(req, cfg, caps, deps = {}) {
|
|
2115
|
+
assertPromptIsSendable(req.prompt);
|
|
2116
|
+
if (req.signal?.aborted) throw new Error("agy run cancelled by client.");
|
|
2117
|
+
if (caps.notInstalled) {
|
|
2118
|
+
throw new AgyFailure(
|
|
2119
|
+
"not_installed",
|
|
2120
|
+
`agy CLI not found at "${cfg.agyPath}" when this server started. Install the Antigravity CLI (https://antigravity.google/docs/cli-getting-started) or set AGY_PATH, then restart the MCP server.`
|
|
2121
|
+
);
|
|
2122
|
+
}
|
|
2123
|
+
const spawnAgy = deps.spawn ?? spawnDetached;
|
|
2124
|
+
const pollMs = deps.timing?.pollMs ?? 1e3;
|
|
2125
|
+
const graceMs = deps.timing?.graceMs ?? 15e3;
|
|
2126
|
+
const killGraceMs = deps.timing?.killGraceMs ?? 5e3;
|
|
2127
|
+
const logPath = makeLogPath();
|
|
2128
|
+
const outputFormat = outputFormatFor(req, caps);
|
|
2129
|
+
const tail = new LogTail(logPath);
|
|
2130
|
+
const reapMs = killGraceMs + graceMs;
|
|
2131
|
+
let timedOut = false;
|
|
2132
|
+
let trailingLog = "";
|
|
2133
|
+
let child;
|
|
2134
|
+
let untrack;
|
|
2135
|
+
let exited = false;
|
|
2136
|
+
let streamedText = "";
|
|
2137
|
+
let streamedConversationId;
|
|
2138
|
+
let outputFailure;
|
|
2139
|
+
const command = commandFor(
|
|
2140
|
+
req.confineTo,
|
|
2141
|
+
cfg.agyPath,
|
|
2142
|
+
buildArgs(req, cfg, { logPath, caps, outputFormat }),
|
|
2143
|
+
deps.confinement
|
|
2144
|
+
);
|
|
2145
|
+
const finished = await new Promise(
|
|
2146
|
+
(resolve2, reject) => {
|
|
2147
|
+
child = spawnAgy(command.file, command.args, {
|
|
2148
|
+
cwd: req.cwd,
|
|
2149
|
+
...req.env ? { env: req.env } : {}
|
|
2150
|
+
});
|
|
2151
|
+
const proc = child;
|
|
2152
|
+
untrack = deps.track?.(proc);
|
|
2153
|
+
let settled = false;
|
|
2154
|
+
let polling = false;
|
|
2155
|
+
let streamCursor = 0;
|
|
2156
|
+
let streamRest = "";
|
|
2157
|
+
let escalate;
|
|
2158
|
+
const timers = [];
|
|
2159
|
+
const killChild = () => {
|
|
2160
|
+
proc.kill("SIGTERM");
|
|
2161
|
+
escalate ??= setTimeout(() => proc.kill("SIGKILL"), killGraceMs);
|
|
2162
|
+
escalate.unref?.();
|
|
2163
|
+
};
|
|
2164
|
+
const finish = (fn) => {
|
|
2165
|
+
if (settled) return;
|
|
2166
|
+
settled = true;
|
|
2167
|
+
clearInterval(poller);
|
|
2168
|
+
for (const t of timers) clearTimeout(t);
|
|
2169
|
+
req.signal?.removeEventListener("abort", onAbort);
|
|
2170
|
+
fn();
|
|
2171
|
+
};
|
|
2172
|
+
const drainProgress = () => {
|
|
2173
|
+
if (!req.onProgress || outputFormat !== "stream-json") return;
|
|
2174
|
+
const all = proc.stdout();
|
|
2175
|
+
const dropped = proc.stdoutDropped?.() ?? 0;
|
|
2176
|
+
if (dropped + all.length <= streamCursor) return;
|
|
2177
|
+
const from = streamCursor - dropped;
|
|
2178
|
+
if (from < 0) streamRest = "";
|
|
2179
|
+
const chunk = streamRest + all.slice(Math.max(0, from));
|
|
2180
|
+
streamCursor = dropped + all.length;
|
|
2181
|
+
const { events, rest } = parseStreamEvents(chunk);
|
|
2182
|
+
streamRest = rest;
|
|
2183
|
+
for (const ev of events) {
|
|
2184
|
+
if (ev.kind === "init") {
|
|
2185
|
+
streamedConversationId = ev.conversationId ?? streamedConversationId;
|
|
2186
|
+
continue;
|
|
2187
|
+
}
|
|
2188
|
+
if (ev.kind !== "step") continue;
|
|
2189
|
+
streamedText += ev.textDelta;
|
|
2190
|
+
report(req.onProgress, {
|
|
2191
|
+
text: streamedText,
|
|
2192
|
+
stepIndex: ev.stepIndex,
|
|
2193
|
+
stepType: ev.stepType,
|
|
2194
|
+
tokens: ev.usage?.totalTokens ?? 0
|
|
2195
|
+
});
|
|
2196
|
+
}
|
|
2197
|
+
};
|
|
2198
|
+
const stopForOutputLimit = (failure) => {
|
|
2199
|
+
outputFailure ??= failure;
|
|
2200
|
+
drainProgress();
|
|
2201
|
+
if (!exited) killChild();
|
|
2202
|
+
finish(() => resolve2({ stdout: proc.stdout(), stderr: proc.stderr(), code: null }));
|
|
2203
|
+
};
|
|
2204
|
+
const poller = setInterval(async () => {
|
|
2205
|
+
if (polling || settled) return;
|
|
2206
|
+
polling = true;
|
|
2207
|
+
try {
|
|
2208
|
+
const limit = outputLimitOf(proc);
|
|
2209
|
+
if (limit) {
|
|
2210
|
+
stopForOutputLimit(new OutputLimitError(limit.source, limit.limitBytes, req.model));
|
|
2211
|
+
return;
|
|
2212
|
+
}
|
|
2213
|
+
drainProgress();
|
|
2214
|
+
const appended = await tail.read();
|
|
2215
|
+
if (appended)
|
|
2216
|
+
trailingLog = appendTail(trailingLog, appended, MAX_TRAILING_LOG_CHARS).text;
|
|
2217
|
+
if (settled) return;
|
|
2218
|
+
} catch (error) {
|
|
2219
|
+
if (error instanceof OutputLimitError) stopForOutputLimit(error);
|
|
2220
|
+
} finally {
|
|
2221
|
+
polling = false;
|
|
2222
|
+
}
|
|
2223
|
+
}, pollMs);
|
|
2224
|
+
timers.push(
|
|
2225
|
+
setTimeout(
|
|
2226
|
+
() => {
|
|
2227
|
+
killChild();
|
|
2228
|
+
timedOut = true;
|
|
2229
|
+
timers.push(
|
|
2230
|
+
setTimeout(() => {
|
|
2231
|
+
finish(() => resolve2({ stdout: proc.stdout(), stderr: proc.stderr(), code: 0 }));
|
|
2232
|
+
}, reapMs)
|
|
2233
|
+
);
|
|
2234
|
+
},
|
|
2235
|
+
req.timeoutSec * 1e3 + graceMs
|
|
2236
|
+
)
|
|
2237
|
+
);
|
|
2238
|
+
const onAbort = () => {
|
|
2239
|
+
killChild();
|
|
2240
|
+
drainProgress();
|
|
2241
|
+
const envelope2 = outputFormat ? parseEnvelope(proc.stdout()) : null;
|
|
2242
|
+
const partial = answerOf(envelope2, proc.stdout(), outputFormat, streamedText);
|
|
2243
|
+
finish(
|
|
2244
|
+
() => reject(
|
|
2245
|
+
Object.assign(new AgyFailure("agy_error", "agy run cancelled by client.", req.model), {
|
|
2246
|
+
usageKnown: envelope2?.usageKnown ?? false,
|
|
2247
|
+
...envelope2 ? { usage: envelope2.usage, numTurns: envelope2.numTurns } : {},
|
|
2248
|
+
conversationId: envelope2?.conversationId ?? streamedConversationId ?? req.conversationId,
|
|
2249
|
+
finishedReason: "interrupted",
|
|
2250
|
+
...partial ? { partialOutput: clipPartialOutput(partial, cfg.redact) } : {}
|
|
2251
|
+
})
|
|
2252
|
+
)
|
|
2253
|
+
);
|
|
2254
|
+
};
|
|
2255
|
+
if (req.signal?.aborted) {
|
|
2256
|
+
onAbort();
|
|
2257
|
+
return;
|
|
2258
|
+
}
|
|
2259
|
+
req.signal?.addEventListener("abort", onAbort, { once: true });
|
|
2260
|
+
void proc.wait().then(async ({ code, error }) => {
|
|
2261
|
+
exited = true;
|
|
2262
|
+
if (escalate) clearTimeout(escalate);
|
|
2263
|
+
if (settled) return;
|
|
2264
|
+
const limit = outputLimitOf(proc);
|
|
2265
|
+
if (limit) {
|
|
2266
|
+
stopForOutputLimit(new OutputLimitError(limit.source, limit.limitBytes, req.model));
|
|
2267
|
+
return;
|
|
2268
|
+
}
|
|
2269
|
+
drainProgress();
|
|
2270
|
+
if (error) {
|
|
2271
|
+
const failure = await spawnFailure(error, req.cwd, cfg.agyPath);
|
|
2272
|
+
finish(() => reject(failure));
|
|
2273
|
+
return;
|
|
2274
|
+
}
|
|
2275
|
+
finish(() => resolve2({ stdout: proc.stdout(), stderr: proc.stderr(), code }));
|
|
2276
|
+
});
|
|
2277
|
+
}
|
|
2278
|
+
).finally(async () => {
|
|
2279
|
+
if (child && !exited) await Promise.race([child.wait(), delay(reapMs)]);
|
|
2280
|
+
untrack?.();
|
|
2281
|
+
try {
|
|
2282
|
+
trailingLog = appendTail(trailingLog, await tail.flush(), MAX_TRAILING_LOG_CHARS).text;
|
|
2283
|
+
} catch (error) {
|
|
2284
|
+
if (error instanceof OutputLimitError) outputFailure ??= error;
|
|
2285
|
+
} finally {
|
|
2286
|
+
await rm(logPath, { force: true }).catch(() => {
|
|
2287
|
+
});
|
|
2288
|
+
}
|
|
2289
|
+
});
|
|
2290
|
+
const envelope = outputFormat ? parseEnvelope(finished.stdout) : null;
|
|
2291
|
+
const answer = answerOf(envelope, finished.stdout, outputFormat, streamedText);
|
|
2292
|
+
const spent = envelope?.usage;
|
|
2293
|
+
const details = parseAgyError(finished.stderr);
|
|
2294
|
+
const conversationId = envelope?.conversationId ?? streamedConversationId;
|
|
2295
|
+
if (outputFailure) {
|
|
2296
|
+
throw Object.assign(outputFailure, {
|
|
2297
|
+
...spent ? { usage: spent } : {},
|
|
2298
|
+
...details ? { details } : {},
|
|
2299
|
+
usageKnown: envelope?.usageKnown ?? false,
|
|
2300
|
+
...answer ? { partialOutput: clipPartialOutput(answer, cfg.redact) } : {},
|
|
2301
|
+
...conversationId || req.conversationId ? { conversationId: conversationId ?? req.conversationId } : {},
|
|
2302
|
+
...envelope ? { numTurns: envelope.numTurns, deniedActions: envelope.deniedActions } : {}
|
|
2303
|
+
});
|
|
2304
|
+
}
|
|
2305
|
+
const finishedReason = envelope?.finishedReason ?? (/^\[agy\] print timeout after\b/im.test(finished.stderr) ? "print_timeout" : void 0);
|
|
2306
|
+
if (finishedReason === "print_timeout") timedOut = true;
|
|
2307
|
+
if (!timedOut) {
|
|
2308
|
+
const failure = classifyRun({
|
|
2309
|
+
envelope,
|
|
2310
|
+
exitCode: finished.code,
|
|
2311
|
+
stderr: finished.stderr
|
|
2312
|
+
});
|
|
2313
|
+
if (failure) {
|
|
2314
|
+
const quota = failure.kind === "quota" ? detectQuota(trailingLog) : null;
|
|
2315
|
+
throw Object.assign(
|
|
2316
|
+
quota ? new QuotaError(req.model, quota) : new AgyFailure(failure.kind, failure.message, req.model),
|
|
2317
|
+
{
|
|
2318
|
+
...spent ? { usage: spent } : {},
|
|
2319
|
+
...details ? { details } : {},
|
|
2320
|
+
usageKnown: envelope?.usageKnown ?? false,
|
|
2321
|
+
...answer ? { partialOutput: answer } : {},
|
|
2322
|
+
...conversationId ? { conversationId } : {},
|
|
2323
|
+
...finishedReason ? { finishedReason } : {},
|
|
2324
|
+
...envelope ? { numTurns: envelope.numTurns, deniedActions: envelope.deniedActions } : {},
|
|
2325
|
+
...envelope?.structuredOutput !== void 0 ? { structuredOutput: envelope.structuredOutput } : {}
|
|
2326
|
+
}
|
|
2327
|
+
);
|
|
2328
|
+
}
|
|
2329
|
+
if (outputFormat && !envelope) {
|
|
2330
|
+
throw Object.assign(
|
|
2331
|
+
new AgyFailure("agy_error", "agy exited without a complete result envelope.", req.model),
|
|
2332
|
+
{
|
|
2333
|
+
...answer ? { partialOutput: answer } : {},
|
|
2334
|
+
...conversationId ? { conversationId } : {},
|
|
2335
|
+
finishedReason: "missing_result",
|
|
2336
|
+
usageKnown: false
|
|
2337
|
+
}
|
|
2338
|
+
);
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
return {
|
|
2342
|
+
output: answer,
|
|
2343
|
+
...conversationId ? { conversationId } : {},
|
|
2344
|
+
deniedActions: envelope?.deniedActions ?? [],
|
|
2345
|
+
usage: envelope?.usage ?? EMPTY_USAGE,
|
|
2346
|
+
usageKnown: envelope?.usageKnown ?? false,
|
|
2347
|
+
...envelope && envelope.structuredOutput !== void 0 ? { structuredOutput: envelope.structuredOutput } : {},
|
|
2348
|
+
numTurns: envelope?.numTurns ?? 0,
|
|
2349
|
+
timedOut,
|
|
2350
|
+
...finishedReason ? { finishedReason } : {}
|
|
2351
|
+
};
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2354
|
+
// src/usage.ts
|
|
2355
|
+
var BudgetUsageUnknownError = class extends Error {
|
|
2356
|
+
constructor() {
|
|
2357
|
+
super(
|
|
2358
|
+
"The previous run did not report complete token usage, so the configured token budget cannot be verified. No further work was dispatched; inspect agy's usage before explicitly starting a new budget period."
|
|
2359
|
+
);
|
|
2360
|
+
this.name = "BudgetUsageUnknownError";
|
|
2361
|
+
}
|
|
2362
|
+
};
|
|
2363
|
+
var BudgetExceededError = class extends Error {
|
|
2364
|
+
constructor(spent, limit) {
|
|
2365
|
+
super(
|
|
2366
|
+
`Token budget exhausted: ${spent} of ${limit} tokens used by this server since it started. Raise AGY_BUDGET_TOKENS or restart the server to reset the count.`
|
|
2367
|
+
);
|
|
2368
|
+
this.spent = spent;
|
|
2369
|
+
this.limit = limit;
|
|
2370
|
+
this.name = "BudgetExceededError";
|
|
2371
|
+
}
|
|
2372
|
+
spent;
|
|
2373
|
+
limit;
|
|
2374
|
+
};
|
|
2375
|
+
var UsageLedger = class {
|
|
2376
|
+
constructor(budgetTokens) {
|
|
2377
|
+
this.budgetTokens = budgetTokens;
|
|
2378
|
+
}
|
|
2379
|
+
budgetTokens;
|
|
2380
|
+
byModel = /* @__PURE__ */ new Map();
|
|
2381
|
+
record(model, usage, known = true) {
|
|
2382
|
+
const key = model ?? "agy default";
|
|
2383
|
+
const row = this.byModel.get(key) ?? {
|
|
2384
|
+
model: key,
|
|
2385
|
+
runs: 0,
|
|
2386
|
+
unknownRuns: 0,
|
|
2387
|
+
inputTokens: 0,
|
|
2388
|
+
outputTokens: 0,
|
|
2389
|
+
thinkingTokens: 0,
|
|
2390
|
+
cacheReadTokens: 0,
|
|
2391
|
+
totalTokens: 0
|
|
2392
|
+
};
|
|
2393
|
+
row.runs++;
|
|
2394
|
+
if (!known) row.unknownRuns++;
|
|
2395
|
+
row.inputTokens += usage.inputTokens;
|
|
2396
|
+
row.outputTokens += usage.outputTokens;
|
|
2397
|
+
row.thinkingTokens += usage.thinkingTokens;
|
|
2398
|
+
row.cacheReadTokens += usage.cacheReadTokens;
|
|
2399
|
+
row.totalTokens += usage.totalTokens;
|
|
2400
|
+
this.byModel.set(key, row);
|
|
2401
|
+
}
|
|
2402
|
+
get spent() {
|
|
2403
|
+
let sum = 0;
|
|
2404
|
+
for (const row of this.byModel.values()) sum += row.totalTokens;
|
|
2405
|
+
return sum;
|
|
2406
|
+
}
|
|
2407
|
+
rows() {
|
|
2408
|
+
return [...this.byModel.values()].sort((a, b) => b.totalTokens - a.totalTokens);
|
|
2409
|
+
}
|
|
2410
|
+
/** Throws before a run starts once the budget is gone. */
|
|
2411
|
+
assertWithinBudget() {
|
|
2412
|
+
if (this.budgetTokens !== void 0 && this.rows().some((row) => row.unknownRuns > 0)) {
|
|
2413
|
+
throw new BudgetUsageUnknownError();
|
|
2414
|
+
}
|
|
2415
|
+
if (this.budgetTokens !== void 0 && this.spent >= this.budgetTokens) {
|
|
2416
|
+
throw new BudgetExceededError(this.spent, this.budgetTokens);
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
2419
|
+
get budget() {
|
|
2420
|
+
return this.budgetTokens;
|
|
2421
|
+
}
|
|
2422
|
+
};
|
|
2423
|
+
|
|
2424
|
+
// src/warm.ts
|
|
2425
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
2426
|
+
import { resolve as resolvePath } from "node:path";
|
|
2427
|
+
import { StringDecoder as StringDecoder3 } from "node:string_decoder";
|
|
2428
|
+
function turnMessage(prompt) {
|
|
2429
|
+
return `${JSON.stringify({ event: "user", message: { content: prompt } })}
|
|
2430
|
+
`;
|
|
2431
|
+
}
|
|
2432
|
+
var spawnSessionProcess = (file, args, opts) => {
|
|
2433
|
+
const child = spawn3(file, args, {
|
|
2434
|
+
cwd: opts.cwd,
|
|
2435
|
+
detached: true,
|
|
2436
|
+
...opts.env ? { env: { ...process.env, ...opts.env } } : {}
|
|
2437
|
+
});
|
|
2438
|
+
const decoder = new StringDecoder3("utf8");
|
|
2439
|
+
const done = new Promise((resolve2) => {
|
|
2440
|
+
let fallback;
|
|
2441
|
+
child.once("exit", () => {
|
|
2442
|
+
if (child.pid !== void 0) {
|
|
2443
|
+
try {
|
|
2444
|
+
process.kill(-child.pid, "SIGKILL");
|
|
2445
|
+
} catch {
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
fallback = setTimeout(resolve2, 2e3);
|
|
2449
|
+
fallback.unref();
|
|
2450
|
+
});
|
|
2451
|
+
child.once("close", () => {
|
|
2452
|
+
if (fallback) clearTimeout(fallback);
|
|
2453
|
+
resolve2();
|
|
2454
|
+
});
|
|
2455
|
+
child.once("error", () => {
|
|
2456
|
+
if (fallback) clearTimeout(fallback);
|
|
2457
|
+
resolve2();
|
|
2458
|
+
});
|
|
2459
|
+
});
|
|
2460
|
+
child.stdin?.on("error", () => {
|
|
2461
|
+
});
|
|
2462
|
+
child.stdout?.on("error", () => {
|
|
2463
|
+
});
|
|
2464
|
+
child.stderr?.on("error", () => {
|
|
2465
|
+
});
|
|
2466
|
+
child.stderr?.resume();
|
|
2467
|
+
return {
|
|
2468
|
+
write: (line) => {
|
|
2469
|
+
const stdin = child.stdin;
|
|
2470
|
+
if (!stdin || stdin.destroyed || stdin.writableEnded) {
|
|
2471
|
+
throw new WarmUnavailable("resident session stdin is closed");
|
|
2472
|
+
}
|
|
2473
|
+
stdin.write(line, (err) => {
|
|
2474
|
+
if (err) child.kill("SIGTERM");
|
|
2475
|
+
});
|
|
2476
|
+
},
|
|
2477
|
+
onData: (cb) => {
|
|
2478
|
+
child.stdout?.on("data", (d) => cb(decoder.write(d)));
|
|
2479
|
+
},
|
|
2480
|
+
onExit: (cb) => {
|
|
2481
|
+
void done.then(cb);
|
|
2482
|
+
},
|
|
2483
|
+
wait: () => done,
|
|
2484
|
+
kill: (signal) => {
|
|
2485
|
+
if (child.pid === void 0) return;
|
|
2486
|
+
try {
|
|
2487
|
+
process.kill(-child.pid, signal);
|
|
2488
|
+
} catch {
|
|
2489
|
+
try {
|
|
2490
|
+
child.kill(signal);
|
|
2491
|
+
} catch {
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
}
|
|
2495
|
+
};
|
|
2496
|
+
};
|
|
2497
|
+
function confinementKey(roots) {
|
|
2498
|
+
return JSON.stringify([...new Set((roots ?? []).map((r) => resolvePath(r)))].sort());
|
|
2499
|
+
}
|
|
2500
|
+
var WarmUnavailable = class extends Error {
|
|
2501
|
+
constructor(reason) {
|
|
2502
|
+
super(reason);
|
|
2503
|
+
this.name = "WarmUnavailable";
|
|
2504
|
+
}
|
|
2505
|
+
};
|
|
2506
|
+
var WarmTurnUncertain = class extends AgyFailure {
|
|
2507
|
+
constructor(reason) {
|
|
2508
|
+
super(
|
|
2509
|
+
"agy_error",
|
|
2510
|
+
`The resident agy session was dropped (${reason}) after the turn had already been sent, so it may or may not have run. Not retrying automatically: inspect the working tree and the conversation before re-sending.`
|
|
2511
|
+
);
|
|
2512
|
+
this.name = "WarmTurnUncertain";
|
|
2513
|
+
}
|
|
2514
|
+
};
|
|
2515
|
+
var WarmTimeout = class extends Error {
|
|
2516
|
+
constructor(text2, usage) {
|
|
2517
|
+
super("resident agy session exceeded the turn timeout");
|
|
2518
|
+
this.text = text2;
|
|
2519
|
+
this.usage = usage;
|
|
2520
|
+
this.name = "WarmTimeout";
|
|
2521
|
+
}
|
|
2522
|
+
text;
|
|
2523
|
+
usage;
|
|
2524
|
+
finishedReason = "print_timeout";
|
|
2525
|
+
conversationId;
|
|
2526
|
+
numTurns;
|
|
2527
|
+
deniedActions;
|
|
2528
|
+
};
|
|
2529
|
+
function usageDelta(now, before) {
|
|
2530
|
+
const d = (a, b) => Math.max(0, a - b);
|
|
2531
|
+
return {
|
|
2532
|
+
inputTokens: d(now.inputTokens, before.inputTokens),
|
|
2533
|
+
outputTokens: d(now.outputTokens, before.outputTokens),
|
|
2534
|
+
thinkingTokens: d(now.thinkingTokens, before.thinkingTokens),
|
|
2535
|
+
cacheReadTokens: d(now.cacheReadTokens, before.cacheReadTokens),
|
|
2536
|
+
totalTokens: d(now.totalTokens, before.totalTokens)
|
|
2537
|
+
};
|
|
2538
|
+
}
|
|
2539
|
+
var WarmSessions = class {
|
|
2540
|
+
constructor(cfg, caps, deps = {}) {
|
|
2541
|
+
this.cfg = cfg;
|
|
2542
|
+
this.caps = caps;
|
|
2543
|
+
this.deps = deps;
|
|
2544
|
+
}
|
|
2545
|
+
cfg;
|
|
2546
|
+
caps;
|
|
2547
|
+
deps;
|
|
2548
|
+
sessions = /* @__PURE__ */ new Map();
|
|
2549
|
+
/** Outstanding SIGKILL escalations, cleared on shutdown so nothing is left armed. */
|
|
2550
|
+
pendingKills = /* @__PURE__ */ new Set();
|
|
2551
|
+
/** A dropped session is still owned until it has been killed/reaped. */
|
|
2552
|
+
terminating = /* @__PURE__ */ new Set();
|
|
2553
|
+
killGraceMs = 2e3;
|
|
2554
|
+
get enabled() {
|
|
2555
|
+
return this.cfg.warmSessions && this.caps.has("--input-format") && this.caps.has("--output-format");
|
|
2556
|
+
}
|
|
2557
|
+
stats() {
|
|
2558
|
+
return { resident: this.sessions.size, keys: [...this.sessions.keys()] };
|
|
2559
|
+
}
|
|
2560
|
+
/** Stop stale residents before another process resumes the same conversation. */
|
|
2561
|
+
async invalidate(conversationId) {
|
|
2562
|
+
if (this.sessions.get(conversationId)?.busy)
|
|
2563
|
+
throw new InvalidRequestError(
|
|
2564
|
+
"The resident session is already running a turn. Wait for it to finish before continuing."
|
|
2565
|
+
);
|
|
2566
|
+
const all = /* @__PURE__ */ new Set([
|
|
2567
|
+
...[...this.sessions.values()].filter((s) => s.key === conversationId),
|
|
2568
|
+
...[...this.terminating].filter((s) => s.key === conversationId)
|
|
2569
|
+
]);
|
|
2570
|
+
for (const s of all) this.drop(s, "cold continuation", true);
|
|
2571
|
+
for (const s of all) {
|
|
2572
|
+
if (!s.proc.wait) continue;
|
|
2573
|
+
let timer;
|
|
2574
|
+
try {
|
|
2575
|
+
await Promise.race([
|
|
2576
|
+
s.proc.wait(),
|
|
2577
|
+
new Promise((_, reject) => {
|
|
2578
|
+
timer = setTimeout(
|
|
2579
|
+
() => reject(new WarmTurnUncertain("previous resident did not exit")),
|
|
2580
|
+
this.killGraceMs + 1e3
|
|
2581
|
+
);
|
|
2582
|
+
})
|
|
2583
|
+
]);
|
|
2584
|
+
} finally {
|
|
2585
|
+
if (timer) clearTimeout(timer);
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
}
|
|
2589
|
+
policyKey(opts) {
|
|
2590
|
+
return JSON.stringify({
|
|
2591
|
+
dirs: [...new Set((opts.dirs ?? []).map((d) => resolvePath(d)))].sort(),
|
|
2592
|
+
sandbox: opts.sandbox ?? this.cfg.sandbox,
|
|
2593
|
+
slashCommands: opts.slashCommands === true,
|
|
2594
|
+
mode: opts.mode ?? "plan"
|
|
2595
|
+
});
|
|
2596
|
+
}
|
|
2597
|
+
/**
|
|
2598
|
+
* Runs one turn against the session for `conversationId`, starting it if
|
|
2599
|
+
* needed. Throws `WarmUnavailable` whenever a cold run would be safer — the
|
|
2600
|
+
* caller treats that as "fall back", never as a failed delegation — and
|
|
2601
|
+
* `WarmTimeout` when the turn itself ran out of time.
|
|
2602
|
+
*
|
|
2603
|
+
* The envelope's `usage` is this turn's alone: agy reports the conversation's
|
|
2604
|
+
* running total on every result, verified on agy 1.2.1.
|
|
2605
|
+
*/
|
|
2606
|
+
async turn(conversationId, cwd, prompt, opts) {
|
|
2607
|
+
if (!this.enabled) throw new WarmUnavailable("warm sessions are disabled");
|
|
2608
|
+
if (opts.signal?.aborted) throw new Error("agy run cancelled by client.");
|
|
2609
|
+
const existing = this.sessions.get(conversationId);
|
|
2610
|
+
if (existing?.busy)
|
|
2611
|
+
throw new InvalidRequestError(
|
|
2612
|
+
"The resident session is already running a turn. Wait for it to finish before continuing."
|
|
2613
|
+
);
|
|
2614
|
+
const confinedTo = confinementKey(opts.confineTo);
|
|
2615
|
+
const policyKey = this.policyKey(opts);
|
|
2616
|
+
const mismatch = !existing ? void 0 : resolvePath(existing.cwd) !== resolvePath(cwd) ? "resident session belongs to a different working directory" : existing.confinedTo !== confinedTo ? "resident session was started with different write confinement" : existing.policyKey !== policyKey ? "resident session was started with different execution options" : void 0;
|
|
2617
|
+
if (existing && mismatch) {
|
|
2618
|
+
if (!existing.busy) this.drop(existing, mismatch);
|
|
2619
|
+
throw new WarmUnavailable(mismatch);
|
|
2620
|
+
}
|
|
2621
|
+
const session = existing ?? this.start(conversationId, cwd, opts);
|
|
2622
|
+
if (!session.alive) {
|
|
2623
|
+
this.drop(session, "process is gone");
|
|
2624
|
+
throw new WarmUnavailable("resident agy session had exited");
|
|
2625
|
+
}
|
|
2626
|
+
session.busy = true;
|
|
2627
|
+
session.outputBytes = Buffer.byteLength(session.buffer);
|
|
2628
|
+
session.lastUsed = this.now();
|
|
2629
|
+
this.arm(session);
|
|
2630
|
+
let deadline;
|
|
2631
|
+
const onAbort = () => {
|
|
2632
|
+
session.pending?.reject(
|
|
2633
|
+
session.pending.sent ? Object.assign(new AgyFailure("agy_error", "agy run cancelled by client."), {
|
|
2634
|
+
usageKnown: false,
|
|
2635
|
+
conversationId: session.key,
|
|
2636
|
+
finishedReason: "interrupted",
|
|
2637
|
+
...session.pending.text ? { partialOutput: clipPartialOutput(session.pending.text, this.cfg.redact) } : {}
|
|
2638
|
+
}) : new Error("agy run cancelled by client.")
|
|
2639
|
+
);
|
|
2640
|
+
this.drop(session, "cancelled");
|
|
2641
|
+
};
|
|
2642
|
+
try {
|
|
2643
|
+
const envelope = await new Promise((resolve2, reject) => {
|
|
2644
|
+
session.pending = {
|
|
2645
|
+
resolve: resolve2,
|
|
2646
|
+
reject,
|
|
2647
|
+
text: "",
|
|
2648
|
+
...opts.onProgress ? { onProgress: opts.onProgress } : {}
|
|
2649
|
+
};
|
|
2650
|
+
deadline = setTimeout(() => {
|
|
2651
|
+
reject(
|
|
2652
|
+
Object.assign(new WarmTimeout(session.pending?.text ?? ""), {
|
|
2653
|
+
conversationId: session.key
|
|
2654
|
+
})
|
|
2655
|
+
);
|
|
2656
|
+
this.drop(session, "turn timed out");
|
|
2657
|
+
}, opts.timeoutMs);
|
|
2658
|
+
deadline.unref?.();
|
|
2659
|
+
opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
2660
|
+
try {
|
|
2661
|
+
session.proc.write(turnMessage(prompt));
|
|
2662
|
+
if (session.pending) session.pending.sent = true;
|
|
2663
|
+
} catch (err) {
|
|
2664
|
+
reject(new WarmUnavailable(`could not write to resident session: ${String(err)}`));
|
|
2665
|
+
}
|
|
2666
|
+
});
|
|
2667
|
+
const usage = usageDelta(envelope.usage, session.usageSoFar);
|
|
2668
|
+
session.usageSoFar = envelope.usage;
|
|
2669
|
+
return { ...envelope, usage };
|
|
2670
|
+
} finally {
|
|
2671
|
+
if (deadline) clearTimeout(deadline);
|
|
2672
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
2673
|
+
session.busy = false;
|
|
2674
|
+
delete session.pending;
|
|
2675
|
+
session.lastUsed = this.now();
|
|
2676
|
+
if (session.alive) this.arm(session);
|
|
2677
|
+
}
|
|
2678
|
+
}
|
|
2679
|
+
now() {
|
|
2680
|
+
return this.deps.now?.() ?? Date.now();
|
|
2681
|
+
}
|
|
2682
|
+
start(conversationId, cwd, opts) {
|
|
2683
|
+
if (!this.evictIfFull()) {
|
|
2684
|
+
throw new WarmUnavailable(`all ${this.cfg.warmMax} resident sessions are busy`);
|
|
2685
|
+
}
|
|
2686
|
+
const args = [
|
|
2687
|
+
"--input-format",
|
|
2688
|
+
"stream-json",
|
|
2689
|
+
"--output-format",
|
|
2690
|
+
"stream-json",
|
|
2691
|
+
"--conversation",
|
|
2692
|
+
conversationId,
|
|
2693
|
+
"--add-dir",
|
|
2694
|
+
cwd
|
|
2695
|
+
];
|
|
2696
|
+
for (const dir of opts.dirs ?? []) if (dir !== cwd) args.push("--add-dir", dir);
|
|
2697
|
+
args.push(
|
|
2698
|
+
...permissionArgs(
|
|
2699
|
+
{
|
|
2700
|
+
mode: opts.mode ?? "plan",
|
|
2701
|
+
sandbox: opts.sandbox,
|
|
2702
|
+
slashCommands: opts.slashCommands
|
|
2703
|
+
},
|
|
2704
|
+
this.cfg,
|
|
2705
|
+
this.caps
|
|
2706
|
+
)
|
|
2707
|
+
);
|
|
2708
|
+
const spawnFn = this.deps.spawnSession ?? spawnSessionProcess;
|
|
2709
|
+
let proc;
|
|
2710
|
+
try {
|
|
2711
|
+
const command = commandFor(opts.confineTo, this.cfg.agyPath, args, this.deps.confinement);
|
|
2712
|
+
proc = spawnFn(command.file, command.args, {
|
|
2713
|
+
cwd,
|
|
2714
|
+
...this.deps.env ? { env: this.deps.env } : {}
|
|
2715
|
+
});
|
|
2716
|
+
} catch (err) {
|
|
2717
|
+
throw new WarmUnavailable(`could not start a resident session: ${err.message}`);
|
|
2718
|
+
}
|
|
2719
|
+
const session = {
|
|
2720
|
+
key: conversationId,
|
|
2721
|
+
cwd,
|
|
2722
|
+
confinedTo: confinementKey(opts.confineTo),
|
|
2723
|
+
policyKey: this.policyKey(opts),
|
|
2724
|
+
proc,
|
|
2725
|
+
buffer: "",
|
|
2726
|
+
outputBytes: 0,
|
|
2727
|
+
alive: true,
|
|
2728
|
+
exited: false,
|
|
2729
|
+
busy: false,
|
|
2730
|
+
lastUsed: this.now(),
|
|
2731
|
+
usageSoFar: {
|
|
2732
|
+
inputTokens: 0,
|
|
2733
|
+
outputTokens: 0,
|
|
2734
|
+
thinkingTokens: 0,
|
|
2735
|
+
cacheReadTokens: 0,
|
|
2736
|
+
totalTokens: 0
|
|
2737
|
+
}
|
|
2738
|
+
};
|
|
2739
|
+
session.proc.onData((chunk) => this.consume(session, chunk));
|
|
2740
|
+
session.proc.onExit(() => {
|
|
2741
|
+
session.alive = false;
|
|
2742
|
+
session.exited = true;
|
|
2743
|
+
if (session.killTimer) {
|
|
2744
|
+
clearTimeout(session.killTimer);
|
|
2745
|
+
this.pendingKills.delete(session.killTimer);
|
|
2746
|
+
delete session.killTimer;
|
|
2747
|
+
}
|
|
2748
|
+
this.terminating.delete(session);
|
|
2749
|
+
session.pending?.reject(
|
|
2750
|
+
session.pending.sent ? this.uncertain(session, "process exited mid-turn") : new WarmUnavailable("resident agy session exited mid-turn")
|
|
2751
|
+
);
|
|
2752
|
+
this.forget(session);
|
|
2753
|
+
});
|
|
2754
|
+
this.sessions.set(conversationId, session);
|
|
2755
|
+
this.arm(session);
|
|
2756
|
+
return session;
|
|
2757
|
+
}
|
|
2758
|
+
consume(session, chunk) {
|
|
2759
|
+
if (!session.alive) return;
|
|
2760
|
+
const bytes = Buffer.byteLength(chunk);
|
|
2761
|
+
if (bytes > MAX_RAW_OUTPUT_BYTES - session.outputBytes) {
|
|
2762
|
+
session.pending?.reject(
|
|
2763
|
+
Object.assign(new OutputLimitError("resident stdout", MAX_RAW_OUTPUT_BYTES), {
|
|
2764
|
+
conversationId: session.key,
|
|
2765
|
+
...session.pending.text ? { partialOutput: clipPartialOutput(session.pending.text, this.cfg.redact) } : {}
|
|
2766
|
+
})
|
|
2767
|
+
);
|
|
2768
|
+
session.buffer = "";
|
|
2769
|
+
this.drop(session, "raw output limit exceeded", true);
|
|
2770
|
+
return;
|
|
2771
|
+
}
|
|
2772
|
+
session.outputBytes += bytes;
|
|
2773
|
+
session.buffer += chunk;
|
|
2774
|
+
const { events, rest } = parseStreamEvents(session.buffer);
|
|
2775
|
+
session.buffer = rest;
|
|
2776
|
+
for (const ev of events) {
|
|
2777
|
+
if (ev.kind === "step" && session.pending) {
|
|
2778
|
+
session.pending.text += ev.textDelta;
|
|
2779
|
+
try {
|
|
2780
|
+
session.pending.onProgress?.(session.pending.text);
|
|
2781
|
+
} catch {
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
if (ev.kind === "result") session.pending?.resolve(ev.envelope);
|
|
2785
|
+
}
|
|
2786
|
+
}
|
|
2787
|
+
arm(session) {
|
|
2788
|
+
if (session.idleTimer) clearTimeout(session.idleTimer);
|
|
2789
|
+
session.idleTimer = setTimeout(() => {
|
|
2790
|
+
if (!session.busy) this.drop(session, "idle");
|
|
2791
|
+
}, this.cfg.warmIdleSec * 1e3);
|
|
2792
|
+
session.idleTimer.unref?.();
|
|
2793
|
+
}
|
|
2794
|
+
/** Makes room for one more session; false when every resident one is mid-turn. */
|
|
2795
|
+
evictIfFull() {
|
|
2796
|
+
while (this.sessions.size >= this.cfg.warmMax) {
|
|
2797
|
+
let oldest;
|
|
2798
|
+
for (const s of this.sessions.values()) {
|
|
2799
|
+
if (!s.busy && (!oldest || s.lastUsed < oldest.lastUsed)) oldest = s;
|
|
2800
|
+
}
|
|
2801
|
+
if (!oldest) return false;
|
|
2802
|
+
this.drop(oldest, "evicted");
|
|
2803
|
+
}
|
|
2804
|
+
return true;
|
|
2805
|
+
}
|
|
2806
|
+
/**
|
|
2807
|
+
* Removes `session` from the map only if it is still the one registered. A
|
|
2808
|
+
* dropped process closes late; deleting by key then removed its replacement,
|
|
2809
|
+
* which shutdown could no longer find and so never killed.
|
|
2810
|
+
*/
|
|
2811
|
+
forget(session) {
|
|
2812
|
+
if (this.sessions.get(session.key) === session) this.sessions.delete(session.key);
|
|
2813
|
+
}
|
|
2814
|
+
uncertain(session, why) {
|
|
2815
|
+
return Object.assign(new WarmTurnUncertain(why), {
|
|
2816
|
+
usageKnown: false,
|
|
2817
|
+
conversationId: session.key,
|
|
2818
|
+
finishedReason: "interrupted",
|
|
2819
|
+
...session.pending?.text ? { partialOutput: clipPartialOutput(session.pending.text, this.cfg.redact) } : {}
|
|
2820
|
+
});
|
|
2821
|
+
}
|
|
2822
|
+
drop(session, why, hard = false) {
|
|
2823
|
+
if (session.idleTimer) clearTimeout(session.idleTimer);
|
|
2824
|
+
if (session.killTimer) {
|
|
2825
|
+
clearTimeout(session.killTimer);
|
|
2826
|
+
this.pendingKills.delete(session.killTimer);
|
|
2827
|
+
delete session.killTimer;
|
|
2828
|
+
}
|
|
2829
|
+
session.alive = false;
|
|
2830
|
+
this.forget(session);
|
|
2831
|
+
if (!session.exited) this.terminating.add(session);
|
|
2832
|
+
session.pending?.reject(
|
|
2833
|
+
session.pending.sent ? this.uncertain(session, why) : new WarmUnavailable(`resident session dropped: ${why}`)
|
|
2834
|
+
);
|
|
2835
|
+
if (session.exited) return;
|
|
2836
|
+
const signal = (sig) => {
|
|
2837
|
+
try {
|
|
2838
|
+
session.proc.kill(sig);
|
|
2839
|
+
} catch {
|
|
2840
|
+
}
|
|
2841
|
+
};
|
|
2842
|
+
if (hard) {
|
|
2843
|
+
signal("SIGTERM");
|
|
2844
|
+
signal("SIGKILL");
|
|
2845
|
+
if (!session.proc.wait) this.terminating.delete(session);
|
|
2846
|
+
return;
|
|
2847
|
+
}
|
|
2848
|
+
signal("SIGTERM");
|
|
2849
|
+
const escalate = setTimeout(() => {
|
|
2850
|
+
this.pendingKills.delete(escalate);
|
|
2851
|
+
delete session.killTimer;
|
|
2852
|
+
if (!session.exited) signal("SIGKILL");
|
|
2853
|
+
if (!session.proc.wait) this.terminating.delete(session);
|
|
2854
|
+
}, this.killGraceMs);
|
|
2855
|
+
escalate.unref?.();
|
|
2856
|
+
session.killTimer = escalate;
|
|
2857
|
+
this.pendingKills.add(escalate);
|
|
2858
|
+
}
|
|
2859
|
+
/** Stops every resident session. Safe to call more than once. */
|
|
2860
|
+
shutdown() {
|
|
2861
|
+
const owned = /* @__PURE__ */ new Set([...this.sessions.values(), ...this.terminating]);
|
|
2862
|
+
for (const t of this.pendingKills) clearTimeout(t);
|
|
2863
|
+
this.pendingKills.clear();
|
|
2864
|
+
for (const s of owned) this.drop(s, "shutdown", true);
|
|
2865
|
+
}
|
|
2866
|
+
};
|
|
2867
|
+
|
|
2868
|
+
// src/delegation.ts
|
|
2869
|
+
function continuationOf(requested, reported) {
|
|
2870
|
+
if (requested === void 0 || reported === void 0) return {};
|
|
2871
|
+
return { continuation: { requested, resumed: requested === reported } };
|
|
2872
|
+
}
|
|
2873
|
+
var ModelNotChosenError = class extends Error {
|
|
2874
|
+
constructor(suggested, available) {
|
|
2875
|
+
const listing = available ? available.map((m) => `- ${m.name}`).join("\n") : "- (agy models could not be listed; run `agy models` yourself)";
|
|
2876
|
+
const fallback = suggested ? `${suggested.model}${suggested.effort ? ` at ${suggested.effort} effort` : ""}` : "agy's own default model";
|
|
2877
|
+
super(
|
|
2878
|
+
`No model has been chosen for this machine yet. Ask the user this, in these words: "Proceed with the default \u2014 ${fallback} \u2014 or change the model or effort?" Then call \`set_model\` once: with no arguments to accept the default, or with the model and effort they chose. The choice is saved and this will not be asked again.
|
|
2879
|
+
Models agy offers:
|
|
2880
|
+
${listing}
|
|
2881
|
+
Set AGY_ASK_MODEL=false to skip this and route on the built-in chains.`
|
|
2882
|
+
);
|
|
2883
|
+
this.name = "ModelNotChosenError";
|
|
2884
|
+
}
|
|
2885
|
+
};
|
|
2886
|
+
var NotRepeatedError = class extends Error {
|
|
2887
|
+
constructor(cause, what) {
|
|
2888
|
+
super(
|
|
2889
|
+
`${cause.message}
|
|
2890
|
+
|
|
2891
|
+
Not ${what}: the request was sent to agy and its outcome may include file changes or external effects. An unchanged or unreadable working tree cannot prove that nothing happened. Inspect the working tree and conversation before deliberately dispatching another turn.`,
|
|
2892
|
+
{ cause }
|
|
2893
|
+
);
|
|
2894
|
+
this.name = "NotRepeatedError";
|
|
2895
|
+
}
|
|
2896
|
+
};
|
|
2897
|
+
var READ_ONLY_TREE_MOVED = "WORKING TREE CHANGED \u2014 this call ran in plan mode with writes into its roots blocked for agy and every process it started, yet the tree changed while it ran. Another process changed it, or agy reached it through a process started outside its sandbox, such as an app or a launchd job. Inspect the tree before trusting it.";
|
|
2898
|
+
var READ_ONLY_VIOLATION = "READ-ONLY VIOLATION \u2014 this call ran in plan mode, and the working tree changed while it ran. agy does not enforce plan mode, with the permission bypass on or off, and this run could not be confined, so treat it as having had write access: inspect the tree before trusting it.";
|
|
2899
|
+
function treeMovedWarning(state) {
|
|
2900
|
+
return state?.enforced ? READ_ONLY_TREE_MOVED : READ_ONLY_VIOLATION;
|
|
2901
|
+
}
|
|
2902
|
+
var DelegationDepthError = class extends Error {
|
|
2903
|
+
constructor(depth, max) {
|
|
2904
|
+
super(
|
|
2905
|
+
`Refusing to delegate: this server is already ${depth} delegation(s) deep (limit ${max}). ${SERVER_NAME} is registered as an MCP server inside the agy session that called it, so the call would loop host -> agy -> ${SERVER_NAME} -> agy until the quota is gone. Unregister it with \`agy mcp remove\`, or raise AGY_MAX_DELEGATION_DEPTH if the nesting is deliberate.`
|
|
2906
|
+
);
|
|
2907
|
+
this.name = "DelegationDepthError";
|
|
2908
|
+
}
|
|
2909
|
+
};
|
|
2910
|
+
var Delegator = class {
|
|
2911
|
+
constructor(cfg, models, caps, deps = {}, env = process.env) {
|
|
2912
|
+
this.cfg = cfg;
|
|
2913
|
+
this.models = models;
|
|
2914
|
+
this.caps = caps;
|
|
2915
|
+
this.deps = deps;
|
|
2916
|
+
this.depth = delegationDepth(env);
|
|
2917
|
+
this.cooldowns = deps.cooldowns ?? new CooldownRegistry();
|
|
2918
|
+
this.admission = new Admission(cfg.maxConcurrency);
|
|
2919
|
+
this.ledger = new UsageLedger(cfg.budgetTokens);
|
|
2920
|
+
this.warm = new WarmSessions(cfg, caps, { ...deps, env: this.childEnv() });
|
|
2921
|
+
this.prefs = deps.preferences ?? new MemoryPreferenceStore();
|
|
2922
|
+
}
|
|
2923
|
+
cfg;
|
|
2924
|
+
models;
|
|
2925
|
+
caps;
|
|
2926
|
+
deps;
|
|
2927
|
+
cooldowns;
|
|
2928
|
+
admission;
|
|
2929
|
+
ledger;
|
|
2930
|
+
warm;
|
|
2931
|
+
prefs;
|
|
2932
|
+
depth;
|
|
2933
|
+
/** Cold agy processes still running, so shutdown can reap what it started. */
|
|
2934
|
+
live = /* @__PURE__ */ new Set();
|
|
2935
|
+
/** Everything the `agy_status` tool reports. */
|
|
2936
|
+
status() {
|
|
2937
|
+
const confinement = this.deps.confinement;
|
|
2938
|
+
const enforced = this.cfg.readOnlyEnforcement !== "off" && confinement?.available === true;
|
|
2939
|
+
return {
|
|
2940
|
+
preference: this.prefs.load(),
|
|
2941
|
+
askModel: this.cfg.askModel,
|
|
2942
|
+
agyVersion: this.caps.version,
|
|
2943
|
+
missingFlags: this.caps.missing,
|
|
2944
|
+
spent: this.ledger.spent,
|
|
2945
|
+
...this.ledger.budget !== void 0 ? { budget: this.ledger.budget } : {},
|
|
2946
|
+
usage: this.ledger.rows(),
|
|
2947
|
+
cooldowns: this.cooldowns.active(),
|
|
2948
|
+
inFlight: this.admission.inFlight,
|
|
2949
|
+
queued: this.admission.queued,
|
|
2950
|
+
warm: this.warm.stats(),
|
|
2951
|
+
depth: this.depth,
|
|
2952
|
+
readOnly: {
|
|
2953
|
+
policy: this.cfg.readOnlyEnforcement,
|
|
2954
|
+
enforced,
|
|
2955
|
+
...enforced ? {} : {
|
|
2956
|
+
reason: this.cfg.readOnlyEnforcement === "off" ? "AGY_READ_ONLY_ENFORCEMENT is off" : confinement?.reason ?? "write confinement was not set up"
|
|
2957
|
+
}
|
|
2958
|
+
}
|
|
2959
|
+
};
|
|
2960
|
+
}
|
|
2961
|
+
/** The models agy offers, or null when the listing could not be read. */
|
|
2962
|
+
availableModels() {
|
|
2963
|
+
return this.models.available();
|
|
2964
|
+
}
|
|
2965
|
+
/**
|
|
2966
|
+
* What `set_model` accepts when the user just says "proceed": the configured
|
|
2967
|
+
* default model resolved against the live listing, at the tier its name carries.
|
|
2968
|
+
*/
|
|
2969
|
+
async defaultChoice() {
|
|
2970
|
+
if (!this.cfg.defaultModel) return null;
|
|
2971
|
+
const available = await this.models.available();
|
|
2972
|
+
if (!available) return null;
|
|
2973
|
+
const id = resolveEntry(this.cfg.defaultModel, available);
|
|
2974
|
+
if (!id) {
|
|
2975
|
+
throw new InvalidRequestError(
|
|
2976
|
+
`AGY_DEFAULT_MODEL "${this.cfg.defaultModel}" is not offered by this installation. Run agy models and choose an available default or call set_model with a listed ID.`
|
|
2977
|
+
);
|
|
2978
|
+
}
|
|
2979
|
+
const pick = await this.selection(this.cfg.defaultModel, this.cfg.defaultEffort, available);
|
|
2980
|
+
const tier = available.find((m) => m.id === pick.model)?.effort;
|
|
2981
|
+
return { model: pick.model, ...isEffort(tier) ? { effort: tier } : {}, setAt: "" };
|
|
2982
|
+
}
|
|
2983
|
+
/** Resolve a fixed variant or an intentional family/effort selection exactly once. */
|
|
2984
|
+
async selection(entry, effort2, available) {
|
|
2985
|
+
const id = resolveEntry(entry, available);
|
|
2986
|
+
if (!id) {
|
|
2987
|
+
throw new InvalidRequestError(
|
|
2988
|
+
`Model "${entry}" is not available. Run agy models and select a listed model ID.`
|
|
2989
|
+
);
|
|
2990
|
+
}
|
|
2991
|
+
const fixed = available.find((m) => m.id === entry || m.name === entry);
|
|
2992
|
+
if (fixed && effort2 && fixed.effort !== effort2) {
|
|
2993
|
+
throw new InvalidRequestError(
|
|
2994
|
+
`Model "${entry}" fixes the ${fixed.effort ?? "untiered"} variant; effort "${effort2}" conflicts with that selection. Select the desired listed ID or use a family selector.`
|
|
2995
|
+
);
|
|
2996
|
+
}
|
|
2997
|
+
return await this.models.forEffort(id, effort2) ?? { model: id };
|
|
2998
|
+
}
|
|
2999
|
+
/**
|
|
3000
|
+
* Records the user's choice for every later call on this machine.
|
|
3001
|
+
*
|
|
3002
|
+
* The model is validated against the live listing; a tier that differs from
|
|
3003
|
+
* the one in the model's name selects the sibling at that tier, so what is
|
|
3004
|
+
* stored is exactly what will be passed to agy.
|
|
3005
|
+
*/
|
|
3006
|
+
async setPreference(model, effort2) {
|
|
3007
|
+
const available = await this.models.available();
|
|
3008
|
+
if (!available) {
|
|
3009
|
+
throw new Error(
|
|
3010
|
+
"set_model could not verify the model: `agy models` failed, so nothing was saved. Check that agy is installed and signed in, then call set_model again."
|
|
3011
|
+
);
|
|
3012
|
+
}
|
|
3013
|
+
if (!model && !effort2) {
|
|
3014
|
+
const fallback = await this.defaultChoice();
|
|
3015
|
+
if (!fallback) {
|
|
3016
|
+
throw new Error(
|
|
3017
|
+
"set_model needs a `model`: the default could not be resolved against agy's model list."
|
|
3018
|
+
);
|
|
3019
|
+
}
|
|
3020
|
+
const pref2 = { ...fallback, setAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
3021
|
+
this.prefs.save(pref2);
|
|
3022
|
+
return pref2;
|
|
3023
|
+
}
|
|
3024
|
+
model ??= this.cfg.defaultModel;
|
|
3025
|
+
if (!model)
|
|
3026
|
+
throw new InvalidRequestError("set_model requires a listed model or configured default.");
|
|
3027
|
+
const pick = await this.selection(model, effort2, available);
|
|
3028
|
+
const tier = available.find((m) => m.id === pick.model)?.effort;
|
|
3029
|
+
const pref = {
|
|
3030
|
+
model: pick.model,
|
|
3031
|
+
...isEffort(tier) ? { effort: tier } : {},
|
|
3032
|
+
setAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3033
|
+
};
|
|
3034
|
+
this.prefs.save(pref);
|
|
3035
|
+
return pref;
|
|
3036
|
+
}
|
|
3037
|
+
/**
|
|
3038
|
+
* Kills everything this delegator started. Cold runs are detached process
|
|
3039
|
+
* groups running with permissions skipped, so the bridge's own exit does not
|
|
3040
|
+
* stop them; without this they ran on for up to AGY_TIMEOUT after the client
|
|
3041
|
+
* was gone. Synchronous, because the exit path cannot wait.
|
|
3042
|
+
*/
|
|
3043
|
+
shutdown() {
|
|
3044
|
+
this.warm.shutdown();
|
|
3045
|
+
for (const proc of this.live) {
|
|
3046
|
+
proc.kill("SIGTERM");
|
|
3047
|
+
proc.kill("SIGKILL");
|
|
3048
|
+
}
|
|
3049
|
+
this.live.clear();
|
|
3050
|
+
}
|
|
3051
|
+
/** The environment a child agy inherits, carrying the recursion counter. */
|
|
3052
|
+
childEnv() {
|
|
3053
|
+
return { AGY_DELEGATION_DEPTH: String(this.depth + 1) };
|
|
3054
|
+
}
|
|
3055
|
+
assertMayDelegate(req) {
|
|
3056
|
+
if (this.depth >= this.cfg.maxDelegationDepth) {
|
|
3057
|
+
throw new DelegationDepthError(this.depth, this.cfg.maxDelegationDepth);
|
|
3058
|
+
}
|
|
3059
|
+
this.ledger.assertWithinBudget();
|
|
3060
|
+
assertWithinRoots(
|
|
3061
|
+
[req.cwd, ...this.dirsFor(req), ...req.tool.touchedPaths(req.args, req.cwd)],
|
|
3062
|
+
this.cfg.allowedRoots
|
|
3063
|
+
);
|
|
3064
|
+
}
|
|
3065
|
+
/**
|
|
3066
|
+
* How this call is kept read-only, or undefined for a call allowed to write.
|
|
3067
|
+
* Confinement follows the configured policy and what the machine supports.
|
|
3068
|
+
*/
|
|
3069
|
+
readOnlyFor(req) {
|
|
3070
|
+
if (modeFor(req.tool, req.write) !== "plan") return void 0;
|
|
3071
|
+
if (this.cfg.readOnlyEnforcement === "off") {
|
|
3072
|
+
return { enforced: false, reason: "AGY_READ_ONLY_ENFORCEMENT is off" };
|
|
3073
|
+
}
|
|
3074
|
+
const confinement = this.deps.confinement;
|
|
3075
|
+
if (!confinement?.available) {
|
|
3076
|
+
return { enforced: false, reason: confinement?.reason ?? "write confinement was not set up" };
|
|
3077
|
+
}
|
|
3078
|
+
if (rootInsideState([req.cwd, ...this.dirsFor(req)])) {
|
|
3079
|
+
return { enforced: false, reason: "a root is inside agy's own state directory" };
|
|
3080
|
+
}
|
|
3081
|
+
return { enforced: true };
|
|
3082
|
+
}
|
|
3083
|
+
/** The roots a read-only run is confined against, when it is confined at all. */
|
|
3084
|
+
confineFor(req) {
|
|
3085
|
+
return this.readOnlyFor(req)?.enforced ? [req.cwd, ...this.dirsFor(req)] : void 0;
|
|
3086
|
+
}
|
|
3087
|
+
/**
|
|
3088
|
+
* Every workspace root this call needs: what the caller asked for, plus the
|
|
3089
|
+
* directories the tool's own arguments imply — a file outside `cwd` is not in
|
|
3090
|
+
* agy's workspace unless its directory is added too.
|
|
3091
|
+
*
|
|
3092
|
+
* Whatever this returns is containment-checked by `assertMayDelegate`, so a
|
|
3093
|
+
* derived root can never widen the caller's reach.
|
|
3094
|
+
*/
|
|
3095
|
+
dirsFor(req) {
|
|
3096
|
+
return [.../* @__PURE__ */ new Set([...req.dirs ?? [], ...req.tool.extraDirs(req.args, req.cwd)])];
|
|
3097
|
+
}
|
|
3098
|
+
async run(req) {
|
|
3099
|
+
this.assertMayDelegate(req);
|
|
3100
|
+
const prompt = req.tool.buildPrompt(req.args, req.cwd);
|
|
3101
|
+
assertPromptIsSendable(prompt);
|
|
3102
|
+
const pref = this.prefs.load();
|
|
3103
|
+
if (this.cfg.askModel && !pref && !req.model && !req.conversationId) {
|
|
3104
|
+
throw new ModelNotChosenError(await this.defaultChoice(), await this.models.available());
|
|
3105
|
+
}
|
|
3106
|
+
const route = await this.routeFor(req, pref);
|
|
3107
|
+
const plan = modeFor(req.tool, req.write) === "plan";
|
|
3108
|
+
const readOnly = this.readOnlyFor(req);
|
|
3109
|
+
if (readOnly && !readOnly.enforced && this.cfg.readOnlyEnforcement === "require") {
|
|
3110
|
+
throw new AgyFailure(
|
|
3111
|
+
"agy_error",
|
|
3112
|
+
`Refusing a read-only run that cannot be confined (${readOnly.reason}). AGY_READ_ONLY_ENFORCEMENT=require forbids falling back to watching the tree.`
|
|
3113
|
+
);
|
|
3114
|
+
}
|
|
3115
|
+
const roots = [req.cwd, ...this.dirsFor(req)];
|
|
3116
|
+
const snap = this.deps.snapshot ?? snapshotTree;
|
|
3117
|
+
const fingerprint = async () => combineSnapshots(await Promise.all(roots.map((r) => snap(r))));
|
|
3118
|
+
return this.admission.run(
|
|
3119
|
+
req.conversationId,
|
|
3120
|
+
async () => {
|
|
3121
|
+
this.ledger.assertWithinBudget();
|
|
3122
|
+
const before = plan ? await fingerprint() : { method: "none" };
|
|
3123
|
+
let result;
|
|
3124
|
+
try {
|
|
3125
|
+
result = await this.attemptWithInventoryRefresh(req, prompt, route);
|
|
3126
|
+
} catch (err) {
|
|
3127
|
+
if (plan && err instanceof Error && treeChanged(before, await fingerprint())) {
|
|
3128
|
+
err.message = `${err.message}
|
|
3129
|
+
|
|
3130
|
+
${treeMovedWarning(readOnly)}`;
|
|
3131
|
+
}
|
|
3132
|
+
throw err;
|
|
3133
|
+
}
|
|
3134
|
+
if (!plan) return result;
|
|
3135
|
+
const wrote = treeChanged(before, await fingerprint());
|
|
3136
|
+
const watched = readOnly ? { ...result, readOnly } : result;
|
|
3137
|
+
return wrote === void 0 ? watched : { ...watched, wroteInReadOnlyMode: wrote };
|
|
3138
|
+
},
|
|
3139
|
+
req.signal
|
|
3140
|
+
);
|
|
3141
|
+
}
|
|
3142
|
+
/**
|
|
3143
|
+
* The models to try, in order, each with the `--effort` it will be sent.
|
|
3144
|
+
*
|
|
3145
|
+
* A requested effort belongs to the primary model only — the caller's
|
|
3146
|
+
* `model`, else the user's `set_model` choice, else the chain's head.
|
|
3147
|
+
* Re-tiering the fallbacks as well would turn "Flash (Medium)" back into the
|
|
3148
|
+
* "Flash (High)" that just hit its quota, so they keep the tier their name
|
|
3149
|
+
* carries. No effort is invented for an untiered fallback.
|
|
3150
|
+
*/
|
|
3151
|
+
async routeFor(req, pref) {
|
|
3152
|
+
if (req.conversationId && !req.model) {
|
|
3153
|
+
if (req.effort) {
|
|
3154
|
+
throw new InvalidRequestError(
|
|
3155
|
+
"An effort-only follow_up cannot be verified because this bridge does not know the conversation's current model. Include its listed model ID (or a family selector) with the effort, or omit effort to preserve the conversation's choice."
|
|
3156
|
+
);
|
|
3157
|
+
}
|
|
3158
|
+
return { candidates: [{}] };
|
|
3159
|
+
}
|
|
3160
|
+
const available = await this.models.available();
|
|
3161
|
+
if (req.model) {
|
|
3162
|
+
if (available)
|
|
3163
|
+
return { candidates: [await this.selection(req.model, req.effort, available)] };
|
|
3164
|
+
if (!/^[a-z0-9][a-z0-9._-]*$/.test(req.model)) {
|
|
3165
|
+
throw new InvalidRequestError(
|
|
3166
|
+
"Model discovery is unavailable, so a bridge selector or display label cannot be converted to a CLI ID. Check agy models or provide an exact CLI model ID; nothing was dispatched."
|
|
3167
|
+
);
|
|
3168
|
+
}
|
|
3169
|
+
const resolution2 = await this.models.resolveChain({ explicit: req.model, chain: [] });
|
|
3170
|
+
const pick = await this.models.forEffort(resolution2.models[0], req.effort);
|
|
3171
|
+
return { candidates: [pick ?? { model: resolution2.models[0] }], note: resolution2.note };
|
|
3172
|
+
}
|
|
3173
|
+
if (pref) {
|
|
3174
|
+
if (!available || !resolveEntry(pref.model, available)) {
|
|
3175
|
+
throw new InvalidRequestError(
|
|
3176
|
+
`Saved model "${pref.model}" cannot be verified in agy models. No replacement was chosen and the saved preference was kept. Run agy models, then call set_model with an available model ID to recover.`
|
|
3177
|
+
);
|
|
3178
|
+
}
|
|
3179
|
+
const saved = available.find((m) => m.id === resolveEntry(pref.model, available));
|
|
3180
|
+
if (pref.effort && saved?.effort !== pref.effort) {
|
|
3181
|
+
throw new InvalidRequestError(
|
|
3182
|
+
`Saved model "${pref.model}" and effort "${pref.effort}" disagree with the listing. Call set_model with the exact variant you intend; the preference was kept unchanged.`
|
|
3183
|
+
);
|
|
3184
|
+
}
|
|
3185
|
+
}
|
|
3186
|
+
const resolution = await this.models.resolveChain({
|
|
3187
|
+
chain: [...pref ? [pref.model] : [], ...req.tool.chain ?? []],
|
|
3188
|
+
defaultModel: this.cfg.defaultModel
|
|
3189
|
+
});
|
|
3190
|
+
const tierOf = (id) => available?.find((m) => m.id === id)?.effort;
|
|
3191
|
+
const candidates = [];
|
|
3192
|
+
for (const [i, model] of resolution.models.entries()) {
|
|
3193
|
+
if (!model) {
|
|
3194
|
+
candidates.push({});
|
|
3195
|
+
continue;
|
|
3196
|
+
}
|
|
3197
|
+
const primaryEffort = req.effort ?? (pref ? void 0 : this.cfg.defaultEffort);
|
|
3198
|
+
const pick = i === 0 ? await this.models.forEffort(model, primaryEffort) : tierOf(model) ? { model } : await this.models.forEffort(model, void 0);
|
|
3199
|
+
const candidate = pick ?? { model };
|
|
3200
|
+
if (!candidates.some((c) => c.model === candidate.model)) candidates.push(candidate);
|
|
3201
|
+
}
|
|
3202
|
+
return { candidates, ...resolution.note ? { note: resolution.note } : {} };
|
|
3203
|
+
}
|
|
3204
|
+
/** Configured policy and effective IDs are distinct status facts. */
|
|
3205
|
+
async effectiveRoutes() {
|
|
3206
|
+
const preference = this.prefs.load();
|
|
3207
|
+
const rows = [];
|
|
3208
|
+
for (const tool of TOOLS) {
|
|
3209
|
+
if (!tool.chain) continue;
|
|
3210
|
+
try {
|
|
3211
|
+
const route = await this.routeFor({ tool, args: {}, cwd: "", timeoutSec: 0 }, preference);
|
|
3212
|
+
rows.push({
|
|
3213
|
+
tool: tool.name,
|
|
3214
|
+
models: route.candidates.map((c) => c.model ?? "agy default (unverified)")
|
|
3215
|
+
});
|
|
3216
|
+
} catch (error) {
|
|
3217
|
+
rows.push({ tool: tool.name, models: [], error: error.message });
|
|
3218
|
+
}
|
|
3219
|
+
}
|
|
3220
|
+
return rows;
|
|
3221
|
+
}
|
|
3222
|
+
/**
|
|
3223
|
+
* The single exit through which every answer leaves this bridge.
|
|
3224
|
+
*
|
|
3225
|
+
* Order matters and is the reason both steps live here rather than in the
|
|
3226
|
+
* runner: redaction runs on the whole answer first, then truncation cuts it.
|
|
3227
|
+
* The other way round, a secret that straddled the cut point was split into
|
|
3228
|
+
* two halves that no longer matched any credential shape, and survived.
|
|
3229
|
+
* Routing both through one funnel also means the warm-session paths, which
|
|
3230
|
+
* never touch the runner, are scrubbed and capped exactly like a cold run.
|
|
3231
|
+
*/
|
|
3232
|
+
finish(partial) {
|
|
3233
|
+
const scrubbed = this.cfg.redact ? redact(partial.output) : { text: partial.output, count: 0 };
|
|
3234
|
+
const structured = this.cfg.redact && partial.structuredOutput !== void 0 ? redactDeep(partial.structuredOutput) : void 0;
|
|
3235
|
+
const cut = truncate(scrubbed.text, this.cfg.maxOutputChars);
|
|
3236
|
+
return {
|
|
3237
|
+
...partial,
|
|
3238
|
+
...structured ? { structuredOutput: structured.value } : {},
|
|
3239
|
+
output: cut.text,
|
|
3240
|
+
...cut.from !== void 0 ? { truncatedFrom: cut.from } : {},
|
|
3241
|
+
redactions: scrubbed.count + (structured?.count ?? 0)
|
|
3242
|
+
};
|
|
3243
|
+
}
|
|
3244
|
+
/**
|
|
3245
|
+
* A resident session runs with the conversation's own model, in plan mode,
|
|
3246
|
+
* so it can only stand in for a call that asks for nothing else.
|
|
3247
|
+
*/
|
|
3248
|
+
warmEligible(req) {
|
|
3249
|
+
return this.warm.enabled && req.conversationId !== void 0 && !req.jsonSchema && !req.model && !req.effort && modeFor(req.tool, req.write) === "plan";
|
|
3250
|
+
}
|
|
3251
|
+
/**
|
|
3252
|
+
* Invalidates discovery after an invalid-model failure for the next deliberate
|
|
3253
|
+
* call. Error text alone never authorizes replay of a dispatched turn.
|
|
3254
|
+
*/
|
|
3255
|
+
async attemptWithInventoryRefresh(req, prompt, route) {
|
|
3256
|
+
try {
|
|
3257
|
+
return await this.attempt(req, prompt, route);
|
|
3258
|
+
} catch (err) {
|
|
3259
|
+
const cause = err instanceof NotRepeatedError ? err.cause : err;
|
|
3260
|
+
if (cause instanceof AgyFailure && cause.kind === "invalid_model") this.models.invalidate();
|
|
3261
|
+
throw err;
|
|
3262
|
+
}
|
|
3263
|
+
}
|
|
3264
|
+
/** Legacy releases stored display labels; honor a uniquely mapped label too. */
|
|
3265
|
+
async coolingFor(model) {
|
|
3266
|
+
const available = await this.models.available();
|
|
3267
|
+
const row = available?.find((item) => item.id === model);
|
|
3268
|
+
const aliases = /* @__PURE__ */ new Set([model]);
|
|
3269
|
+
if (row && available?.filter((item) => item.name === row.name).length === 1)
|
|
3270
|
+
aliases.add(row.name);
|
|
3271
|
+
const longest = this.cooldowns.active().find((entry) => aliases.has(entry.model));
|
|
3272
|
+
return longest ? this.cooldowns.describe(longest.model) : void 0;
|
|
3273
|
+
}
|
|
3274
|
+
async attempt(req, prompt, route) {
|
|
3275
|
+
const attempts = [];
|
|
3276
|
+
if (this.warmEligible(req)) {
|
|
3277
|
+
const conversationId = req.conversationId;
|
|
3278
|
+
try {
|
|
3279
|
+
this.ledger.assertWithinBudget();
|
|
3280
|
+
const confineTo = this.confineFor(req);
|
|
3281
|
+
const envelope = await this.warm.turn(conversationId, req.cwd, prompt, {
|
|
3282
|
+
timeoutMs: req.timeoutSec * 1e3,
|
|
3283
|
+
dirs: this.dirsFor(req),
|
|
3284
|
+
slashCommands: req.slashCommands,
|
|
3285
|
+
sandbox: req.sandbox,
|
|
3286
|
+
...confineTo ? { confineTo } : {},
|
|
3287
|
+
...req.signal ? { signal: req.signal } : {},
|
|
3288
|
+
...req.onProgress ? {
|
|
3289
|
+
onProgress: (text2) => req.onProgress?.({ text: text2, stepIndex: 0, stepType: "agent_response", tokens: 0 })
|
|
3290
|
+
} : {}
|
|
3291
|
+
});
|
|
3292
|
+
this.ledger.record(void 0, envelope.usage, envelope.usageKnown);
|
|
3293
|
+
const classified = classifyRun({ envelope, exitCode: 0, stderr: "" });
|
|
3294
|
+
if (envelope.finishedReason === "print_timeout" || !classified) {
|
|
3295
|
+
return this.finish({
|
|
3296
|
+
output: envelope.response.trim(),
|
|
3297
|
+
attempts,
|
|
3298
|
+
sessionId: envelope.conversationId ?? conversationId,
|
|
3299
|
+
...continuationOf(conversationId, envelope.conversationId),
|
|
3300
|
+
timedOut: envelope.finishedReason === "print_timeout",
|
|
3301
|
+
...envelope.finishedReason ? { finishedReason: envelope.finishedReason } : {},
|
|
3302
|
+
deniedActions: envelope.deniedActions,
|
|
3303
|
+
usage: envelope.usage,
|
|
3304
|
+
usageKnown: envelope.usageKnown,
|
|
3305
|
+
...envelope.structuredOutput !== void 0 ? { structuredOutput: envelope.structuredOutput } : {},
|
|
3306
|
+
numTurns: envelope.numTurns,
|
|
3307
|
+
warm: true
|
|
3308
|
+
});
|
|
3309
|
+
}
|
|
3310
|
+
const failure = new AgyFailure(
|
|
3311
|
+
classified?.kind ?? "agy_error",
|
|
3312
|
+
classified?.message ?? "The resident agy session did not complete."
|
|
3313
|
+
);
|
|
3314
|
+
failure.usage = envelope.usage;
|
|
3315
|
+
failure.usageKnown = envelope.usageKnown;
|
|
3316
|
+
failure.partialOutput = envelope.response;
|
|
3317
|
+
failure.conversationId = envelope.conversationId ?? conversationId;
|
|
3318
|
+
failure.finishedReason = envelope.finishedReason;
|
|
3319
|
+
failure.numTurns = envelope.numTurns;
|
|
3320
|
+
failure.deniedActions = envelope.deniedActions;
|
|
3321
|
+
failure.structuredOutput = envelope.structuredOutput;
|
|
3322
|
+
await this.warm.invalidate(conversationId);
|
|
3323
|
+
throw new NotRepeatedError(failure, "retried");
|
|
3324
|
+
} catch (err) {
|
|
3325
|
+
if (err instanceof WarmTimeout) {
|
|
3326
|
+
this.ledger.record(void 0, err.usage ?? EMPTY_USAGE, Boolean(err.usage));
|
|
3327
|
+
return this.finish({
|
|
3328
|
+
output: err.text.trim(),
|
|
3329
|
+
attempts,
|
|
3330
|
+
sessionId: err.conversationId ?? conversationId,
|
|
3331
|
+
timedOut: true,
|
|
3332
|
+
finishedReason: err.finishedReason ?? "print_timeout",
|
|
3333
|
+
deniedActions: err.deniedActions ?? [],
|
|
3334
|
+
usage: err.usage ?? EMPTY_USAGE,
|
|
3335
|
+
usageKnown: Boolean(err.usage),
|
|
3336
|
+
numTurns: err.numTurns ?? 0,
|
|
3337
|
+
warm: true
|
|
3338
|
+
});
|
|
3339
|
+
}
|
|
3340
|
+
if (err instanceof WarmUnavailable) {
|
|
3341
|
+
attempts.push(`warm session unavailable (${err.message}); ran a fresh agy process`);
|
|
3342
|
+
} else {
|
|
3343
|
+
this.recordFailedSpend(void 0, err);
|
|
3344
|
+
throw err;
|
|
3345
|
+
}
|
|
3346
|
+
}
|
|
3347
|
+
}
|
|
3348
|
+
for (const [i, { model, effort: effort2 }] of route.candidates.entries()) {
|
|
3349
|
+
const pinned = i === 0 && req.model !== void 0 && req.modelOrigin !== "automatic";
|
|
3350
|
+
const cooling = model && !pinned ? await this.coolingFor(model) : void 0;
|
|
3351
|
+
if (cooling !== void 0) {
|
|
3352
|
+
attempts.push(`${model}: quota cooldown, ${cooling} left`);
|
|
3353
|
+
continue;
|
|
3354
|
+
}
|
|
3355
|
+
try {
|
|
3356
|
+
return await this.runOnce(req, prompt, model, effort2, attempts, route.note);
|
|
3357
|
+
} catch (err) {
|
|
3358
|
+
this.recordFailedSpend(model, err);
|
|
3359
|
+
const quota = err instanceof QuotaError || err instanceof AgyFailure && err.policy.failover;
|
|
3360
|
+
if (!quota || !model) {
|
|
3361
|
+
if (err instanceof AgyFailure && (err.kind === "network" || err.kind === "invalid_model")) {
|
|
3362
|
+
throw new NotRepeatedError(err, "retried");
|
|
3363
|
+
}
|
|
3364
|
+
throw err;
|
|
3365
|
+
}
|
|
3366
|
+
const reset = err instanceof QuotaError ? err.resetSeconds : void 0;
|
|
3367
|
+
this.cooldowns.set(model, reset);
|
|
3368
|
+
throw new NotRepeatedError(err, "failed over to the next model");
|
|
3369
|
+
}
|
|
3370
|
+
}
|
|
3371
|
+
throw new Error(
|
|
3372
|
+
`All candidate models are quota-exhausted or cooling down:
|
|
3373
|
+
${attempts.map((a) => `- ${a}`).join("\n")}
|
|
3374
|
+
Retry after the quota resets, or pass an explicit \`model\`.`
|
|
3375
|
+
);
|
|
3376
|
+
}
|
|
3377
|
+
/** A failed run still spent tokens; the budget has to see them. */
|
|
3378
|
+
recordFailedSpend(model, err) {
|
|
3379
|
+
const failure = err;
|
|
3380
|
+
if (failure?.usage || failure?.usageKnown === false) {
|
|
3381
|
+
this.ledger.record(model, failure.usage ?? EMPTY_USAGE, failure.usageKnown !== false);
|
|
3382
|
+
}
|
|
3383
|
+
}
|
|
3384
|
+
async runOnce(req, prompt, model, effort2, attempts, note) {
|
|
3385
|
+
if (req.conversationId) await this.warm.invalidate(req.conversationId);
|
|
3386
|
+
this.ledger.assertWithinBudget();
|
|
3387
|
+
const result = await runAgy(
|
|
3388
|
+
{
|
|
3389
|
+
prompt,
|
|
3390
|
+
cwd: req.cwd,
|
|
3391
|
+
...this.dirsFor(req).length ? { dirs: this.dirsFor(req) } : {},
|
|
3392
|
+
...model ? { model } : {},
|
|
3393
|
+
...effort2 ? { effort: effort2 } : {},
|
|
3394
|
+
mode: modeFor(req.tool, req.write),
|
|
3395
|
+
...req.sandbox !== void 0 ? { sandbox: req.sandbox } : {},
|
|
3396
|
+
...req.slashCommands !== void 0 ? { slashCommands: req.slashCommands } : {},
|
|
3397
|
+
...req.jsonSchema ? { jsonSchema: req.jsonSchema } : {},
|
|
3398
|
+
...req.conversationId ? { conversationId: req.conversationId } : {},
|
|
3399
|
+
timeoutSec: req.timeoutSec,
|
|
3400
|
+
...req.signal ? { signal: req.signal } : {},
|
|
3401
|
+
env: this.childEnv(),
|
|
3402
|
+
...req.onProgress ? { onProgress: req.onProgress } : {},
|
|
3403
|
+
...this.confineFor(req) ? { confineTo: this.confineFor(req) } : {}
|
|
3404
|
+
},
|
|
3405
|
+
this.cfg,
|
|
3406
|
+
this.caps,
|
|
3407
|
+
{
|
|
3408
|
+
spawn: this.deps.spawn,
|
|
3409
|
+
confinement: this.deps.confinement,
|
|
3410
|
+
timing: this.deps.timing,
|
|
3411
|
+
track: (proc) => {
|
|
3412
|
+
this.live.add(proc);
|
|
3413
|
+
return () => this.live.delete(proc);
|
|
3414
|
+
}
|
|
3415
|
+
}
|
|
3416
|
+
);
|
|
3417
|
+
this.ledger.record(model, result.usage, result.usageKnown);
|
|
3418
|
+
return this.finish({
|
|
3419
|
+
output: result.output,
|
|
3420
|
+
...model ? { model } : {},
|
|
3421
|
+
attempts,
|
|
3422
|
+
...note ? { note } : {},
|
|
3423
|
+
// No fallback to agy's global last-conversation cache: that file is keyed by
|
|
3424
|
+
// directory across the whole machine, so it hands back the user's own
|
|
3425
|
+
// interactive session, which follow_up would then read and append to.
|
|
3426
|
+
// A run that reports no conversation id simply has no resumable session.
|
|
3427
|
+
...result.conversationId ? { sessionId: result.conversationId } : {},
|
|
3428
|
+
...continuationOf(req.conversationId, result.conversationId),
|
|
3429
|
+
timedOut: result.timedOut,
|
|
3430
|
+
...result.finishedReason ? { finishedReason: result.finishedReason } : {},
|
|
3431
|
+
deniedActions: result.deniedActions,
|
|
3432
|
+
usage: result.usage,
|
|
3433
|
+
usageKnown: result.usageKnown,
|
|
3434
|
+
...result.structuredOutput !== void 0 ? { structuredOutput: result.structuredOutput } : {},
|
|
3435
|
+
numTurns: result.numTurns,
|
|
3436
|
+
warm: false
|
|
3437
|
+
});
|
|
3438
|
+
}
|
|
3439
|
+
/**
|
|
3440
|
+
* Fans one prompt out to several models, or several prompts out to the
|
|
3441
|
+
* automatic route. Each leg goes through `run`, so the semaphore, cooldowns,
|
|
3442
|
+
* budget and depth guard all still apply.
|
|
3443
|
+
*/
|
|
3444
|
+
async runMany(req, legs, opts = {}) {
|
|
3445
|
+
const chosen = req.model !== void 0 || opts.modelsChosen === true;
|
|
3446
|
+
if (this.cfg.askModel && !this.prefs.load() && !chosen && !req.conversationId) {
|
|
3447
|
+
throw new ModelNotChosenError(await this.defaultChoice(), await this.models.available());
|
|
3448
|
+
}
|
|
3449
|
+
let prepared = legs;
|
|
3450
|
+
if (legs.some((leg) => leg.model !== void 0)) {
|
|
3451
|
+
const available = await this.models.available();
|
|
3452
|
+
if (!available) {
|
|
3453
|
+
throw new InvalidRequestError(
|
|
3454
|
+
"Cannot verify council membership because agy models could not be read. Nothing was dispatched. Check the CLI and authentication, then try again."
|
|
3455
|
+
);
|
|
3456
|
+
}
|
|
3457
|
+
prepared = [];
|
|
3458
|
+
const effective = /* @__PURE__ */ new Set();
|
|
3459
|
+
const unavailable = [];
|
|
3460
|
+
for (const leg of legs) {
|
|
3461
|
+
if (!leg.model) {
|
|
3462
|
+
prepared.push(leg);
|
|
3463
|
+
continue;
|
|
3464
|
+
}
|
|
3465
|
+
if (leg.automatic && !resolveEntry(leg.model, available)) {
|
|
3466
|
+
unavailable.push(leg.label);
|
|
3467
|
+
continue;
|
|
3468
|
+
}
|
|
3469
|
+
const pick = await this.selection(leg.model, req.effort, available);
|
|
3470
|
+
const id = pick.model;
|
|
3471
|
+
if (effective.has(id)) {
|
|
3472
|
+
if (leg.automatic) continue;
|
|
3473
|
+
throw new InvalidRequestError(
|
|
3474
|
+
`Council selections resolve to the same model "${id}" more than once. Choose distinct listed variants; nothing was dispatched.`
|
|
3475
|
+
);
|
|
3476
|
+
}
|
|
3477
|
+
effective.add(id);
|
|
3478
|
+
prepared.push({ ...leg, model: id });
|
|
3479
|
+
}
|
|
3480
|
+
if (!prepared.length) {
|
|
3481
|
+
throw new InvalidRequestError(
|
|
3482
|
+
"None of the default council's models are listed by this agy account. Pass explicit available models or use a single-model call; nothing was dispatched."
|
|
3483
|
+
);
|
|
3484
|
+
}
|
|
3485
|
+
for (const label of unavailable)
|
|
3486
|
+
prepared.push({ label: `${label} (unavailable)`, automatic: true });
|
|
3487
|
+
}
|
|
3488
|
+
return Promise.all(
|
|
3489
|
+
prepared.map(async (leg) => {
|
|
3490
|
+
if (leg.automatic && !leg.model)
|
|
3491
|
+
return {
|
|
3492
|
+
label: leg.label,
|
|
3493
|
+
error: "Not offered in the current model inventory; skipped without dispatch."
|
|
3494
|
+
};
|
|
3495
|
+
try {
|
|
3496
|
+
const {
|
|
3497
|
+
tasks: _tasks,
|
|
3498
|
+
models: _models,
|
|
3499
|
+
...singleArgs
|
|
3500
|
+
} = req.args;
|
|
3501
|
+
const delegation = await this.run({
|
|
3502
|
+
...req,
|
|
3503
|
+
...leg.model ? { model: leg.model } : {},
|
|
3504
|
+
...leg.model ? { modelOrigin: leg.automatic ? "automatic" : "explicit" } : {},
|
|
3505
|
+
// The model is now a canonical fixed variant. Its tier was already
|
|
3506
|
+
// reconciled above; a second inherited effort must not re-tier it.
|
|
3507
|
+
...leg.model ? { effort: void 0 } : {},
|
|
3508
|
+
// `!== undefined`, not truthiness: an empty task used to fall back to
|
|
3509
|
+
// the joined prompt of every task, running all the others again.
|
|
3510
|
+
...leg.prompt !== void 0 ? { args: { ...singleArgs, prompt: leg.prompt } } : {}
|
|
3511
|
+
});
|
|
3512
|
+
return { label: leg.label, delegation };
|
|
3513
|
+
} catch (err) {
|
|
3514
|
+
return { label: leg.label, error: err.message };
|
|
3515
|
+
}
|
|
3516
|
+
})
|
|
3517
|
+
);
|
|
3518
|
+
}
|
|
3519
|
+
};
|
|
3520
|
+
|
|
3521
|
+
// src/server.ts
|
|
3522
|
+
import { z as z2 } from "zod";
|
|
3523
|
+
var SET_MODEL_ARGS = z2.object({
|
|
3524
|
+
model: z2.string().min(1).optional(),
|
|
3525
|
+
effort: z2.enum(EFFORTS).optional()
|
|
3526
|
+
});
|
|
3527
|
+
var VERSION = JSON.parse(readFileSync3(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
3528
|
+
function makeNonce() {
|
|
3529
|
+
return randomBytes(6).toString("hex");
|
|
3530
|
+
}
|
|
3531
|
+
function deniedNote(d) {
|
|
3532
|
+
if (d.deniedActions.length === 0) return void 0;
|
|
3533
|
+
const names = [...new Set(d.deniedActions.map((a) => a.displayName || a.action))];
|
|
3534
|
+
return `agy answered but ${d.deniedActions.length} tool action(s) were auto-denied (${names.join(", ")}) \u2014 the answer may be incomplete. Read-only tools ask agy to deny writes and commands, so this is expected for a review; for work that must run commands, use \`delegate\` with \`write: true\`.`;
|
|
3535
|
+
}
|
|
3536
|
+
function renderDelegation(d, timeoutSec, nonce) {
|
|
3537
|
+
const meta = [
|
|
3538
|
+
`model: ${d.model ?? (d.warm ? "the conversation's own" : "agy default")}`
|
|
3539
|
+
];
|
|
3540
|
+
if (d.warm) meta.push("warm session");
|
|
3541
|
+
if (d.readOnly) {
|
|
3542
|
+
meta.push(
|
|
3543
|
+
d.readOnly.enforced ? "read-only: enforced, writes into the workspace blocked" : `read-only: watched, not enforced (${d.readOnly.reason})`
|
|
3544
|
+
);
|
|
3545
|
+
}
|
|
3546
|
+
if (d.note) meta.push(`note: ${d.note}`);
|
|
3547
|
+
if (d.attempts.length) meta.push(`failover: ${d.attempts.join("; ")}`);
|
|
3548
|
+
if (d.sessionId) meta.push(`session: ${d.sessionId} (use follow_up to continue)`);
|
|
3549
|
+
if (d.finishedReason) meta.push(`finished reason: ${d.finishedReason}`);
|
|
3550
|
+
if (d.usage.totalTokens) meta.push(`tokens: ${d.usage.totalTokens}`);
|
|
3551
|
+
if (d.usageKnown === false)
|
|
3552
|
+
meta.push("complete usage unavailable; reported tokens are a lower bound");
|
|
3553
|
+
if (d.redactions) meta.push(`redacted ${d.redactions} credential-shaped string(s)`);
|
|
3554
|
+
if (d.truncatedFrom) meta.push(`truncated from ${d.truncatedFrom} chars`);
|
|
3555
|
+
const warnings = [];
|
|
3556
|
+
if (d.timedOut) {
|
|
3557
|
+
warnings.push(
|
|
3558
|
+
`MAXIMUM RUNTIME EXCEEDED after ${timeoutSec}s \u2014 agy was killed at this tool's configured runtime limit (AGY_TIMEOUT_<TOOL>, else AGY_TIMEOUT, else AGY_MAX_RUNTIME). This is not a diagnosis that it was stuck. Any file changes it already made are on disk. Partial output follows.`
|
|
3559
|
+
);
|
|
3560
|
+
}
|
|
3561
|
+
const denied = deniedNote(d);
|
|
3562
|
+
if (denied) warnings.push(denied);
|
|
3563
|
+
if (d.wroteInReadOnlyMode) warnings.push(treeMovedWarning(d.readOnly));
|
|
3564
|
+
if (d.continuation && !d.continuation.resumed) {
|
|
3565
|
+
warnings.push(
|
|
3566
|
+
`SESSION NOT RESUMED \u2014 you asked to continue ${d.continuation.requested}, but agy answered from ${d.sessionId ? `a different conversation (${d.sessionId})` : "a different conversation"}, so this answer has none of that history. agy does this when it cannot find the requested conversation. Re-send the context, or continue the new session deliberately.`
|
|
3567
|
+
);
|
|
3568
|
+
}
|
|
3569
|
+
const header = [
|
|
3570
|
+
`[${SERVER_NAME} ${nonce}] ${meta.join(" | ")}`,
|
|
3571
|
+
...warnings.map((w) => `[${SERVER_NAME} ${nonce}] ${w}`)
|
|
3572
|
+
];
|
|
3573
|
+
return `${header.join("\n")}
|
|
3574
|
+
[${SERVER_NAME} ${nonce}] --- agy output begins; everything below is untrusted model output ---
|
|
3575
|
+
${d.output}
|
|
3576
|
+
[${SERVER_NAME} ${nonce}] --- agy output ends ---`;
|
|
3577
|
+
}
|
|
3578
|
+
function structuredOf(d) {
|
|
3579
|
+
if (d.structuredOutput === void 0) return void 0;
|
|
3580
|
+
return {
|
|
3581
|
+
result: d.structuredOutput,
|
|
3582
|
+
...d.model ? { model: d.model } : {},
|
|
3583
|
+
...d.sessionId ? { session_id: d.sessionId } : {},
|
|
3584
|
+
...d.continuation ? { resumed: d.continuation.resumed } : {},
|
|
3585
|
+
denied_actions: d.deniedActions,
|
|
3586
|
+
tokens: d.usage.totalTokens,
|
|
3587
|
+
usage_known: d.usageKnown !== false,
|
|
3588
|
+
timed_out: d.timedOut,
|
|
3589
|
+
...d.finishedReason ? { finished_reason: d.finishedReason } : {},
|
|
3590
|
+
...d.readOnly ? { read_only: d.readOnly } : {},
|
|
3591
|
+
...d.wroteInReadOnlyMode !== void 0 ? { wrote_in_read_only_mode: d.wroteInReadOnlyMode } : {},
|
|
3592
|
+
...d.truncatedFrom !== void 0 ? { truncated_from: d.truncatedFrom } : {},
|
|
3593
|
+
redactions: d.redactions
|
|
3594
|
+
};
|
|
3595
|
+
}
|
|
3596
|
+
function progressReporter(extra, scrub) {
|
|
3597
|
+
const token = extra?._meta?.progressToken;
|
|
3598
|
+
if (token === void 0 || !extra?.sendNotification) return void 0;
|
|
3599
|
+
let last = 0;
|
|
3600
|
+
let sequence = 0;
|
|
3601
|
+
return (p) => {
|
|
3602
|
+
const now = Date.now();
|
|
3603
|
+
if (now - last < 1e3) return;
|
|
3604
|
+
last = now;
|
|
3605
|
+
const message = `agy ${p.stepType}: ${p.text}`;
|
|
3606
|
+
extra.sendNotification?.({
|
|
3607
|
+
method: "notifications/progress",
|
|
3608
|
+
params: {
|
|
3609
|
+
progressToken: token,
|
|
3610
|
+
// Provider step indices restart on another leg and warm updates use
|
|
3611
|
+
// zero. MCP progress must increase for the whole request token.
|
|
3612
|
+
progress: ++sequence,
|
|
3613
|
+
// Redact before slicing: this is live model output, and it reached the
|
|
3614
|
+
// client unscrubbed even with AGY_REDACT on.
|
|
3615
|
+
message: (scrub ? redact(message).text : message).slice(-200)
|
|
3616
|
+
}
|
|
3617
|
+
}).catch(() => {
|
|
3618
|
+
});
|
|
3619
|
+
};
|
|
3620
|
+
}
|
|
3621
|
+
function renderStatus(status, available, nonce, effective = []) {
|
|
3622
|
+
const lines = [
|
|
3623
|
+
`agy ${status.agyVersion}`,
|
|
3624
|
+
status.preference ? `model choice (set_model): ${status.preference.model}` + (status.preference.effort ? ` at ${status.preference.effort} effort` : "") + ", placed ahead of every tool chain" : status.askModel ? "model choice (set_model): none yet \u2014 tools refuse to run until the user picks one" : "model choice (set_model): none; AGY_ASK_MODEL is off, tool chains route on their own",
|
|
3625
|
+
status.missingFlags.length ? `flags this agy lacks: ${status.missingFlags.join(", ")}` : "all flags this bridge uses are supported",
|
|
3626
|
+
`runs: ${status.inFlight} in flight, ${status.queued} queued`,
|
|
3627
|
+
`delegation depth: ${status.depth}`,
|
|
3628
|
+
status.budget !== void 0 ? `reported tokens: ${status.spent} of ${status.budget} admission budget (in-flight/unknown usage may exceed it)` : `reported tokens: ${status.spent} (no budget set)`,
|
|
3629
|
+
`warm sessions: ${status.warm.resident} resident`,
|
|
3630
|
+
`read-only runs: ${status.readOnly.enforced ? "enforced, writes into their roots blocked" : status.readOnly.policy === "require" ? `refused, they cannot be confined \u2014 ${status.readOnly.reason}` : `watched, not enforced \u2014 ${status.readOnly.reason}`} (AGY_READ_ONLY_ENFORCEMENT=${status.readOnly.policy})`
|
|
3631
|
+
];
|
|
3632
|
+
if (status.usage.length) {
|
|
3633
|
+
lines.push("", "usage by model:");
|
|
3634
|
+
for (const row of status.usage) {
|
|
3635
|
+
lines.push(
|
|
3636
|
+
` ${row.model}: ${row.runs} run(s), ${row.totalTokens} reported tokens${row.unknownRuns ? `, ${row.unknownRuns} run(s) with incomplete usage` : ""}`
|
|
3637
|
+
);
|
|
3638
|
+
}
|
|
3639
|
+
}
|
|
3640
|
+
lines.push("", status.cooldowns.length ? "quota cooldowns:" : "quota cooldowns: none");
|
|
3641
|
+
for (const c of status.cooldowns) lines.push(` ${c.model}: ${c.secondsLeft}s left`);
|
|
3642
|
+
lines.push("", "configured tool chains (selectors, not observed model use):");
|
|
3643
|
+
for (const tool of TOOLS) {
|
|
3644
|
+
if (tool.chain) lines.push(` ${tool.name}: ${tool.chain.join(" -> ")}`);
|
|
3645
|
+
}
|
|
3646
|
+
lines.push("", "effective single-call routes (listed IDs, subject to cooldown):");
|
|
3647
|
+
for (const row of effective) lines.push(` ${row.tool}: ${row.error ?? row.models.join(" -> ")}`);
|
|
3648
|
+
lines.push("default council policy (separate paid legs): " + COUNCIL.join(", "));
|
|
3649
|
+
lines.push("", available ? "models agy offers:" : "models agy offers: could not be listed");
|
|
3650
|
+
for (const m of available ?? []) lines.push(` ${m.id} \u2014 ${m.name}`);
|
|
3651
|
+
return `[${SERVER_NAME} ${nonce}] status
|
|
3652
|
+
${lines.join("\n")}`;
|
|
3653
|
+
}
|
|
3654
|
+
var COUNCIL = ["gemini-flash@latest-high", "gemini-pro@latest-high", "claude-opus@latest"];
|
|
3655
|
+
function failureText(text2, cfg) {
|
|
3656
|
+
return truncate(cfg.redact ? redact(text2).text : text2, cfg.maxOutputChars);
|
|
3657
|
+
}
|
|
3658
|
+
function fanoutLegs(args) {
|
|
3659
|
+
const tasks = Array.isArray(args.tasks) ? args.tasks : [];
|
|
3660
|
+
const models = Array.isArray(args.models) ? args.models : [];
|
|
3661
|
+
if (tasks.length) {
|
|
3662
|
+
return tasks.map((prompt, i) => ({ prompt, label: `task ${i + 1}` }));
|
|
3663
|
+
}
|
|
3664
|
+
if (models.length) return models.map((model) => ({ model, label: model }));
|
|
3665
|
+
if (typeof args.model === "string") return [{ model: args.model, label: args.model }];
|
|
3666
|
+
return COUNCIL.map((model) => ({ model, label: model, automatic: true }));
|
|
3667
|
+
}
|
|
3668
|
+
function renderFanout(results, timeoutSec, nonce, cfg) {
|
|
3669
|
+
const parts = results.map(
|
|
3670
|
+
(r) => r.delegation ? `[${SERVER_NAME} ${nonce}] leg: ${r.label}
|
|
3671
|
+
${renderDelegation(r.delegation, timeoutSec, nonce)}` : `[${SERVER_NAME} ${nonce}] leg: ${r.label}
|
|
3672
|
+
[${SERVER_NAME} ${nonce}] failed: ${failureText(r.error ?? "Unknown failure", cfg).text}`
|
|
3673
|
+
);
|
|
3674
|
+
const answered = results.filter((r) => r.delegation).length;
|
|
3675
|
+
return `[${SERVER_NAME} ${nonce}] fan-out: ${answered} of ${results.length} legs answered. Compare them yourself \u2014 agreement between models is evidence, not proof.
|
|
3676
|
+
|
|
3677
|
+
` + parts.join("\n\n");
|
|
3678
|
+
}
|
|
3679
|
+
async function askUserForModel(delegator, elicit) {
|
|
3680
|
+
const [suggested, available] = await Promise.all([
|
|
3681
|
+
delegator.defaultChoice(),
|
|
3682
|
+
delegator.availableModels()
|
|
3683
|
+
]);
|
|
3684
|
+
const choices = available?.map((m) => ({ const: m.id, title: m.name })) ?? [];
|
|
3685
|
+
if (choices.length === 0)
|
|
3686
|
+
return "Cannot choose a model until agy models can be read. Nothing was dispatched.";
|
|
3687
|
+
const defaultModel = suggested?.model;
|
|
3688
|
+
const result = await elicit({
|
|
3689
|
+
mode: "form",
|
|
3690
|
+
message: (defaultModel ? `Proceed with the default \u2014 ${defaultModel} \u2014 or choose a listed variant? ` : "Choose a listed model variant. ") + "The model ID includes its tier. This choice is saved for this machine.",
|
|
3691
|
+
requestedSchema: {
|
|
3692
|
+
type: "object",
|
|
3693
|
+
properties: {
|
|
3694
|
+
model: {
|
|
3695
|
+
type: "string",
|
|
3696
|
+
title: "Model",
|
|
3697
|
+
oneOf: choices,
|
|
3698
|
+
...defaultModel ? { default: defaultModel } : {}
|
|
3699
|
+
}
|
|
3700
|
+
},
|
|
3701
|
+
required: ["model"]
|
|
3702
|
+
}
|
|
3703
|
+
});
|
|
3704
|
+
if (result.action !== "accept") {
|
|
3705
|
+
return `The user ${result.action === "decline" ? "declined" : "cancelled"} the model choice, so nothing was delegated. Ask them what they want, then call \`set_model\`, or set AGY_ASK_MODEL=false.`;
|
|
3706
|
+
}
|
|
3707
|
+
const content = result.content ?? {};
|
|
3708
|
+
const model = typeof content.model === "string" && content.model ? content.model : defaultModel;
|
|
3709
|
+
if (!model) return "No model was selected; nothing was dispatched.";
|
|
3710
|
+
await delegator.setPreference(model === defaultModel ? void 0 : model, void 0);
|
|
3711
|
+
return null;
|
|
3712
|
+
}
|
|
3713
|
+
function createToolHandler(tool, cfg, delegator, elicitFor = () => void 0) {
|
|
3714
|
+
const timeoutSec = timeoutFor(cfg, tool.name);
|
|
3715
|
+
const failed = (text2, delegationFailed = true) => ({
|
|
3716
|
+
content: [
|
|
3717
|
+
{
|
|
3718
|
+
type: "text",
|
|
3719
|
+
text: cfg.onFailure === "strict" && delegationFailed ? text2 + `
|
|
3720
|
+
|
|
3721
|
+
[${SERVER_NAME} strict mode] Delegation failed. Do NOT perform this work yourself in the main context \u2014 report the failure to the user and let them decide how to proceed.` : text2
|
|
3722
|
+
}
|
|
3723
|
+
],
|
|
3724
|
+
isError: true
|
|
3725
|
+
});
|
|
3726
|
+
const handle = async (args, extra) => {
|
|
3727
|
+
const nonce = makeNonce();
|
|
3728
|
+
const gated = async (delegate) => {
|
|
3729
|
+
try {
|
|
3730
|
+
return await delegate();
|
|
3731
|
+
} catch (err) {
|
|
3732
|
+
const elicit = elicitFor(extra);
|
|
3733
|
+
if (!(err instanceof ModelNotChosenError) || !elicit) throw err;
|
|
3734
|
+
const refusal = await askUserForModel(delegator, elicit);
|
|
3735
|
+
if (refusal) throw new Error(refusal);
|
|
3736
|
+
return await delegate();
|
|
3737
|
+
}
|
|
3738
|
+
};
|
|
3739
|
+
try {
|
|
3740
|
+
if (tool.kind === "status") {
|
|
3741
|
+
const available = await delegator.availableModels();
|
|
3742
|
+
return {
|
|
3743
|
+
content: [
|
|
3744
|
+
{
|
|
3745
|
+
type: "text",
|
|
3746
|
+
text: renderStatus(
|
|
3747
|
+
delegator.status(),
|
|
3748
|
+
available,
|
|
3749
|
+
nonce,
|
|
3750
|
+
await delegator.effectiveRoutes()
|
|
3751
|
+
)
|
|
3752
|
+
}
|
|
3753
|
+
]
|
|
3754
|
+
};
|
|
3755
|
+
}
|
|
3756
|
+
if (tool.kind === "configure") {
|
|
3757
|
+
const choice = SET_MODEL_ARGS.parse(args);
|
|
3758
|
+
const pref = await delegator.setPreference(choice.model, choice.effort);
|
|
3759
|
+
return {
|
|
3760
|
+
content: [
|
|
3761
|
+
{
|
|
3762
|
+
type: "text",
|
|
3763
|
+
text: `[${SERVER_NAME} ${nonce}] model set to ${pref.model}` + (pref.effort ? ` at ${pref.effort} effort` : "") + ". Saved for this machine; every tool routes to it first from now on."
|
|
3764
|
+
}
|
|
3765
|
+
]
|
|
3766
|
+
};
|
|
3767
|
+
}
|
|
3768
|
+
const routing = ROUTING_ARGS.parse(args);
|
|
3769
|
+
const onProgress = progressReporter(extra, cfg.redact);
|
|
3770
|
+
const base = {
|
|
3771
|
+
tool,
|
|
3772
|
+
args,
|
|
3773
|
+
cwd: routing.cwd ?? process.cwd(),
|
|
3774
|
+
...routing.dirs?.length ? { dirs: routing.dirs } : {},
|
|
3775
|
+
...routing.session_id ? { conversationId: routing.session_id } : {},
|
|
3776
|
+
...routing.model ? { model: routing.model } : {},
|
|
3777
|
+
...routing.effort ? { effort: routing.effort } : {},
|
|
3778
|
+
...routing.schema ? { jsonSchema: routing.schema } : {},
|
|
3779
|
+
...routing.slash_commands !== void 0 ? { slashCommands: routing.slash_commands } : {},
|
|
3780
|
+
...routing.write !== void 0 ? { write: routing.write } : {},
|
|
3781
|
+
...routing.sandbox !== void 0 ? { sandbox: routing.sandbox } : {},
|
|
3782
|
+
timeoutSec,
|
|
3783
|
+
...extra?.signal ? { signal: extra.signal } : {},
|
|
3784
|
+
...onProgress ? { onProgress } : {}
|
|
3785
|
+
};
|
|
3786
|
+
if (tool.kind === "fanout") {
|
|
3787
|
+
tool.schema.parse(args);
|
|
3788
|
+
const modelsChosen = Array.isArray(args.models) && args.models.length > 0;
|
|
3789
|
+
const results = await gated(
|
|
3790
|
+
() => delegator.runMany(base, fanoutLegs(args), { modelsChosen })
|
|
3791
|
+
);
|
|
3792
|
+
const text2 = renderFanout(results, timeoutSec, nonce, cfg);
|
|
3793
|
+
if (results.every((r) => r.error || r.delegation?.timedOut)) return failed(text2);
|
|
3794
|
+
return { content: [{ type: "text", text: text2 }] };
|
|
3795
|
+
}
|
|
3796
|
+
const delegation = await gated(() => delegator.run(base));
|
|
3797
|
+
const structured = structuredOf(delegation);
|
|
3798
|
+
return {
|
|
3799
|
+
content: [{ type: "text", text: renderDelegation(delegation, timeoutSec, nonce) }],
|
|
3800
|
+
...structured ? { structuredContent: structured } : {},
|
|
3801
|
+
isError: delegation.timedOut || void 0
|
|
3802
|
+
};
|
|
3803
|
+
} catch (err) {
|
|
3804
|
+
const msg = failureText(err.message, cfg).text;
|
|
3805
|
+
const invalid = err instanceof InvalidRequestError || err instanceof z2.ZodError;
|
|
3806
|
+
const cause = err instanceof NotRepeatedError ? err.cause : err;
|
|
3807
|
+
if ((cause instanceof AgyFailure || cause instanceof QuotaError) && (cause.partialOutput || cause.conversationId)) {
|
|
3808
|
+
const partial = failureText(cause.partialOutput ?? "", cfg);
|
|
3809
|
+
return {
|
|
3810
|
+
...failed(
|
|
3811
|
+
`${msg}
|
|
3812
|
+
[${SERVER_NAME} ${nonce}] incomplete response${cause.conversationId ? ` | session: ${cause.conversationId}` : ""}${cause.finishedReason ? ` | finished reason: ${cause.finishedReason}` : ""}
|
|
3813
|
+
${partial.from !== void 0 ? `[${SERVER_NAME} ${nonce}] partial output truncated from ${partial.from} chars
|
|
3814
|
+
` : ""}[${SERVER_NAME} ${nonce}] --- untrusted partial output begins ---
|
|
3815
|
+
${partial.text}
|
|
3816
|
+
[${SERVER_NAME} ${nonce}] --- untrusted partial output ends ---`,
|
|
3817
|
+
!invalid
|
|
3818
|
+
),
|
|
3819
|
+
structuredContent: {
|
|
3820
|
+
complete: false,
|
|
3821
|
+
...cause.conversationId ? { session_id: cause.conversationId } : {},
|
|
3822
|
+
...cause.finishedReason ? { finished_reason: cause.finishedReason } : {},
|
|
3823
|
+
...partial.from !== void 0 ? { partial_truncated_from: partial.from } : {},
|
|
3824
|
+
...cause.structuredOutput !== void 0 ? { partial_result: cause.structuredOutput } : {},
|
|
3825
|
+
...cause.usage ? { reported_usage: cause.usage } : {},
|
|
3826
|
+
usage_known: cause.usageKnown !== false
|
|
3827
|
+
}
|
|
3828
|
+
};
|
|
3829
|
+
}
|
|
3830
|
+
return failed(msg, !invalid);
|
|
3831
|
+
}
|
|
3832
|
+
};
|
|
3833
|
+
return async (args, extra) => {
|
|
3834
|
+
const response = await handle(args, extra);
|
|
3835
|
+
return cfg.redact ? redactDeep(response).value : response;
|
|
3836
|
+
};
|
|
3837
|
+
}
|
|
3838
|
+
async function createServer() {
|
|
3839
|
+
const cfg = loadConfig();
|
|
3840
|
+
sweepStaleLogs();
|
|
3841
|
+
const [caps, confinement] = await Promise.all([
|
|
3842
|
+
probeCapabilities(cfg.agyPath),
|
|
3843
|
+
cfg.readOnlyEnforcement === "off" ? Promise.resolve(unavailableConfinement("AGY_READ_ONLY_ENFORCEMENT is off")) : probeConfinement()
|
|
3844
|
+
]);
|
|
3845
|
+
if (!confinement.available && cfg.readOnlyEnforcement !== "off") {
|
|
3846
|
+
console.error(
|
|
3847
|
+
`${SERVER_NAME}: read-only runs cannot be confined here (${confinement.reason}); ` + (cfg.readOnlyEnforcement === "require" ? "AGY_READ_ONLY_ENFORCEMENT=require, so read-only tools will refuse to run." : "they will be watched, not enforced.")
|
|
3848
|
+
);
|
|
3849
|
+
}
|
|
3850
|
+
if (caps.version.startsWith("unknown")) {
|
|
3851
|
+
console.error(
|
|
3852
|
+
`${SERVER_NAME}: could not probe "${cfg.agyPath}" (${caps.version}). Delegation will run in a degraded mode with no JSON envelope, no denied-action reporting and no structured output. Check AGY_PATH, or install the Antigravity CLI.`
|
|
3853
|
+
);
|
|
3854
|
+
} else if (caps.missing.length) {
|
|
3855
|
+
console.error(
|
|
3856
|
+
`${SERVER_NAME}: agy ${caps.version} does not support ${caps.missing.join(", ")}; those features are disabled for this session.`
|
|
3857
|
+
);
|
|
3858
|
+
}
|
|
3859
|
+
return buildServer(cfg, caps, confinement);
|
|
3860
|
+
}
|
|
3861
|
+
var SHUTDOWN_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
3862
|
+
function installShutdown(stop, proc = process) {
|
|
3863
|
+
let done = false;
|
|
3864
|
+
const run = () => {
|
|
3865
|
+
if (done) return;
|
|
3866
|
+
done = true;
|
|
3867
|
+
try {
|
|
3868
|
+
stop();
|
|
3869
|
+
} catch {
|
|
3870
|
+
}
|
|
3871
|
+
};
|
|
3872
|
+
proc.once("exit", run);
|
|
3873
|
+
for (const sig of SHUTDOWN_SIGNALS) {
|
|
3874
|
+
const handler = () => {
|
|
3875
|
+
run();
|
|
3876
|
+
proc.removeListener(sig, handler);
|
|
3877
|
+
proc.kill(proc.pid, sig);
|
|
3878
|
+
};
|
|
3879
|
+
proc.once(sig, handler);
|
|
3880
|
+
}
|
|
3881
|
+
}
|
|
3882
|
+
function buildServer(cfg, caps, confinement = unavailableConfinement("write confinement was not set up")) {
|
|
3883
|
+
const delegator = new Delegator(cfg, new ModelRegistry(() => listModels(cfg.agyPath)), caps, {
|
|
3884
|
+
confinement,
|
|
3885
|
+
cooldowns: new CooldownRegistry(new FileCooldownStore()),
|
|
3886
|
+
preferences: new FilePreferenceStore()
|
|
3887
|
+
});
|
|
3888
|
+
installShutdown(() => {
|
|
3889
|
+
delegator.shutdown();
|
|
3890
|
+
removeLogDir();
|
|
3891
|
+
});
|
|
3892
|
+
const server = new McpServer({ name: SERVER_NAME, title: SERVER_TITLE, version: VERSION });
|
|
3893
|
+
const elicitFor = () => server.server.getClientCapabilities()?.elicitation?.form ? (params) => server.server.elicitInput(params) : void 0;
|
|
3894
|
+
for (const tool of TOOLS) {
|
|
3895
|
+
server.registerTool(
|
|
3896
|
+
tool.name,
|
|
3897
|
+
{ description: tool.description, inputSchema: tool.schema },
|
|
3898
|
+
createToolHandler(tool, cfg, delegator, elicitFor)
|
|
3899
|
+
);
|
|
3900
|
+
}
|
|
3901
|
+
return server;
|
|
3902
|
+
}
|
|
3903
|
+
|
|
3904
|
+
// src/index.ts
|
|
3905
|
+
createServer().then(async (server) => {
|
|
3906
|
+
await server.connect(new StdioServerTransport());
|
|
3907
|
+
const exit = () => process.exit(0);
|
|
3908
|
+
process.stdin.once("end", exit);
|
|
3909
|
+
process.stdin.once("close", exit);
|
|
3910
|
+
}).catch((err) => {
|
|
3911
|
+
console.error(`${SERVER_NAME} failed to start:`, err);
|
|
3912
|
+
process.exit(1);
|
|
3913
|
+
});
|