@letsrebase/verify 0.0.0-stage → 0.1.1
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/.claude/commands/rebase-verify.md +118 -0
- package/LICENSE +21 -0
- package/PRIVACY.md +113 -0
- package/README.md +210 -2
- package/SECURITY.md +33 -0
- package/bin/rebase-verify.mjs +700 -0
- package/package.json +38 -4
- package/share/practices.json +224 -0
- package/share/tech-labels.json +57 -0
- package/share/tech-lexicon.json +62 -0
- package/src/adapters/claude-code.mjs +225 -0
- package/src/adapters/codex.mjs +476 -0
- package/src/adapters/cursor.mjs +584 -0
- package/src/adapters/kimi.mjs +594 -0
- package/src/adapters/omp.mjs +59 -0
- package/src/adapters/opencode.mjs +439 -0
- package/src/adapters/pi.mjs +414 -0
- package/src/adapters/tool-vocab.mjs +15 -0
- package/src/agent-run.mjs +10 -0
- package/src/agentic-literacy.mjs +211 -0
- package/src/agents/acp.mjs +364 -0
- package/src/agents/json-answer.mjs +72 -0
- package/src/agents/registry.mjs +370 -0
- package/src/agents/run.mjs +131 -0
- package/src/ai-relationship.mjs +95 -0
- package/src/consistency.mjs +382 -0
- package/src/days.mjs +45 -0
- package/src/digest.mjs +501 -0
- package/src/distribution.mjs +54 -0
- package/src/enrich.mjs +118 -0
- package/src/fingerprint.mjs +134 -0
- package/src/forensics.mjs +178 -0
- package/src/groundedness.mjs +347 -0
- package/src/hub.mjs +136 -0
- package/src/intensity.mjs +132 -0
- package/src/live-status.mjs +79 -0
- package/src/practices-llm.mjs +90 -0
- package/src/practices-rules.mjs +295 -0
- package/src/practices-sample.mjs +111 -0
- package/src/practices.mjs +279 -0
- package/src/profile-llm.mjs +249 -0
- package/src/profile.mjs +497 -0
- package/src/redact.mjs +97 -0
- package/src/sources.mjs +91 -0
- package/src/submit.mjs +65 -0
- package/src/system-text.mjs +3 -0
- package/src/tech-usage.mjs +88 -0
- package/src/trajectory.mjs +264 -0
- package/src/wizard.mjs +411 -0
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
// Drive the person's own coding agent over ACP (JSON-RPC over stdio) for one
|
|
2
|
+
// text-in, text-out job. The agent runs in a fresh empty dir, with a minimal
|
|
3
|
+
// environment, no client capabilities (no fs, no terminal), and a tripwire:
|
|
4
|
+
// any tool call cancels the turn and fails it.
|
|
5
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
6
|
+
import { appendFileSync, existsSync, mkdirSync, mkdtempSync } from "node:fs";
|
|
7
|
+
import { rm } from "node:fs/promises";
|
|
8
|
+
import { tmpdir } from "node:os";
|
|
9
|
+
import { dirname, extname, join } from "node:path";
|
|
10
|
+
import { Readable, Writable } from "node:stream";
|
|
11
|
+
import * as acp from "@agentclientprotocol/sdk";
|
|
12
|
+
import { AGENT_RUN_MARKER } from "../agent-run.mjs";
|
|
13
|
+
|
|
14
|
+
export class ToolUseError extends Error {
|
|
15
|
+
constructor(tool) {
|
|
16
|
+
super(`the agent tried to use a tool (${tool}); tools are off for this run`);
|
|
17
|
+
this.name = "ToolUseError";
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export class AgentAuthError extends Error {
|
|
21
|
+
constructor(detail) {
|
|
22
|
+
super(`the agent is not logged in${detail ? `: ${detail}` : ""}`);
|
|
23
|
+
this.name = "AgentAuthError";
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export class AgentStartError extends Error {
|
|
27
|
+
constructor(message) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.name = "AgentStartError";
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export class ModelNotOfferedError extends Error {
|
|
33
|
+
constructor(id) {
|
|
34
|
+
super(`the agent does not offer model "${id}"`);
|
|
35
|
+
this.name = "ModelNotOfferedError";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const BASE_ENV = new Set(
|
|
40
|
+
[
|
|
41
|
+
"PATH", "HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "TMPDIR", "TEMP", "TMP", "SystemRoot", "LANG",
|
|
42
|
+
"HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY",
|
|
43
|
+
// .cmd shims (npx) need these on Windows
|
|
44
|
+
...(process.platform === "win32" ? ["COMSPEC", "PATHEXT"] : []),
|
|
45
|
+
].map((n) => n.toUpperCase()),
|
|
46
|
+
);
|
|
47
|
+
const isBaseName = (n) => {
|
|
48
|
+
const u = n.toUpperCase();
|
|
49
|
+
return BASE_ENV.has(u) || u.startsWith("LC_") || u.startsWith("XDG_");
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
export function childEnv(extraNames = [], source = process.env) {
|
|
53
|
+
const extra = new Set(extraNames.map((n) => n.toUpperCase()));
|
|
54
|
+
const env = {};
|
|
55
|
+
for (const [k, v] of Object.entries(source)) {
|
|
56
|
+
if (v !== undefined && (isBaseName(k) || extra.has(k.toUpperCase()))) env[k] = v;
|
|
57
|
+
}
|
|
58
|
+
return env;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Windows: npx is a .cmd, so it goes through the shell as ONE command string
|
|
62
|
+
// (passing args with shell:true is deprecated, DEP0190).
|
|
63
|
+
export function windowsCommandLine(command, args = []) {
|
|
64
|
+
const q = (a) => (/[\s"&|<>^()%]/.test(a) || a === "" ? `"${a.replace(/"/g, '""')}"` : a);
|
|
65
|
+
return [command, ...args].map(q).join(" ");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Windows: a command without an extension that resolves to a .cmd (an npm shim: npx, omp,
|
|
69
|
+
// opencode, ...) can only be started through the shell.
|
|
70
|
+
export function needsShell(command, { platform = process.platform, env = process.env, exists = existsSync } = {}) {
|
|
71
|
+
if (platform !== "win32" || extname(command)) return false;
|
|
72
|
+
if (command === "npx") return true;
|
|
73
|
+
const pathKey = Object.keys(env).find((k) => k.toUpperCase() === "PATH");
|
|
74
|
+
const dirs = String(pathKey ? env[pathKey] : "").split(";").map((d) => d.replace(/^"(.*)"$/, "$1")).filter(Boolean);
|
|
75
|
+
const hasExe = dirs.some((d) => exists(join(d, `${command}.exe`)) || exists(join(d, `${command}.com`)));
|
|
76
|
+
return !hasExe && dirs.some((d) => exists(join(d, `${command}.cmd`)));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const abortError = () => Object.assign(new Error("aborted"), { name: "AbortError" });
|
|
80
|
+
const isAuthError = (e) =>
|
|
81
|
+
e?.code === -32000 || (e?.code === -32603 && /no model selected/i.test(JSON.stringify(e.data ?? "") + (e.message ?? "")));
|
|
82
|
+
|
|
83
|
+
function flattenOptions(opts = []) {
|
|
84
|
+
return opts.flatMap((o) => (Array.isArray(o.options) ? o.options : [o]));
|
|
85
|
+
}
|
|
86
|
+
const configEntry = (configOptions, category) => (configOptions ?? []).find((o) => o?.category === category);
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Start an agent and open one session.
|
|
90
|
+
*
|
|
91
|
+
* spec: { command, args, env?, sessionMeta?, sessionParams?, mode?, system?,
|
|
92
|
+
* systemPromptVia: "meta" | "param" | "inline", tripGraceMs? }
|
|
93
|
+
* With via "meta" or "param" the system prompt is fixed at session/new from
|
|
94
|
+
* `spec.system`; prompt(text, { system }) then rejects a different system
|
|
95
|
+
* (throws) instead of silently dropping it. With "inline" it is prepended to
|
|
96
|
+
* the text of each prompt.
|
|
97
|
+
*/
|
|
98
|
+
export async function startAgent(spec, { onEvent = () => {}, logFile, signal } = {}) {
|
|
99
|
+
if (signal?.aborted) throw abortError();
|
|
100
|
+
let cwd;
|
|
101
|
+
let child;
|
|
102
|
+
let conn;
|
|
103
|
+
let closed = false;
|
|
104
|
+
let closeDone;
|
|
105
|
+
let exited = false;
|
|
106
|
+
let exitInfo = null;
|
|
107
|
+
let stderrTail = "";
|
|
108
|
+
let exitPromise = Promise.resolve();
|
|
109
|
+
const log = (dir, extra) => {
|
|
110
|
+
if (logFile) appendFileSync(logFile, JSON.stringify({ t: Date.now(), dir, ...extra }) + "\n");
|
|
111
|
+
};
|
|
112
|
+
const emit = (e) => {
|
|
113
|
+
try {
|
|
114
|
+
onEvent(e);
|
|
115
|
+
} catch {
|
|
116
|
+
// a broken observer never breaks the run
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
const startErr = () =>
|
|
120
|
+
new AgentStartError(
|
|
121
|
+
`the agent "${spec.command}" exited (${exitInfo?.signal ?? exitInfo?.code ?? "unknown"})${stderrTail.trim() ? `: ${stderrTail.trim().split("\n").pop()}` : ""}`,
|
|
122
|
+
);
|
|
123
|
+
|
|
124
|
+
function close() {
|
|
125
|
+
if (closed) return closeDone;
|
|
126
|
+
closed = true;
|
|
127
|
+
closeDone = (async () => {
|
|
128
|
+
try {
|
|
129
|
+
conn?.close();
|
|
130
|
+
} catch {}
|
|
131
|
+
if (child && !exited && child.pid) {
|
|
132
|
+
if (process.platform === "win32") spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true });
|
|
133
|
+
else {
|
|
134
|
+
// detached: the child leads its own group; npx, the adapter and the CLI it spawns all die
|
|
135
|
+
try {
|
|
136
|
+
process.kill(-child.pid, "SIGKILL");
|
|
137
|
+
} catch {}
|
|
138
|
+
}
|
|
139
|
+
try {
|
|
140
|
+
child.kill("SIGKILL");
|
|
141
|
+
} catch {}
|
|
142
|
+
}
|
|
143
|
+
await Promise.race([exitPromise, new Promise((r) => setTimeout(r, 10000).unref())]);
|
|
144
|
+
if (cwd) await rm(cwd, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
|
145
|
+
})();
|
|
146
|
+
return closeDone;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
let turn = null; // { text, tripped, timer, expire }
|
|
150
|
+
let pendingTrip = null; // a tool event seen outside a turn
|
|
151
|
+
let sessionId = null;
|
|
152
|
+
const seenTools = new Set();
|
|
153
|
+
const notifyCancel = () => conn.agent.notify("session/cancel", { sessionId }).catch(() => {});
|
|
154
|
+
const onAbort = () => {
|
|
155
|
+
if (sessionId && !closed) notifyCancel();
|
|
156
|
+
close();
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
try {
|
|
160
|
+
cwd = mkdtempSync(join(tmpdir(), AGENT_RUN_MARKER));
|
|
161
|
+
if (logFile) mkdirSync(dirname(logFile), { recursive: true });
|
|
162
|
+
const env = childEnv(spec.env);
|
|
163
|
+
const viaShell = needsShell(spec.command, { env });
|
|
164
|
+
const spawnOpts = {
|
|
165
|
+
cwd,
|
|
166
|
+
env,
|
|
167
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
168
|
+
windowsHide: true,
|
|
169
|
+
detached: process.platform !== "win32",
|
|
170
|
+
};
|
|
171
|
+
child = viaShell
|
|
172
|
+
? spawn(windowsCommandLine(spec.command, spec.args ?? []), { ...spawnOpts, shell: true })
|
|
173
|
+
: spawn(spec.command, spec.args ?? [], spawnOpts);
|
|
174
|
+
child.stderr.on("data", (d) => (stderrTail = (stderrTail + d).slice(-2000)));
|
|
175
|
+
child.stdin.on("error", () => {});
|
|
176
|
+
exitPromise = new Promise((resolve) => {
|
|
177
|
+
child.once("exit", (code, sig) => ((exited = true), (exitInfo = { code, signal: sig }), resolve()));
|
|
178
|
+
child.once("error", () => ((exited = true), resolve()));
|
|
179
|
+
});
|
|
180
|
+
const dead = new Promise((_, reject) => {
|
|
181
|
+
child.once("error", (e) =>
|
|
182
|
+
reject(new AgentStartError(e.code === "ENOENT" ? `cannot start "${spec.command}": not found` : `cannot start "${spec.command}": ${e.message}`)),
|
|
183
|
+
);
|
|
184
|
+
child.once("exit", () => {
|
|
185
|
+
if (!closed) reject(startErr());
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
dead.catch(() => {});
|
|
189
|
+
|
|
190
|
+
// Wire log: every message both ways; initialize/authenticate responses can
|
|
191
|
+
// carry account data, so only their method is kept.
|
|
192
|
+
const redactIds = new Map();
|
|
193
|
+
const base = acp.ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout));
|
|
194
|
+
const writer = base.writable.getWriter();
|
|
195
|
+
const stream = {
|
|
196
|
+
readable: base.readable.pipeThrough(
|
|
197
|
+
new TransformStream({
|
|
198
|
+
transform(msg, ctrl) {
|
|
199
|
+
if (msg && msg.id !== undefined && !msg.method && redactIds.has(msg.id)) log("in", { method: redactIds.get(msg.id), redacted: true });
|
|
200
|
+
else log("in", { msg });
|
|
201
|
+
ctrl.enqueue(msg);
|
|
202
|
+
},
|
|
203
|
+
}),
|
|
204
|
+
),
|
|
205
|
+
writable: new WritableStream({
|
|
206
|
+
write(msg) {
|
|
207
|
+
if (msg && msg.id !== undefined && (msg.method === "initialize" || msg.method === "authenticate")) redactIds.set(msg.id, msg.method);
|
|
208
|
+
log("out", { msg });
|
|
209
|
+
return writer.write(msg);
|
|
210
|
+
},
|
|
211
|
+
close: () => writer.close().catch(() => {}),
|
|
212
|
+
abort: (r) => writer.abort(r).catch(() => {}),
|
|
213
|
+
}),
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
const trip = (tool) => {
|
|
217
|
+
emit({ kind: "tool-tripped", tool });
|
|
218
|
+
if (!turn) return void (pendingTrip ??= tool);
|
|
219
|
+
if (turn.tripped) return;
|
|
220
|
+
turn.tripped = tool;
|
|
221
|
+
notifyCancel();
|
|
222
|
+
turn.timer = setTimeout(() => turn?.expire(), spec.tripGraceMs ?? 5000);
|
|
223
|
+
turn.timer.unref?.();
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
const app = acp
|
|
227
|
+
.client({ name: "rebase-verify" })
|
|
228
|
+
.onRequest("session/request_permission", async ({ params }) => {
|
|
229
|
+
const reject = params.options?.find((o) => /^reject/.test(o.kind ?? ""));
|
|
230
|
+
emit({ kind: "permission-refused", toolCall: params.toolCall });
|
|
231
|
+
return reject ? { outcome: { outcome: "selected", optionId: reject.optionId } } : { outcome: { outcome: "cancelled" } };
|
|
232
|
+
})
|
|
233
|
+
.onNotification("session/update", ({ params }) => {
|
|
234
|
+
const u = params.update;
|
|
235
|
+
emit({ ...u, kind: u.sessionUpdate });
|
|
236
|
+
// text counts only from the current session: an earlier one (once renewed) adds nothing
|
|
237
|
+
if (turn && u.sessionUpdate === "agent_message_chunk" && u.content?.type === "text" && (sessionId === null || params.sessionId === sessionId)) turn.text += u.content.text;
|
|
238
|
+
// a tool_call, or an update for a tool call we never saw, is a tool in use, whatever session names it
|
|
239
|
+
if (u.sessionUpdate === "tool_call") {
|
|
240
|
+
seenTools.add(u.toolCallId);
|
|
241
|
+
trip(u.title || u.kind || "tool");
|
|
242
|
+
} else if (u.sessionUpdate === "tool_call_update" && !seenTools.has(u.toolCallId)) {
|
|
243
|
+
seenTools.add(u.toolCallId);
|
|
244
|
+
trip(u.title || u.kind || "tool");
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
conn = app.connect(stream);
|
|
248
|
+
const call = async (method, params) => {
|
|
249
|
+
try {
|
|
250
|
+
return await Promise.race([conn.agent.request(method, params), dead]);
|
|
251
|
+
} catch (e) {
|
|
252
|
+
if (closed || e instanceof AgentStartError || typeof e?.code === "number") throw e;
|
|
253
|
+
// the connection dropped: if the child died, say so with its stderr
|
|
254
|
+
if (!exited) await Promise.race([exitPromise, new Promise((r) => setTimeout(r, 2000).unref())]);
|
|
255
|
+
if (exited) throw startErr();
|
|
256
|
+
throw e;
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
260
|
+
|
|
261
|
+
emit({ kind: "started", pid: child.pid, cwd });
|
|
262
|
+
const init = await call("initialize", { protocolVersion: 1, clientInfo: { name: "rebase-verify", version: "0" }, clientCapabilities: {} });
|
|
263
|
+
const meta = { ...(spec.sessionMeta ?? {}) };
|
|
264
|
+
const params = { cwd, mcpServers: [], ...(spec.sessionParams ?? {}) };
|
|
265
|
+
if (spec.system && spec.systemPromptVia === "meta") meta.systemPrompt = spec.system;
|
|
266
|
+
if (spec.system && spec.systemPromptVia === "param")
|
|
267
|
+
params.systemPrompt = { mode: "append", content: [{ type: "text", text: spec.system }] };
|
|
268
|
+
if (Object.keys(meta).length) params._meta = meta;
|
|
269
|
+
let modelEntry = null;
|
|
270
|
+
let chosenModel = null;
|
|
271
|
+
// session/new on the open connection (same cwd, meta and params), then the mode and the
|
|
272
|
+
// chosen model again: a new session starts from the agent's defaults.
|
|
273
|
+
const open = async () => {
|
|
274
|
+
let created;
|
|
275
|
+
try {
|
|
276
|
+
created = await call("session/new", params);
|
|
277
|
+
} catch (e) {
|
|
278
|
+
throw isAuthError(e) ? new AgentAuthError(e.message) : e;
|
|
279
|
+
}
|
|
280
|
+
sessionId = created.sessionId;
|
|
281
|
+
const configOptions = created.configOptions;
|
|
282
|
+
modelEntry = configEntry(configOptions, "model");
|
|
283
|
+
session.models = flattenOptions(modelEntry?.options).map((o) => ({ id: o.value, name: o.name ?? o.value }));
|
|
284
|
+
session.currentModel = modelEntry?.currentValue ?? null;
|
|
285
|
+
if (spec.mode) {
|
|
286
|
+
const modeEntry = configEntry(configOptions, "mode");
|
|
287
|
+
if (modeEntry && flattenOptions(modeEntry.options).some((o) => o.value === spec.mode))
|
|
288
|
+
await call("session/set_config_option", { sessionId, configId: modeEntry.id, value: spec.mode });
|
|
289
|
+
else await call("session/set_mode", { sessionId, modeId: spec.mode });
|
|
290
|
+
}
|
|
291
|
+
if (chosenModel) await session.setModel(chosenModel);
|
|
292
|
+
};
|
|
293
|
+
const session = {
|
|
294
|
+
models: [],
|
|
295
|
+
currentModel: null,
|
|
296
|
+
async setModel(id) {
|
|
297
|
+
if (!modelEntry || !session.models.some((m) => m.id === id)) throw new ModelNotOfferedError(id);
|
|
298
|
+
await call("session/set_config_option", { sessionId, configId: modelEntry.id, value: id });
|
|
299
|
+
chosenModel = id;
|
|
300
|
+
session.currentModel = id;
|
|
301
|
+
emit({ kind: "model-set", model: id });
|
|
302
|
+
},
|
|
303
|
+
// A new session on the same process: the next turn sees nothing of the earlier ones.
|
|
304
|
+
async renew() {
|
|
305
|
+
if (pendingTrip) throw new ToolUseError(pendingTrip);
|
|
306
|
+
seenTools.clear();
|
|
307
|
+
if (init?.agentCapabilities?.sessionCapabilities?.close && sessionId) {
|
|
308
|
+
// best effort: the agent may drop the old session's state; a slow or failing close never stops the run
|
|
309
|
+
let timer;
|
|
310
|
+
try {
|
|
311
|
+
await Promise.race([call("session/close", { sessionId }), new Promise((r) => (timer = setTimeout(r, 2000)))]);
|
|
312
|
+
} catch {
|
|
313
|
+
// ignored
|
|
314
|
+
} finally {
|
|
315
|
+
clearTimeout(timer);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
await open();
|
|
319
|
+
emit({ kind: "session-renewed", sessionId });
|
|
320
|
+
},
|
|
321
|
+
async prompt(text, { system } = {}) {
|
|
322
|
+
if (pendingTrip) throw new ToolUseError(pendingTrip);
|
|
323
|
+
const fixed = spec.systemPromptVia === "meta" || spec.systemPromptVia === "param";
|
|
324
|
+
if (fixed && system !== undefined && system !== spec.system)
|
|
325
|
+
throw new Error("the system prompt is fixed when the agent starts; pass it in the spec, not to prompt()");
|
|
326
|
+
const body = !fixed && system ? `${system}\n\n${text}` : text;
|
|
327
|
+
const t = { text: "", tripped: null, timer: null, expire: null };
|
|
328
|
+
const deadline = new Promise((_, rej) => (t.expire = () => rej(new Error("trip-deadline"))));
|
|
329
|
+
deadline.catch(() => {});
|
|
330
|
+
turn = t;
|
|
331
|
+
emit({ kind: "turn-start" });
|
|
332
|
+
try {
|
|
333
|
+
const res = await Promise.race([call("session/prompt", { sessionId, prompt: [{ type: "text", text: body }] }), deadline]);
|
|
334
|
+
emit({ kind: "turn-end", stopReason: res.stopReason });
|
|
335
|
+
if (t.tripped) throw new ToolUseError(t.tripped);
|
|
336
|
+
return { text: t.text, usage: res.usage ?? null, stopReason: res.stopReason };
|
|
337
|
+
} catch (e) {
|
|
338
|
+
if (e instanceof ToolUseError) throw e;
|
|
339
|
+
if (t.tripped) {
|
|
340
|
+
await close();
|
|
341
|
+
throw new ToolUseError(t.tripped);
|
|
342
|
+
}
|
|
343
|
+
if (signal?.aborted) {
|
|
344
|
+
await closeDone;
|
|
345
|
+
throw abortError();
|
|
346
|
+
}
|
|
347
|
+
throw isAuthError(e) ? new AgentAuthError(e.message) : e;
|
|
348
|
+
} finally {
|
|
349
|
+
clearTimeout(t.timer);
|
|
350
|
+
turn = null;
|
|
351
|
+
}
|
|
352
|
+
},
|
|
353
|
+
cancel: () => notifyCancel(),
|
|
354
|
+
close,
|
|
355
|
+
};
|
|
356
|
+
|
|
357
|
+
await open();
|
|
358
|
+
return session;
|
|
359
|
+
} catch (e) {
|
|
360
|
+
await close();
|
|
361
|
+
if (signal?.aborted) throw abortError();
|
|
362
|
+
throw e;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// An agent answers in free text: the JSON may be fenced, or followed by
|
|
2
|
+
// chatter. Take the first balanced `{...}` that parses as an object.
|
|
3
|
+
export class NoJsonError extends Error {
|
|
4
|
+
constructor(message = "no JSON object in the answer") {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = "NoJsonError";
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// End index (inclusive) of the balanced object starting at `start`, string-aware.
|
|
11
|
+
function balancedEnd(text, start) {
|
|
12
|
+
let depth = 0;
|
|
13
|
+
let inString = false;
|
|
14
|
+
for (let i = start; i < text.length; i++) {
|
|
15
|
+
const ch = text[i];
|
|
16
|
+
if (inString) {
|
|
17
|
+
if (ch === "\\") i++;
|
|
18
|
+
else if (ch === '"') inString = false;
|
|
19
|
+
} else if (ch === '"') inString = true;
|
|
20
|
+
else if (ch === "{") depth++;
|
|
21
|
+
else if (ch === "}" && --depth === 0) return i;
|
|
22
|
+
}
|
|
23
|
+
return -1;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// The one repair: a comma before a closing `}` or `]` (outside strings) is dropped.
|
|
27
|
+
function withoutTrailingCommas(span) {
|
|
28
|
+
let out = "";
|
|
29
|
+
let inString = false;
|
|
30
|
+
for (let i = 0; i < span.length; i++) {
|
|
31
|
+
const ch = span[i];
|
|
32
|
+
if (inString) {
|
|
33
|
+
out += ch;
|
|
34
|
+
if (ch === "\\") out += span[++i] ?? "";
|
|
35
|
+
else if (ch === '"') inString = false;
|
|
36
|
+
} else if (ch === '"') {
|
|
37
|
+
inString = true;
|
|
38
|
+
out += ch;
|
|
39
|
+
} else if (ch === ",") {
|
|
40
|
+
let j = i + 1;
|
|
41
|
+
while (j < span.length && /\s/.test(span[j])) j++;
|
|
42
|
+
if (span[j] !== "}" && span[j] !== "]") out += ch;
|
|
43
|
+
} else out += ch;
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const parseObject = (span) => {
|
|
49
|
+
const value = JSON.parse(span);
|
|
50
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export function firstJsonObject(text) {
|
|
54
|
+
if (typeof text !== "string") throw new NoJsonError();
|
|
55
|
+
for (let start = text.indexOf("{"); start >= 0; start = text.indexOf("{", start + 1)) {
|
|
56
|
+
const end = balancedEnd(text, start);
|
|
57
|
+
if (end < 0) continue;
|
|
58
|
+
const span = text.slice(start, end + 1);
|
|
59
|
+
for (const candidate of [span, withoutTrailingCommas(span)]) {
|
|
60
|
+
try {
|
|
61
|
+
const value = parseObject(candidate);
|
|
62
|
+
if (value) return value;
|
|
63
|
+
} catch {
|
|
64
|
+
// not JSON as it stands; the second candidate drops trailing commas
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
// A balanced span that is not JSON (prose braces) is skipped WHOLE,
|
|
68
|
+
// so a broken outer object never yields one of its inner objects.
|
|
69
|
+
start = end;
|
|
70
|
+
}
|
|
71
|
+
throw new NoJsonError();
|
|
72
|
+
}
|