@parcha/agentrun-harness-acp 0.1.0-beta.52 → 0.1.0-beta.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/adapter.js +3 -0
- package/dist/facts.d.ts +4 -0
- package/dist/facts.js +4 -0
- package/dist/harness.js +36 -7
- package/dist/host/agent.d.ts +4 -0
- package/dist/host/agent.js +18 -6
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/recipe.d.ts +12 -0
- package/dist/recipe.js +28 -2
- package/dist/state.d.ts +28 -9
- package/dist/state.js +121 -28
- package/package.json +2 -2
- package/testing/fake-acp-agent.mjs +52 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,23 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## 0.1.0-beta.53 (2026-11-22)
|
|
6
|
+
|
|
7
|
+
- A harness recipe now covers an outside agent's release as its vendor ships it (Google's agy CLI among them), and the owner's own sign-in, made by the agent itself: <!-- changes/recipes-outside-harness.md -->
|
|
8
|
+
- `.zip` releases install, unpacked in Node with no `unzip` on the host. An entry that leaves the folder (`..`, an absolute path, a backslash), a symbolic link, a device, an encrypted entry or a duplicate refuses the whole archive before anything lands.
|
|
9
|
+
- An archive is pinned by one digest, its `sha256` or, where the vendor's manifest lists that, its `sha512` (Google's agy CLI manifests). `release.registry` is optional, for a release that is the vendor's own rather than the ACP registry's.
|
|
10
|
+
- Every file the archive unpacks to is pinned, not the binary alone: the tree's sha256 is recorded at the first install (or given as the release's `treeSha256`), and a check or a sign-in refuses a sidecar that changed since.
|
|
11
|
+
- A release may give its own `args` per platform, over the recipe's.
|
|
12
|
+
- `model.id` picks a plan-billed agent's model among those its `session/new` lists (`session/set_model`); one it does not list is refused before a prompt.
|
|
13
|
+
- A key may be handed under the name the agent reads: `keys: [{ "name": "ANTIGRAVITY_GEMINI_API_KEY", "env": "GEMINI_API_KEY" }]`. It is read by its saved name, so the server's own `GEMINI_API_KEY` never reaches the agent. `keyMethod` is the method the agent's ACP `authenticate` signs in with on it (`gemini-api-key`).
|
|
14
|
+
- One list in the kernel, `launchEnv` (`LAUNCH_ENV`, `LAUNCH_ENV_PREFIXES`), names the variables that change what a process loads or runs before its own code: `PATH`, `LD_*`, `DYLD_*`, `NODE_OPTIONS`, `NODE_PATH`, `PYTHON*`, `BASH_*`, `ENV`, `GIT_*` and a few shells' and interpreters' start-up variables. A key is never handed under one of them, nor a recipe's `env` or `model.env` named one. The recipe loader and the ACP adapter both refuse them.
|
|
15
|
+
- A key's saved and handed names follow the kernel's `KEY_NAME` (capitals, digits and `_`, at most 64) in the recipe loader as in the ACP adapter, so `harness-check` no longer refuses a lowercase key name the loader took. Other variable names keep `ENV_NAME`.
|
|
16
|
+
- `signIn: { "args": [...], "homeArg": FLAG }` names the agent's own sign-in, as T3 Code runs agy: `agentrun harness sign-in --recipe FILE` starts the installed, unmodified agent on your terminal with its arguments, `args` (`--login`) and `homeArg` naming its own folder (`--gemini-dir DIR`). The agent prints the address, reads the code you paste and keeps its sign-in in that folder; exit 0 is signed in (`HARNESS_SIGN_IN_FAILED` otherwise).
|
|
17
|
+
- harness-check runs on the recipe's keys alone, never the sign-in, so a plan-billed recipe names a key beside any `signIn`. A run on the sign-in hands the agent `homeArg` and its folder, no key, nothing it prints kept.
|
|
18
|
+
- AgentRun never reads, refreshes or sends the sign-in's token, and has no usage reader: it never opens the folder, and a test keeps every credential file and Google account or quota endpoint out of the harness sources.
|
|
19
|
+
- The ACP adapter's `stderr: "none"` (`AcpRecipe`) keeps nothing an agent prints, for a run on a sign-in: a failure says its exit status and AgentRun's own code, and an error the agent answers says its JSON-RPC code alone.
|
|
20
|
+
- An ACP run (Cursor, Goose, or a harness recipe) no longer stalls after many turns. Before, the adapter copied the agent's whole session store into the run's records at every turn, so the records grew with the square of the turn count. After about 20 Cursor turns they no longer fit the 32 MiB channel to the run's process: an approval answered 204, and the run then waited for good. Now the mirror stores each file as 64 KiB pieces, each written once per session, so a store that grows by appending costs only its new bytes. It never copies SQLite's `-shm` file, and holds at most 8 MiB per session. Past that, the run's timeline says "The agent's session state passed 8 MiB, so a resume starts it fresh with the conversation so far." and the mirror stops. A run whose records no longer cross to its process now fails at once, naming the size and the limit, and the approval that woke it is answered that the run failed. Adapters get a `notice` event, which serve shows as a step on the run's timeline. A session store mirrored before this version is not restored: such a run resumes fresh with the conversation so far. <!-- changes/acp-state-mirror-bounded.md -->
|
|
21
|
+
|
|
5
22
|
## 0.1.0-beta.52 (2026-11-21)
|
|
6
23
|
|
|
7
24
|
- An ACP agent's failure words no longer keep a piece of a recipe key when the agent is still writing that key at the end of its stderr tail, or when two keys overlap: every place a key or its start appears is found in the text as written, then all of them are cut at once. <!-- changes/acp-key-cut-tail-end.md -->
|
package/dist/adapter.js
CHANGED
|
@@ -28,6 +28,9 @@ function adapterEvent(event) {
|
|
|
28
28
|
return { type: "tool_start", callId: String(e.callId ?? ""), name: e.name, args: e.args, ...(typeof e.parent === "string" ? { parent: e.parent } : {}) };
|
|
29
29
|
if (e?.type === "tool_end" && typeof e.name === "string")
|
|
30
30
|
return { type: "tool_end", callId: String(e.callId ?? ""), name: e.name, isError: e.isError === true, ...(typeof e.result === "string" ? { result: e.result } : {}), ...(e.truncated === true ? { truncated: true } : {}) };
|
|
31
|
+
const notice = event;
|
|
32
|
+
if (notice?.type === "notice" && typeof notice.text === "string")
|
|
33
|
+
return { type: "notice", text: notice.text };
|
|
31
34
|
return undefined;
|
|
32
35
|
}
|
|
33
36
|
const turnsIn = (drive) => transcriptOf(drive.state()).filter((r) => r.data?.type === "turn");
|
package/dist/facts.d.ts
CHANGED
|
@@ -26,6 +26,10 @@ export declare const ACP_CODES: Readonly<{
|
|
|
26
26
|
readonly modelUnlisted: "ACP_MODEL_UNLISTED";
|
|
27
27
|
/** The agent asked for another call of its own tools REASK_LIMIT times in a turn instead of one the person allowed. */
|
|
28
28
|
readonly reaskLimit: "ACP_REASK_LIMIT";
|
|
29
|
+
/** The recipe's sign-in method (recipe.authMethod) is not one the agent's initialize lists: no session was opened. */
|
|
30
|
+
readonly authUnlisted: "ACP_AUTH_UNLISTED";
|
|
31
|
+
/** The agent refused the recipe's sign-in method (ACP authenticate failed): no session was opened. */
|
|
32
|
+
readonly authFailed: "ACP_AUTH_FAILED";
|
|
29
33
|
}>;
|
|
30
34
|
export interface AcpFacts {
|
|
31
35
|
readonly id: string;
|
package/dist/facts.js
CHANGED
|
@@ -29,6 +29,10 @@ export const ACP_CODES = Object.freeze({
|
|
|
29
29
|
modelUnlisted: "ACP_MODEL_UNLISTED",
|
|
30
30
|
/** The agent asked for another call of its own tools REASK_LIMIT times in a turn instead of one the person allowed. */
|
|
31
31
|
reaskLimit: "ACP_REASK_LIMIT",
|
|
32
|
+
/** The recipe's sign-in method (recipe.authMethod) is not one the agent's initialize lists: no session was opened. */
|
|
33
|
+
authUnlisted: "ACP_AUTH_UNLISTED",
|
|
34
|
+
/** The agent refused the recipe's sign-in method (ACP authenticate failed): no session was opened. */
|
|
35
|
+
authFailed: "ACP_AUTH_FAILED",
|
|
32
36
|
});
|
|
33
37
|
/** The facts of the ACP harness `id`. */
|
|
34
38
|
export function acpFacts(id, label = id) {
|
package/dist/harness.js
CHANGED
|
@@ -178,8 +178,20 @@ export function acpHarness(options, control) {
|
|
|
178
178
|
.join("\n")
|
|
179
179
|
.trim()
|
|
180
180
|
.slice(-300);
|
|
181
|
-
/**
|
|
182
|
-
|
|
181
|
+
/** A recipe whose agent's words are kept nowhere (recipe.stderr `none`: an agent on a person's sign-in, whose token no
|
|
182
|
+
* key cut knows): a failure says its exit status and the adapter's own codes, never a word the agent printed or
|
|
183
|
+
* answered. */
|
|
184
|
+
const hushed = recipe.stderr === "none";
|
|
185
|
+
/** An error's words for a failure: on a hushed run, an error the agent answered says its JSON-RPC code alone. */
|
|
186
|
+
const agentSaid = (error) => {
|
|
187
|
+
if (!hushed)
|
|
188
|
+
return said(error);
|
|
189
|
+
const code = error?.code;
|
|
190
|
+
return typeof code === "number" ? `the agent answered error ${code}; its words are kept nowhere on this run` : said(error);
|
|
191
|
+
};
|
|
192
|
+
/** Why an agent that ended did: its last words on stderr, else the error's, else that it said nothing. On a hushed run,
|
|
193
|
+
* its exit status alone. */
|
|
194
|
+
const whyEnded = (agent, error) => hushed ? `${agent.ended() ?? "its end is not known yet"}; what it printed is kept nowhere on this run` : lastWords(agent.stderrTail()) || lastWords(message(error)) || "it said nothing";
|
|
183
195
|
/** Mirror the agent's session store into `journal` (the caller flushes). A failure is said and never thrown: the next
|
|
184
196
|
* point takes the mirror again, and a turn's outcome is never lost to it. */
|
|
185
197
|
const mirrorInto = (rt, journal) => {
|
|
@@ -464,9 +476,11 @@ export function acpHarness(options, control) {
|
|
|
464
476
|
const keyEnv = {};
|
|
465
477
|
const absent = [];
|
|
466
478
|
for (const name of recipe.keys ?? []) {
|
|
479
|
+
// Read by its own name, handed under the one the agent reads (recipe.keyEnv): a value the host holds under that
|
|
480
|
+
// name is never the agent's.
|
|
467
481
|
const value = hostEnv[name];
|
|
468
482
|
if (typeof value === "string" && value !== "")
|
|
469
|
-
keyEnv[name] = value;
|
|
483
|
+
keyEnv[recipe.keyEnv?.[name] ?? name] = value;
|
|
470
484
|
else
|
|
471
485
|
absent.push(name);
|
|
472
486
|
}
|
|
@@ -502,7 +516,7 @@ export function acpHarness(options, control) {
|
|
|
502
516
|
const stopped = new AbortController();
|
|
503
517
|
const signal = AbortSignal.any([ctx.signal, stopped.signal]);
|
|
504
518
|
const key = randomBytes(32).toString("base64url");
|
|
505
|
-
const rt = { ctx, loading: false, fresh: true, wiped: false, firstBlocks: [], calls: new CallIds(), counted: new Set(), claimed: new Set(), ownIds: new Set(), kinds: new Map(), sessionId: "", mirror: new StateMirror(home, (recipe.state ?? []).map((p) => homePath(p)), own, records, log) };
|
|
519
|
+
const rt = { ctx, loading: false, fresh: true, wiped: false, firstBlocks: [], calls: new CallIds(), counted: new Set(), claimed: new Set(), ownIds: new Set(), kinds: new Map(), sessionId: "", mirror: new StateMirror(home, (recipe.state ?? []).map((p) => homePath(p)), own, records, log, (words) => (rt.current?.ctx ?? ctx).live({ type: "notice", text: words })) };
|
|
506
520
|
const mcp = await startMcpServer({ tools: listed.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })), key, log, call: (name, args, callSignal) => onMcpCall(rt, name, args, callSignal) });
|
|
507
521
|
let proxy;
|
|
508
522
|
let agent;
|
|
@@ -569,6 +583,7 @@ export function acpHarness(options, control) {
|
|
|
569
583
|
...(options.confine ? { confine: options.confine } : {}),
|
|
570
584
|
...(options.parentWatch ? { parentWatch: options.parentWatch } : {}),
|
|
571
585
|
keys: Object.values(keyEnv),
|
|
586
|
+
...(hushed ? { stderr: "none" } : {}),
|
|
572
587
|
signal,
|
|
573
588
|
onUpdate: (notification) => onUpdate(rt, notification),
|
|
574
589
|
onPermission: (request, connection) => onPermission(rt, request, connection),
|
|
@@ -587,7 +602,7 @@ export function acpHarness(options, control) {
|
|
|
587
602
|
throw new Error(named);
|
|
588
603
|
if (!live.alive() || live.connection.signal.aborted)
|
|
589
604
|
throw new Error(`${ACP_CODES.agentExited}: the agent ended during ${what}: ${whyEnded(live, error)}`);
|
|
590
|
-
throw new Error(`acp: ${what} failed: ${
|
|
605
|
+
throw new Error(`acp: ${what} failed: ${agentSaid(error)}`);
|
|
591
606
|
});
|
|
592
607
|
const init = await ask("initialize", () => live.connection.agent.request("initialize", { protocolVersion: PROTOCOL_VERSION, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false }, clientInfo: { name: "agentrun", version: "1" } }));
|
|
593
608
|
if (init.protocolVersion !== PROTOCOL_VERSION)
|
|
@@ -600,6 +615,20 @@ export function acpHarness(options, control) {
|
|
|
600
615
|
missing.push("MCP over http (agentCapabilities.mcpCapabilities.http)");
|
|
601
616
|
if (missing.length)
|
|
602
617
|
throw new Error(`${ACP_CODES.capabilityMismatch}: the recipe declares ${missing.join(" and ")}, which the agent's initialize does not advertise`);
|
|
618
|
+
// The recipe's sign-in method, told before any session opens: one the agent lists, or none is tried.
|
|
619
|
+
if (recipe.authMethod) {
|
|
620
|
+
const methods = (init.authMethods ?? []).map((method) => method.id);
|
|
621
|
+
if (!methods.includes(recipe.authMethod))
|
|
622
|
+
throw new Error(`${ACP_CODES.authUnlisted}: ${recipe.label ?? recipe.id} signs in with ${recipe.authMethod}, which its initialize does not list (${methods.join(", ") || "it lists none"}); no session was opened`);
|
|
623
|
+
try {
|
|
624
|
+
await ask("authenticate", () => live.connection.agent.request("authenticate", { methodId: recipe.authMethod }));
|
|
625
|
+
}
|
|
626
|
+
catch (error) {
|
|
627
|
+
if (signal.aborted || !live.alive())
|
|
628
|
+
throw error;
|
|
629
|
+
throw new Error(`${ACP_CODES.authFailed}: ${recipe.label ?? recipe.id} refused its sign-in method ${recipe.authMethod}: ${message(error).replace(/^acp: authenticate failed: /, "")}; no session was opened`);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
603
632
|
const server = recipe.declares.mcp === "http"
|
|
604
633
|
? { type: "http", name: MCP_SERVER, url: mcp.url, headers: [{ name: "Authorization", value: `Bearer ${key}` }] }
|
|
605
634
|
: { name: MCP_SERVER, command: process.execPath, args: [STDIO_BRIDGE], env: [{ name: "AGENTRUN_MCP_URL", value: mcp.url }, { name: "AGENTRUN_MCP_KEY", value: key }] };
|
|
@@ -619,7 +648,7 @@ export function acpHarness(options, control) {
|
|
|
619
648
|
catch (error) {
|
|
620
649
|
if (signal.aborted || !live.alive())
|
|
621
650
|
throw error;
|
|
622
|
-
log("acp: the agent did not load its session; a new one starts with the conversation so far", { error:
|
|
651
|
+
log("acp: the agent did not load its session; a new one starts with the conversation so far", { error: agentSaid(error) });
|
|
623
652
|
}
|
|
624
653
|
finally {
|
|
625
654
|
rt.loading = false;
|
|
@@ -804,7 +833,7 @@ export function acpHarness(options, control) {
|
|
|
804
833
|
outcome = { status: "failed", error: turn.limitHit };
|
|
805
834
|
else if (failure !== undefined) {
|
|
806
835
|
const named = refusalIn(`${agent.agent.stderrTail()}\n${message(failure)}`);
|
|
807
|
-
outcome = { status: "failed", error: named ?? (agent.agent.alive() && !agent.agent.connection.signal.aborted ? `acp: session/prompt failed: ${
|
|
836
|
+
outcome = { status: "failed", error: named ?? (agent.agent.alive() && !agent.agent.connection.signal.aborted ? `acp: session/prompt failed: ${agentSaid(failure)}` : `${ACP_CODES.agentExited}: the agent ended during the turn: ${whyEnded(agent.agent, failure)}`) };
|
|
808
837
|
}
|
|
809
838
|
else {
|
|
810
839
|
const reason = answer?.stopReason;
|
package/dist/host/agent.d.ts
CHANGED
|
@@ -13,6 +13,8 @@ export interface AgentProcessOptions {
|
|
|
13
13
|
parentWatch?: ParentWatch;
|
|
14
14
|
/** The key values in `env` (the recipe's keys): cut from its stderr before the tail is shortened. */
|
|
15
15
|
keys?: readonly string[];
|
|
16
|
+
/** `tail` (default): its stderr's tail is kept for a failure's words. `none`: its stderr goes nowhere, never read. */
|
|
17
|
+
stderr?: "tail" | "none";
|
|
16
18
|
signal: AbortSignal;
|
|
17
19
|
/** Each session/update the agent sends, in the order it sent them. */
|
|
18
20
|
onUpdate(update: SessionNotification): void;
|
|
@@ -28,6 +30,8 @@ export interface AgentProcess {
|
|
|
28
30
|
}>;
|
|
29
31
|
alive(): boolean;
|
|
30
32
|
stderrTail(): string;
|
|
33
|
+
/** How it ended (`exit status 1`, `signal SIGKILL`), once it has; undefined while it runs. */
|
|
34
|
+
ended(): string | undefined;
|
|
31
35
|
kill(): void;
|
|
32
36
|
}
|
|
33
37
|
/** Start the agent and open the client connection over its stdio. */
|
package/dist/host/agent.js
CHANGED
|
@@ -4,7 +4,9 @@
|
|
|
4
4
|
// (parentWatched) inside the host's confinement: a SIGKILLed host leaves no agent behind.
|
|
5
5
|
// - Its stderr is kept, its tail only, for a failure's words; nothing it prints reaches the log whole. The keys it was
|
|
6
6
|
// handed are cut from the tail before it is shortened, a key's end at the head of a cut tail goes too, and so does a
|
|
7
|
-
// key's start at its end (one the agent is still writing, read mid-run) (key-cut.ts).
|
|
7
|
+
// key's start at its end (one the agent is still writing, read mid-run) (key-cut.ts). With `stderr: "none"` (an
|
|
8
|
+
// agent run on a person's sign-in, whose token no key cut knows) nothing of it is kept or read: its end is said by
|
|
9
|
+
// its exit status alone.
|
|
8
10
|
// - kill() ends its whole group; so does an abort of `signal`.
|
|
9
11
|
import { spawn } from "node:child_process";
|
|
10
12
|
import { Readable, Writable } from "node:stream";
|
|
@@ -16,7 +18,9 @@ const STDERR_TAIL = 8 * 1024;
|
|
|
16
18
|
/** Start the agent and open the client connection over its stdio. */
|
|
17
19
|
export function startAgent(options) {
|
|
18
20
|
const run = confined(parentWatched({ command: options.command, args: [...options.args] }, options.parentWatch), options.confine);
|
|
19
|
-
const
|
|
21
|
+
const quiet = options.stderr === "none";
|
|
22
|
+
const errTo = quiet ? "ignore" : "pipe";
|
|
23
|
+
const child = spawn(run.command, run.args, { cwd: options.cwd, env: childEnv(options.from ?? process.env, options.env), detached: true, stdio: ["pipe", "pipe", errTo] });
|
|
20
24
|
// What it printed, raw, kept a key's length beyond the tail: a key split across chunks, or across the tail's start, is
|
|
21
25
|
// still whole here, and cut whole (stderrTail). `cut`: whether its start was ever dropped.
|
|
22
26
|
const keys = keysToCut(options.keys ?? []);
|
|
@@ -33,19 +37,25 @@ export function startAgent(options) {
|
|
|
33
37
|
// A key's start at the end goes at every read, the agent alive or not: alive, it may be a key still being written;
|
|
34
38
|
// ended, the most it drops is a key's length less one, and only text that spells a key's start.
|
|
35
39
|
const stderrTail = () => cutKeys(raw, keys, { head: cut, tail: true }).slice(-STDERR_TAIL);
|
|
36
|
-
|
|
37
|
-
|
|
40
|
+
if (!quiet) {
|
|
41
|
+
child.stderr.setEncoding("utf8");
|
|
42
|
+
child.stderr.on("data", take);
|
|
43
|
+
}
|
|
38
44
|
// A write to a stdin the agent closed is its exit's to report, never an unhandled error.
|
|
39
45
|
child.stdin.on("error", () => { });
|
|
40
46
|
let done = false;
|
|
47
|
+
let end;
|
|
41
48
|
const exited = new Promise((resolve) => {
|
|
42
49
|
child.once("error", (err) => {
|
|
50
|
+
// The spawn's own error (ENOENT, EACCES): ours, never the agent's words.
|
|
43
51
|
take(`\n${String(err.message)}`);
|
|
44
52
|
done = true;
|
|
53
|
+
end = `it never started (${err.code ?? "spawn failed"})`;
|
|
45
54
|
resolve({ code: null, signal: null });
|
|
46
55
|
});
|
|
47
56
|
child.once("close", (code, signal) => {
|
|
48
57
|
done = true;
|
|
58
|
+
end = signal ? `signal ${signal}` : `exit status ${code}`;
|
|
49
59
|
resolve({ code, signal });
|
|
50
60
|
});
|
|
51
61
|
});
|
|
@@ -70,6 +80,8 @@ export function startAgent(options) {
|
|
|
70
80
|
.onNotification("session/update", ({ params }) => options.onUpdate(params))
|
|
71
81
|
.onRequest("session/request_permission", ({ params, signal }) => options.onPermission(params, signal));
|
|
72
82
|
const connection = app.connect(ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout)));
|
|
73
|
-
void exited.then(() => connection.close(new Error(
|
|
74
|
-
|
|
83
|
+
void exited.then(() => connection.close(new Error(quiet
|
|
84
|
+
? `the agent's process ended (${end}); what it printed is kept nowhere`
|
|
85
|
+
: `the agent's process ended: ${stderrTail().trim().slice(-300) || "it printed nothing"}`)));
|
|
86
|
+
return { connection, pid: child.pid, exited, alive: () => !done, stderrTail: quiet ? () => "" : stderrTail, ended: () => end, kill };
|
|
75
87
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ export { acpAdapter, type AcpAdapterOptions, type AcpProxy, type AcpProxySession
|
|
|
2
2
|
export { ACP_CODES, acpFacts, type AcpFacts } from "./facts.js";
|
|
3
3
|
export { homePath, MODEL_ID, recipeProblems, RESERVED_ENV, type AcpBilling, type AcpRecipe, type AcpRefusal } from "./recipe.js";
|
|
4
4
|
export { CALL_STREAM, contextNote, MODEL_STREAM, PERMISSION_STREAM, PROMPT_STREAM, REASK_LIMIT, SESSION_STREAM, sentSubmissions, TOOLS_STREAM } from "./harness.js";
|
|
5
|
-
export { STATE_STREAM, type StateRecord } from "./state.js";
|
|
5
|
+
export { STATE_BUDGET, STATE_STREAM, stateBudgetPassed, stateFiles, type StateRecord } from "./state.js";
|
|
6
6
|
export type { ConfineChild } from "./host/child.js";
|
|
7
7
|
export { GOOSE_INSTALL, GOOSE_NOT_INSTALLED, gooseFacts } from "./goose-facts.js";
|
|
8
8
|
export { gooseAdapter, gooseRecipe, recipeFile, type AcpRecipeFile, type AcpRecipeName, type GooseAdapterOptions, type GooseRecipeOptions } from "./goose.js";
|
package/dist/index.js
CHANGED
|
@@ -3,7 +3,7 @@ export { acpAdapter } from "./adapter.js";
|
|
|
3
3
|
export { ACP_CODES, acpFacts } from "./facts.js";
|
|
4
4
|
export { homePath, MODEL_ID, recipeProblems, RESERVED_ENV } from "./recipe.js";
|
|
5
5
|
export { CALL_STREAM, contextNote, MODEL_STREAM, PERMISSION_STREAM, PROMPT_STREAM, REASK_LIMIT, SESSION_STREAM, sentSubmissions, TOOLS_STREAM } from "./harness.js";
|
|
6
|
-
export { STATE_STREAM } from "./state.js";
|
|
6
|
+
export { STATE_BUDGET, STATE_STREAM, stateBudgetPassed, stateFiles } from "./state.js";
|
|
7
7
|
export { GOOSE_INSTALL, GOOSE_NOT_INSTALLED, gooseFacts } from "./goose-facts.js";
|
|
8
8
|
export { gooseAdapter, gooseRecipe, recipeFile } from "./goose.js";
|
|
9
9
|
export { applyGoose, GOOSE_BETAS, GOOSE_OWN_TOOLS, gooseProxy, goosePolicy, gooseRoutes, gooseToolName, gooseUsage, limitGooseOutput } from "./host/goose-proxy.js";
|
package/dist/recipe.d.ts
CHANGED
|
@@ -31,6 +31,18 @@ export interface AcpRecipe {
|
|
|
31
31
|
* start and handed to the agent under the same name, never written in the recipe. A start whose host lacks one of
|
|
32
32
|
* them is refused with ACP_CODES.keyMissing before anything starts. */
|
|
33
33
|
readonly keys?: readonly string[];
|
|
34
|
+
/** The variable a key reaches the agent as, by its name in `keys`, where it differs: a key saved for this harness alone
|
|
35
|
+
* (ANTIGRAVITY_GEMINI_API_KEY) handed under the name the agent reads (GEMINI_API_KEY). The value is always read by the
|
|
36
|
+
* key's own name, so a value the host holds under the handed name never reaches the agent. */
|
|
37
|
+
readonly keyEnv?: Readonly<Record<string, string>>;
|
|
38
|
+
/** The sign-in method the agent is told with ACP `authenticate` after initialize and before any session opens (its
|
|
39
|
+
* authMethods id: Antigravity's `gemini-api-key`; on its owner's sign-in, none, the agent reading its own). One its initialize does
|
|
40
|
+
* not list is refused with ACP_CODES.authUnlisted, one it refuses with ACP_CODES.authFailed. Absent: none is sent. */
|
|
41
|
+
readonly authMethod?: string;
|
|
42
|
+
/** `none`: nothing the agent prints on stderr is read or kept, nor the words of an error it answers; a failure says
|
|
43
|
+
* its exit status and the adapter's own code alone. For an agent on a person's sign-in, whose token no key cut knows.
|
|
44
|
+
* Default `tail`. */
|
|
45
|
+
readonly stderr?: "tail" | "none";
|
|
34
46
|
/** Files in HOME the agent derives from its keys (Cursor's `.config/cursor/auth.json`): never written, since each
|
|
35
47
|
* start makes every one an empty folder the agent cannot write a file at (an agent named here must run on the key in
|
|
36
48
|
* its env when its save fails, as Cursor 2026.11.13 does), so a hard kill leaves none on disk; never mirrored; and
|
package/dist/recipe.js
CHANGED
|
@@ -2,12 +2,13 @@
|
|
|
2
2
|
// keeps its sessions and who bills its model. The loader's own rules (keys, registry archives, owner installs) are S5's;
|
|
3
3
|
// these are the checks the adapter itself needs before it starts anything. Written for AgentRun.
|
|
4
4
|
import { isAbsolute, normalize, sep } from "node:path";
|
|
5
|
-
|
|
6
|
-
const KEY_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
5
|
+
import { KEY_NAME, launchEnv } from "@parcha/agentrun-kernel";
|
|
7
6
|
/** A model id as an agent lists one (`gpt-5.4-nano[reasoning=medium]`): one line, no spaces, not an option. */
|
|
8
7
|
export const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/=,[\]-]{0,199}$/;
|
|
9
8
|
/** A refusal's code: capitals, digits and `_`. */
|
|
10
9
|
const CODE = /^[A-Z][A-Z0-9_]{1,63}$/;
|
|
10
|
+
/** A sign-in method's id as an agent lists one in authMethods (`gemini-api-key`). */
|
|
11
|
+
const AUTH_METHOD = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
11
12
|
/** `path` in HOME, normalized, or undefined when it leaves HOME (absolute, `..`, or a `$HOME/` prefix spelled out). */
|
|
12
13
|
export function homePath(path) {
|
|
13
14
|
const bare = path.startsWith("$HOME/") ? path.slice("$HOME/".length) : path;
|
|
@@ -45,6 +46,9 @@ export function recipeProblems(recipe) {
|
|
|
45
46
|
const reserved = Object.keys(recipe.env ?? {}).filter((name) => RESERVED_ENV.has(name));
|
|
46
47
|
if (reserved.length)
|
|
47
48
|
problems.push(`the env names ${reserved.join(", ")}, which the adapter sets`);
|
|
49
|
+
const launching = Object.keys(recipe.env ?? {}).filter((name) => !RESERVED_ENV.has(name) && launchEnv(name));
|
|
50
|
+
if (launching.length)
|
|
51
|
+
problems.push(`the env names ${launching.join(", ")}, which change what the agent's process loads or runs`);
|
|
48
52
|
for (const name of recipe.keys ?? []) {
|
|
49
53
|
if (typeof name !== "string" || !KEY_NAME.test(name))
|
|
50
54
|
problems.push(`the key ${JSON.stringify(name)} is not a variable's name (capitals, digits and _)`);
|
|
@@ -65,6 +69,28 @@ export function recipeProblems(recipe) {
|
|
|
65
69
|
problems.push("quiet is a list of words, none empty");
|
|
66
70
|
if (recipe.model !== undefined && (typeof recipe.model !== "string" || !MODEL_ID.test(recipe.model)))
|
|
67
71
|
problems.push(`the model ${JSON.stringify(String(recipe.model).slice(0, 80))} is not a model id`);
|
|
72
|
+
const handed = new Set();
|
|
73
|
+
for (const name of recipe.keys ?? []) {
|
|
74
|
+
const as = recipe.keyEnv?.[name] ?? name;
|
|
75
|
+
if (typeof as !== "string" || !KEY_NAME.test(as))
|
|
76
|
+
problems.push(`the key ${name} is handed as ${JSON.stringify(as)}, which is not a variable's name`);
|
|
77
|
+
else if (RESERVED_ENV.has(as))
|
|
78
|
+
problems.push(`the key ${name} is handed as ${as}, a variable the adapter sets`);
|
|
79
|
+
else if (launchEnv(as))
|
|
80
|
+
problems.push(`the key ${name} is handed as ${as}, which changes what the agent's process loads or runs`);
|
|
81
|
+
else if (as !== name && Object.hasOwn(recipe.env ?? {}, as))
|
|
82
|
+
problems.push(`the key ${name} is handed as ${as}, which is also in env`);
|
|
83
|
+
if (handed.has(as))
|
|
84
|
+
problems.push(`two keys are handed as ${as}`);
|
|
85
|
+
handed.add(as);
|
|
86
|
+
}
|
|
87
|
+
for (const name of Object.keys(recipe.keyEnv ?? {}))
|
|
88
|
+
if (!(recipe.keys ?? []).includes(name))
|
|
89
|
+
problems.push(`keyEnv names ${name}, which is not one of the keys`);
|
|
90
|
+
if (recipe.authMethod !== undefined && (typeof recipe.authMethod !== "string" || !AUTH_METHOD.test(recipe.authMethod)))
|
|
91
|
+
problems.push(`the sign-in method ${JSON.stringify(String(recipe.authMethod).slice(0, 80))} is not a method's id`);
|
|
92
|
+
if (recipe.stderr !== undefined && recipe.stderr !== "tail" && recipe.stderr !== "none")
|
|
93
|
+
problems.push('stderr is "tail" or "none"');
|
|
68
94
|
return problems;
|
|
69
95
|
}
|
|
70
96
|
/** The variables the adapter sets itself: a recipe never names them. */
|
package/dist/state.d.ts
CHANGED
|
@@ -1,18 +1,26 @@
|
|
|
1
1
|
import type { NativeJournal } from "@parcha/agentrun-kernel/process";
|
|
2
2
|
/** The journal stream that holds the agent's session store. */
|
|
3
3
|
export declare const STATE_STREAM = "acp.state";
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
sha256?: string;
|
|
7
|
-
data?: string;
|
|
8
|
-
deleted?: true;
|
|
9
|
-
}
|
|
4
|
+
/** One record of STATE_STREAM. Its shape is the mirror's own (stateFiles reads it). */
|
|
5
|
+
export type StateRecord = Readonly<Record<string, unknown>>;
|
|
10
6
|
/** A file the mirror never takes: its name says it holds a credential. */
|
|
11
7
|
export declare const CREDENTIAL_FILE: RegExp;
|
|
12
8
|
/** The most bytes one file may have to be mirrored; a larger one is skipped, said in the log. */
|
|
13
9
|
export declare const MAX_STATE_FILE: number;
|
|
14
|
-
/** The
|
|
15
|
-
|
|
10
|
+
/** The bytes of one piece of a mirrored file. Small enough that a take of a store that grows by appending costs little
|
|
11
|
+
* past what it wrote (its last piece again), large enough that a file's record stays short. */
|
|
12
|
+
export declare const STATE_PIECE: number;
|
|
13
|
+
/** The most bytes a session's mirror records hold: a quarter of the run channel's frame (32 MiB), so a resume that reads
|
|
14
|
+
* them back always fits. */
|
|
15
|
+
export declare const STATE_BUDGET: number;
|
|
16
|
+
/** What the run is told when its mirror passes its budget (`limit` bytes, STATE_BUDGET unless a test's). */
|
|
17
|
+
export declare const stateBudgetPassed: (limit?: number) => string;
|
|
18
|
+
/** Whether the records say the mirror passed its budget: then they restore nothing. */
|
|
19
|
+
export declare const stateDropped: (records: readonly StateRecord[]) => boolean;
|
|
20
|
+
/** The files the records give back, by their path in HOME: the newest record of each, made whole from its pieces. None
|
|
21
|
+
* once the mirror passed its budget (its newest takes were never written). A file a piece of which is missing, or
|
|
22
|
+
* whose bytes do not match its sha256, is left out: never a file the agent did not write. */
|
|
23
|
+
export declare function stateFiles(records: readonly StateRecord[]): Map<string, Buffer>;
|
|
16
24
|
/** Write the mirrored files back into `home`. */
|
|
17
25
|
export declare function restoreState(home: string, records: readonly StateRecord[]): void;
|
|
18
26
|
/** The mirror of one agent process's HOME: what changed since the records' newest, appended to `journal`. */
|
|
@@ -23,11 +31,22 @@ export declare class StateMirror {
|
|
|
23
31
|
* credentials it names. */
|
|
24
32
|
private readonly skip;
|
|
25
33
|
private readonly log;
|
|
34
|
+
/** Says to the run, in words, that the mirror passed its budget (once, when it does). */
|
|
35
|
+
private readonly say;
|
|
36
|
+
private readonly budget;
|
|
26
37
|
private readonly known;
|
|
38
|
+
/** The pieces the session's records hold already. */
|
|
39
|
+
private readonly pieces;
|
|
40
|
+
/** The bytes the session's mirror records hold. */
|
|
41
|
+
private spent;
|
|
42
|
+
/** The mirror passed its budget: it takes nothing more. */
|
|
43
|
+
private dropped;
|
|
27
44
|
constructor(home: string, paths: readonly string[],
|
|
28
45
|
/** Paths in HOME never mirrored, each a file or a folder: the recipe's own files (written at every start) and the
|
|
29
46
|
* credentials it names. */
|
|
30
|
-
skip: ReadonlySet<string>, records: readonly StateRecord[], log?: (message: string, fields?: Record<string, unknown>) => void
|
|
47
|
+
skip: ReadonlySet<string>, records: readonly StateRecord[], log?: (message: string, fields?: Record<string, unknown>) => void,
|
|
48
|
+
/** Says to the run, in words, that the mirror passed its budget (once, when it does). */
|
|
49
|
+
say?: (words: string) => void, budget?: number);
|
|
31
50
|
/** Append what changed to `journal` (the caller flushes). Returns how many records it appended. */
|
|
32
51
|
take(journal: NativeJournal, stream?: string): number;
|
|
33
52
|
}
|
package/dist/state.js
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
// The agent's own session store, mirrored into the session's records and given back to the next agent process. ACP has
|
|
2
2
|
// no hook before a paid request, so the mirror is taken at the points the adapter sees: after session/new, after each
|
|
3
3
|
// finished tool call, and at each turn's end. Written for AgentRun.
|
|
4
|
-
// - Each file under the recipe's `state` paths is
|
|
5
|
-
//
|
|
6
|
-
//
|
|
4
|
+
// - Each file under the recipe's `state` paths is cut into pieces of STATE_PIECE bytes, each kept by its sha256 and
|
|
5
|
+
// written once per session, whichever file or take holds it again; a file's record lists its pieces in order, or says
|
|
6
|
+
// it was deleted. Only a file whose bytes changed since its last record is written again, and then only its new
|
|
7
|
+
// pieces: a store that grows by appending (SQLite's WAL) costs a take what it wrote, never a whole copy. A file's
|
|
8
|
+
// pieces and its record go in one batch, so a kill leaves the previous whole set. The record shape is this file's own:
|
|
9
|
+
// a reader goes through stateFiles or restoreState.
|
|
10
|
+
// - SQLite's shared-memory index (`*-shm`) is never mirrored: SQLite builds it again from the WAL when it opens the store.
|
|
7
11
|
// - A file whose name says it holds a credential (a token, a key, an auth or credentials file) is never mirrored, and the
|
|
8
12
|
// recipe's own files (written fresh at every start) and the credentials it names (whatever their names) are not either.
|
|
13
|
+
// - A session's mirror holds at most STATE_BUDGET bytes of records. A take that would pass it writes one record saying
|
|
14
|
+
// so and the mirror stops: from then on a resume gives the agent no store, and it starts fresh with the conversation
|
|
15
|
+
// so far (the adapter's path for an agent that cannot load its session). The journal stays bounded whatever the turns.
|
|
9
16
|
// - The next process's HOME gets the newest record of each path back, before the agent starts.
|
|
10
17
|
import { createHash } from "node:crypto";
|
|
11
18
|
import { lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
@@ -16,7 +23,21 @@ export const STATE_STREAM = "acp.state";
|
|
|
16
23
|
export const CREDENTIAL_FILE = /(^|[._-])(credentials?|tokens?|auth|secrets?|keyring|keychain|cookies?)([._-]|$)|\.(pem|key|p12)$/i;
|
|
17
24
|
/** The most bytes one file may have to be mirrored; a larger one is skipped, said in the log. */
|
|
18
25
|
export const MAX_STATE_FILE = 16 * 1024 * 1024;
|
|
26
|
+
/** The bytes of one piece of a mirrored file. Small enough that a take of a store that grows by appending costs little
|
|
27
|
+
* past what it wrote (its last piece again), large enough that a file's record stays short. */
|
|
28
|
+
export const STATE_PIECE = 64 * 1024;
|
|
29
|
+
/** The most bytes a session's mirror records hold: a quarter of the run channel's frame (32 MiB), so a resume that reads
|
|
30
|
+
* them back always fits. */
|
|
31
|
+
export const STATE_BUDGET = 8 * 1024 * 1024;
|
|
32
|
+
/** What the run is told when its mirror passes its budget (`limit` bytes, STATE_BUDGET unless a test's). */
|
|
33
|
+
export const stateBudgetPassed = (limit = STATE_BUDGET) => `The agent's session state passed ${Number((limit / (1024 * 1024)).toFixed(2))} MiB, so a resume starts it fresh with the conversation so far.`;
|
|
19
34
|
const sha = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
35
|
+
/** The bytes a record holds in the journal, as its JSON. */
|
|
36
|
+
const sizeOf = (record) => Buffer.byteLength(JSON.stringify(record));
|
|
37
|
+
const isPiece = (record) => typeof record?.piece === "string" && typeof record.data === "string";
|
|
38
|
+
const isDropped = (record) => record?.dropped === true;
|
|
39
|
+
/** SQLite's shared-memory index beside a WAL store: built again from the WAL at open, never mirrored. */
|
|
40
|
+
const SHARED_MEMORY = /-shm$/;
|
|
20
41
|
/** A file or directory the agent removed (or replaced with a file) while the walk read it: gone, never an error. */
|
|
21
42
|
const gone = (error) => ["ENOENT", "ENOTDIR"].includes(error?.code ?? "");
|
|
22
43
|
/** `read()`, or undefined when what it reads is gone. Any other error is thrown: the mirror says nothing it did not read. */
|
|
@@ -47,7 +68,8 @@ function filesUnder(home, paths, skip, log) {
|
|
|
47
68
|
visit(join(absolute, name));
|
|
48
69
|
return;
|
|
49
70
|
}
|
|
50
|
-
|
|
71
|
+
const name = path.split("/").at(-1) ?? "";
|
|
72
|
+
if (!stat.isFile() || skipped(path, skip) || CREDENTIAL_FILE.test(name) || SHARED_MEMORY.test(name))
|
|
51
73
|
return;
|
|
52
74
|
if (stat.size > MAX_STATE_FILE) {
|
|
53
75
|
log("acp: a state file too large to mirror was skipped", { path, bytes: stat.size });
|
|
@@ -89,27 +111,50 @@ function filesUnder(home, paths, skip, log) {
|
|
|
89
111
|
}
|
|
90
112
|
return out;
|
|
91
113
|
}
|
|
92
|
-
/** The newest record of each path, as the records hold them. */
|
|
93
|
-
|
|
114
|
+
/** The newest record of each path, as the records hold them: a file's pieces, or its deletion. */
|
|
115
|
+
function foldFiles(records) {
|
|
94
116
|
const out = new Map();
|
|
95
117
|
for (const record of records) {
|
|
96
118
|
if (!record || typeof record.path !== "string")
|
|
97
119
|
continue;
|
|
98
|
-
if (record.deleted)
|
|
120
|
+
if (record.deleted === true)
|
|
99
121
|
out.delete(record.path);
|
|
100
|
-
else
|
|
101
|
-
out.set(record.path, record);
|
|
122
|
+
else if (typeof record.sha256 === "string" && Array.isArray(record.pieces) && record.pieces.every((piece) => typeof piece === "string"))
|
|
123
|
+
out.set(record.path, { sha256: record.sha256, pieces: record.pieces });
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
/** Whether the records say the mirror passed its budget: then they restore nothing. */
|
|
128
|
+
export const stateDropped = (records) => records.some(isDropped);
|
|
129
|
+
/** The files the records give back, by their path in HOME: the newest record of each, made whole from its pieces. None
|
|
130
|
+
* once the mirror passed its budget (its newest takes were never written). A file a piece of which is missing, or
|
|
131
|
+
* whose bytes do not match its sha256, is left out: never a file the agent did not write. */
|
|
132
|
+
export function stateFiles(records) {
|
|
133
|
+
const out = new Map();
|
|
134
|
+
if (stateDropped(records))
|
|
135
|
+
return out;
|
|
136
|
+
const pieces = new Map();
|
|
137
|
+
for (const record of records)
|
|
138
|
+
if (isPiece(record))
|
|
139
|
+
pieces.set(record.piece, record.data);
|
|
140
|
+
for (const [path, record] of foldFiles(records)) {
|
|
141
|
+
if (path.split("/").includes(".."))
|
|
142
|
+
continue;
|
|
143
|
+
const parts = record.pieces.map((digest) => pieces.get(digest));
|
|
144
|
+
if (!parts.every((part) => part !== undefined))
|
|
145
|
+
continue;
|
|
146
|
+
const bytes = Buffer.concat(parts.map((part) => Buffer.from(part, "base64")));
|
|
147
|
+
if (sha(bytes) === record.sha256)
|
|
148
|
+
out.set(path, bytes);
|
|
102
149
|
}
|
|
103
150
|
return out;
|
|
104
151
|
}
|
|
105
152
|
/** Write the mirrored files back into `home`. */
|
|
106
153
|
export function restoreState(home, records) {
|
|
107
|
-
for (const [path,
|
|
108
|
-
if (record.data === undefined || path.split("/").includes(".."))
|
|
109
|
-
continue;
|
|
154
|
+
for (const [path, bytes] of stateFiles(records)) {
|
|
110
155
|
const file = join(home, ...path.split("/"));
|
|
111
156
|
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
112
|
-
writeFileSync(file,
|
|
157
|
+
writeFileSync(file, bytes, { mode: 0o600 });
|
|
113
158
|
}
|
|
114
159
|
}
|
|
115
160
|
/** The mirror of one agent process's HOME: what changed since the records' newest, appended to `journal`. */
|
|
@@ -118,40 +163,88 @@ export class StateMirror {
|
|
|
118
163
|
paths;
|
|
119
164
|
skip;
|
|
120
165
|
log;
|
|
166
|
+
say;
|
|
167
|
+
budget;
|
|
121
168
|
known = new Map();
|
|
169
|
+
/** The pieces the session's records hold already. */
|
|
170
|
+
pieces = new Set();
|
|
171
|
+
/** The bytes the session's mirror records hold. */
|
|
172
|
+
spent = 0;
|
|
173
|
+
/** The mirror passed its budget: it takes nothing more. */
|
|
174
|
+
dropped;
|
|
122
175
|
constructor(home, paths,
|
|
123
176
|
/** Paths in HOME never mirrored, each a file or a folder: the recipe's own files (written at every start) and the
|
|
124
177
|
* credentials it names. */
|
|
125
|
-
skip, records, log = () => { }
|
|
178
|
+
skip, records, log = () => { },
|
|
179
|
+
/** Says to the run, in words, that the mirror passed its budget (once, when it does). */
|
|
180
|
+
say = () => { }, budget = STATE_BUDGET) {
|
|
126
181
|
this.home = home;
|
|
127
182
|
this.paths = paths;
|
|
128
183
|
this.skip = skip;
|
|
129
184
|
this.log = log;
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
185
|
+
this.say = say;
|
|
186
|
+
this.budget = budget;
|
|
187
|
+
this.dropped = stateDropped(records);
|
|
188
|
+
for (const record of records) {
|
|
189
|
+
this.spent += sizeOf(record);
|
|
190
|
+
if (isPiece(record))
|
|
191
|
+
this.pieces.add(record.piece);
|
|
192
|
+
}
|
|
193
|
+
for (const [path, record] of foldFiles(records))
|
|
194
|
+
this.known.set(path, record.sha256);
|
|
133
195
|
}
|
|
134
196
|
/** Append what changed to `journal` (the caller flushes). Returns how many records it appended. */
|
|
135
197
|
take(journal, stream = STATE_STREAM) {
|
|
136
|
-
if (this.paths.length === 0)
|
|
198
|
+
if (this.paths.length === 0 || this.dropped)
|
|
137
199
|
return 0;
|
|
138
200
|
const now = filesUnder(this.home, this.paths, this.skip, this.log);
|
|
139
|
-
|
|
201
|
+
// The take's records, written only once all of them are known to fit: one batch, never part of a take.
|
|
202
|
+
const records = [];
|
|
203
|
+
const known = new Map(this.known);
|
|
204
|
+
const pieces = new Set();
|
|
140
205
|
for (const [path, bytes] of now) {
|
|
141
206
|
const digest = sha(bytes);
|
|
142
|
-
if (
|
|
207
|
+
if (known.get(path) === digest)
|
|
143
208
|
continue;
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
209
|
+
const list = [];
|
|
210
|
+
for (let at = 0; at < bytes.length; at += STATE_PIECE) {
|
|
211
|
+
const part = bytes.subarray(at, at + STATE_PIECE);
|
|
212
|
+
const piece = sha(part);
|
|
213
|
+
list.push(piece);
|
|
214
|
+
if (this.pieces.has(piece) || pieces.has(piece))
|
|
215
|
+
continue;
|
|
216
|
+
pieces.add(piece);
|
|
217
|
+
records.push({ piece, data: part.toString("base64") });
|
|
218
|
+
}
|
|
219
|
+
records.push({ path, sha256: digest, pieces: list });
|
|
220
|
+
known.set(path, digest);
|
|
147
221
|
}
|
|
148
|
-
for (const path of [...
|
|
222
|
+
for (const path of [...known.keys()]) {
|
|
149
223
|
if (now.has(path))
|
|
150
224
|
continue;
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
appended++;
|
|
225
|
+
records.push({ path, deleted: true });
|
|
226
|
+
known.delete(path);
|
|
154
227
|
}
|
|
155
|
-
|
|
228
|
+
if (records.length === 0)
|
|
229
|
+
return 0;
|
|
230
|
+
const bytes = records.reduce((sum, record) => sum + sizeOf(record), 0);
|
|
231
|
+
if (this.spent + bytes > this.budget) {
|
|
232
|
+
const dropped = { dropped: true, bytes: this.spent + bytes, limit: this.budget };
|
|
233
|
+
journal.append(stream, dropped);
|
|
234
|
+
this.spent += sizeOf(dropped);
|
|
235
|
+
this.dropped = true;
|
|
236
|
+
this.log("acp: the agent's session state passed the mirror's budget; it is mirrored no more, and a resume starts fresh", { bytes: dropped.bytes, limit: this.budget });
|
|
237
|
+
this.say(stateBudgetPassed(this.budget));
|
|
238
|
+
return 1;
|
|
239
|
+
}
|
|
240
|
+
for (const record of records)
|
|
241
|
+
journal.append(stream, record);
|
|
242
|
+
this.spent += bytes;
|
|
243
|
+
for (const piece of pieces)
|
|
244
|
+
this.pieces.add(piece);
|
|
245
|
+
this.known.clear();
|
|
246
|
+
for (const [path, digest] of known)
|
|
247
|
+
this.known.set(path, digest);
|
|
248
|
+
return records.length;
|
|
156
249
|
}
|
|
157
250
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/agentrun-harness-acp",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.53",
|
|
4
4
|
"description": "Any Agent Client Protocol agent as an AgentRun harness: the agent over stdio in a private HOME, the host's tools as one loopback MCP server, its permission asks through the host's gate, durable in AgentRun's own store.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentrun",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
51
|
"@agentclientprotocol/sdk": "2.7.0",
|
|
52
|
-
"@parcha/agentrun-kernel": "0.1.0-beta.
|
|
52
|
+
"@parcha/agentrun-kernel": "0.1.0-beta.53",
|
|
53
53
|
"zod": "4.6.6"
|
|
54
54
|
},
|
|
55
55
|
"publishConfig": {
|
|
@@ -36,12 +36,20 @@
|
|
|
36
36
|
// tally: a file the takes of a `retitled` native step are counted in: a step {native, title, retitled: [t2, t3, ...]}
|
|
37
37
|
// asks with its title the first time and with the next of `retitled` each time it is taken again (the last
|
|
38
38
|
// one repeats), its input's command that title, as Cursor writes a new command after a restart.
|
|
39
|
+
// auth: {methods, home, key, leak}: initialize lists the sign-in methods `methods` (ids); session/new and
|
|
40
|
+
// session/load are refused (authRequired) until `authenticate` takes one. `home` {method, env, file}: that
|
|
41
|
+
// method reads `file` in the folder the variable `env` names, the sign-in a person's own login left there, and
|
|
42
|
+
// rewrites it as an agent refreshing its token does. `key` {method, env}: that method reads the key in the
|
|
43
|
+
// variable `env`. `leak`: at session/new, say the token or key it signed in with: "exit" on stderr, then exit 1;
|
|
44
|
+
// "answer" in the words of the error it answers, alive.
|
|
45
|
+
// grow: {bytes}: at each save of a session, append `bytes` random bytes to <sessions>/store.db-wal and rewrite a
|
|
46
|
+
// store.db-shm beside it: a store that grows each turn, as Cursor's SQLite WAL does.
|
|
39
47
|
// A script step {hang: true} is a model that never answers (until a cancel the agent heeds).
|
|
40
48
|
// The step the model takes is the number it took before: its session's history (calls, native calls, answers), plus the
|
|
41
49
|
// calls a recovery or context note names that its history does not hold, as a resumed model reads its conversation.
|
|
42
50
|
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
43
51
|
import { spawn } from "node:child_process";
|
|
44
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
52
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
45
53
|
import { dirname, join } from "node:path";
|
|
46
54
|
import { createInterface } from "node:readline";
|
|
47
55
|
import { Readable, Writable } from "node:stream";
|
|
@@ -73,6 +81,13 @@ const save = (session) => {
|
|
|
73
81
|
if (!loads) return;
|
|
74
82
|
mkdirSync(store, { recursive: true });
|
|
75
83
|
writeFileSync(join(store, `${session.id}.json`), JSON.stringify({ id: session.id, history: session.history }));
|
|
84
|
+
if (config.grow) {
|
|
85
|
+
// A store that grows by appending, as SQLite's WAL does: `bytes` more at each save, and its shared-memory index
|
|
86
|
+
// rewritten beside it.
|
|
87
|
+
const wal = join(store, "store.db-wal");
|
|
88
|
+
appendFileSync(wal, randomBytes(config.grow.bytes));
|
|
89
|
+
writeFileSync(join(store, "store.db-shm"), randomBytes(32 * 1024));
|
|
90
|
+
}
|
|
76
91
|
};
|
|
77
92
|
const sessions = new Map();
|
|
78
93
|
// What it was started with: the names in its environment (never their values), its HOME and its directory.
|
|
@@ -333,6 +348,32 @@ async function takeTurn(client, session, prompt, signal) {
|
|
|
333
348
|
}
|
|
334
349
|
}
|
|
335
350
|
|
|
351
|
+
/** What `authenticate` signed in with (auth): the token's or the key's text; undefined before. */
|
|
352
|
+
let signedIn;
|
|
353
|
+
/** Refuses a session before the sign-in, where the config signs in; says it, where the config leaks it. */
|
|
354
|
+
const needsSignIn = () => {
|
|
355
|
+
if (!config.auth) return;
|
|
356
|
+
if (signedIn === undefined) throw RequestError.authRequired();
|
|
357
|
+
if (config.auth.leak === "exit") {
|
|
358
|
+
process.stderr.write(`fake-acp: the vendor refused the sign-in ${signedIn}\n`);
|
|
359
|
+
process.exit(1);
|
|
360
|
+
}
|
|
361
|
+
if (config.auth.leak === "answer") throw RequestError.internalError(undefined, `the vendor refused the sign-in ${signedIn}`);
|
|
362
|
+
};
|
|
363
|
+
/** The sign-in `methodId` reads, or undefined when it has none. */
|
|
364
|
+
const signInWith = (methodId) => {
|
|
365
|
+
const { home: login, key } = config.auth ?? {};
|
|
366
|
+
if (login && methodId === login.method) {
|
|
367
|
+
const file = process.env[login.env] ? join(process.env[login.env], login.file) : undefined;
|
|
368
|
+
if (!file || !existsSync(file)) return undefined;
|
|
369
|
+
const text = readFileSync(file, "utf8");
|
|
370
|
+
writeFileSync(file, `${text.trim()}\n`);
|
|
371
|
+
return text.trim();
|
|
372
|
+
}
|
|
373
|
+
if (key && methodId === key.method) return process.env[key.env] || undefined;
|
|
374
|
+
return undefined;
|
|
375
|
+
};
|
|
376
|
+
|
|
336
377
|
const app = agent({ name: "fake-acp" })
|
|
337
378
|
.onRequest("initialize", () => ({
|
|
338
379
|
protocolVersion: 1,
|
|
@@ -342,8 +383,17 @@ const app = agent({ name: "fake-acp" })
|
|
|
342
383
|
...(config.systemPrompt ? { sessionCapabilities: { systemPrompt: {} } } : {}),
|
|
343
384
|
},
|
|
344
385
|
agentInfo: { name: "fake-acp", version: "1.0.0" },
|
|
386
|
+
authMethods: (config.auth?.methods ?? []).map((id) => ({ id, name: id })),
|
|
345
387
|
}))
|
|
388
|
+
.onRequest("authenticate", ({ params }) => {
|
|
389
|
+
const text = signInWith(params.methodId);
|
|
390
|
+
if (text === undefined) throw RequestError.authRequired({ methodId: params.methodId });
|
|
391
|
+
said({ type: "authenticate", methodId: params.methodId, sha: createHash("sha256").update(text).digest("hex") });
|
|
392
|
+
signedIn = text;
|
|
393
|
+
return {};
|
|
394
|
+
})
|
|
346
395
|
.onRequest("session/new", async ({ params }) => {
|
|
396
|
+
needsSignIn();
|
|
347
397
|
if (config.failNew) {
|
|
348
398
|
process.stderr.write(`${config.failNew}\n`);
|
|
349
399
|
process.exit(1);
|
|
@@ -362,6 +412,7 @@ const app = agent({ name: "fake-acp" })
|
|
|
362
412
|
return {};
|
|
363
413
|
})
|
|
364
414
|
.onRequest("session/load", async ({ params, client }) => {
|
|
415
|
+
needsSignIn();
|
|
365
416
|
const file = join(store, `${params.sessionId}.json`);
|
|
366
417
|
if (!loads || !existsSync(file)) throw RequestError.resourceNotFound(params.sessionId);
|
|
367
418
|
const { history } = JSON.parse(readFileSync(file, "utf8"));
|