@buildanagent/harness 0.0.0-stage → 0.1.0-alpha.28
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/LICENSE +54 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +716 -2
- package/dist/ablation.d.ts +2 -0
- package/dist/ablation.js +3 -0
- package/dist/ablation.js.map +1 -0
- package/dist/completion/check.d.ts +64 -0
- package/dist/completion/check.js +152 -0
- package/dist/completion/check.js.map +1 -0
- package/dist/completion/checks.d.ts +45 -0
- package/dist/completion/checks.js +173 -0
- package/dist/completion/checks.js.map +1 -0
- package/dist/completion/flags.d.ts +25 -0
- package/dist/completion/flags.js +87 -0
- package/dist/completion/flags.js.map +1 -0
- package/dist/completion/index.d.ts +8 -0
- package/dist/completion/index.js +9 -0
- package/dist/completion/index.js.map +1 -0
- package/dist/completion/snapshot.d.ts +33 -0
- package/dist/completion/snapshot.js +83 -0
- package/dist/completion/snapshot.js.map +1 -0
- package/dist/context/cap.d.ts +32 -0
- package/dist/context/cap.js +50 -0
- package/dist/context/cap.js.map +1 -0
- package/dist/context/estimate.d.ts +18 -0
- package/dist/context/estimate.js +20 -0
- package/dist/context/estimate.js.map +1 -0
- package/dist/context/file-spill.d.ts +5 -0
- package/dist/context/file-spill.js +25 -0
- package/dist/context/file-spill.js.map +1 -0
- package/dist/context/index.d.ts +10 -0
- package/dist/context/index.js +10 -0
- package/dist/context/index.js.map +1 -0
- package/dist/context/mask.d.ts +27 -0
- package/dist/context/mask.js +71 -0
- package/dist/context/mask.js.map +1 -0
- package/dist/context/mid-turn.d.ts +40 -0
- package/dist/context/mid-turn.js +82 -0
- package/dist/context/mid-turn.js.map +1 -0
- package/dist/context/policy.d.ts +9 -0
- package/dist/context/policy.js +140 -0
- package/dist/context/policy.js.map +1 -0
- package/dist/context/spill-ledger.d.ts +25 -0
- package/dist/context/spill-ledger.js +54 -0
- package/dist/context/spill-ledger.js.map +1 -0
- package/dist/context/spill.d.ts +6 -0
- package/dist/context/spill.js +14 -0
- package/dist/context/spill.js.map +1 -0
- package/dist/context/summarize.d.ts +53 -0
- package/dist/context/summarize.js +204 -0
- package/dist/context/summarize.js.map +1 -0
- package/dist/context/summary-template.d.ts +29 -0
- package/dist/context/summary-template.js +69 -0
- package/dist/context/summary-template.js.map +1 -0
- package/dist/context/types.d.ts +150 -0
- package/dist/context/types.js +2 -0
- package/dist/context/types.js.map +1 -0
- package/dist/context/write-cap.d.ts +19 -0
- package/dist/context/write-cap.js +41 -0
- package/dist/context/write-cap.js.map +1 -0
- package/dist/create-harness.d.ts +7 -0
- package/dist/create-harness.js +21 -0
- package/dist/create-harness.js.map +1 -0
- package/dist/credentials/addresses.d.ts +14 -0
- package/dist/credentials/addresses.js +144 -0
- package/dist/credentials/addresses.js.map +1 -0
- package/dist/credentials/allowlist.d.ts +34 -0
- package/dist/credentials/allowlist.js +77 -0
- package/dist/credentials/allowlist.js.map +1 -0
- package/dist/credentials/egress-proxy.d.ts +70 -0
- package/dist/credentials/egress-proxy.js +482 -0
- package/dist/credentials/egress-proxy.js.map +1 -0
- package/dist/credentials/index.d.ts +9 -0
- package/dist/credentials/index.js +10 -0
- package/dist/credentials/index.js.map +1 -0
- package/dist/credentials/scrub.d.ts +16 -0
- package/dist/credentials/scrub.js +93 -0
- package/dist/credentials/scrub.js.map +1 -0
- package/dist/errors.d.ts +56 -0
- package/dist/errors.js +63 -0
- package/dist/errors.js.map +1 -0
- package/dist/extensions/compose.d.ts +27 -0
- package/dist/extensions/compose.js +83 -0
- package/dist/extensions/compose.js.map +1 -0
- package/dist/extensions/context-files-node.d.ts +28 -0
- package/dist/extensions/context-files-node.js +74 -0
- package/dist/extensions/context-files-node.js.map +1 -0
- package/dist/extensions/context-files.d.ts +68 -0
- package/dist/extensions/context-files.js +214 -0
- package/dist/extensions/context-files.js.map +1 -0
- package/dist/extensions/digest.d.ts +6 -0
- package/dist/extensions/digest.js +68 -0
- package/dist/extensions/digest.js.map +1 -0
- package/dist/extensions/index.d.ts +10 -0
- package/dist/extensions/index.js +10 -0
- package/dist/extensions/index.js.map +1 -0
- package/dist/extensions/load.d.ts +42 -0
- package/dist/extensions/load.js +211 -0
- package/dist/extensions/load.js.map +1 -0
- package/dist/extensions/lock.d.ts +8 -0
- package/dist/extensions/lock.js +95 -0
- package/dist/extensions/lock.js.map +1 -0
- package/dist/extensions/node.d.ts +10 -0
- package/dist/extensions/node.js +11 -0
- package/dist/extensions/node.js.map +1 -0
- package/dist/extensions/project-dirs.d.ts +24 -0
- package/dist/extensions/project-dirs.js +97 -0
- package/dist/extensions/project-dirs.js.map +1 -0
- package/dist/extensions/skills-node.d.ts +34 -0
- package/dist/extensions/skills-node.js +123 -0
- package/dist/extensions/skills-node.js.map +1 -0
- package/dist/extensions/skills.d.ts +51 -0
- package/dist/extensions/skills.js +175 -0
- package/dist/extensions/skills.js.map +1 -0
- package/dist/extensions/trust-file.d.ts +3 -0
- package/dist/extensions/trust-file.js +62 -0
- package/dist/extensions/trust-file.js.map +1 -0
- package/dist/extensions/trust-store-node.d.ts +10 -0
- package/dist/extensions/trust-store-node.js +33 -0
- package/dist/extensions/trust-store-node.js.map +1 -0
- package/dist/extensions/types.d.ts +42 -0
- package/dist/extensions/types.js +2 -0
- package/dist/extensions/types.js.map +1 -0
- package/dist/harness.d.ts +156 -0
- package/dist/harness.js +2 -0
- package/dist/harness.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/connection.d.ts +22 -0
- package/dist/mcp/connection.js +267 -0
- package/dist/mcp/connection.js.map +1 -0
- package/dist/mcp/content.d.ts +27 -0
- package/dist/mcp/content.js +177 -0
- package/dist/mcp/content.js.map +1 -0
- package/dist/mcp/errors.d.ts +19 -0
- package/dist/mcp/errors.js +21 -0
- package/dist/mcp/errors.js.map +1 -0
- package/dist/mcp/index.d.ts +10 -0
- package/dist/mcp/index.js +10 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/manager.d.ts +7 -0
- package/dist/mcp/manager.js +173 -0
- package/dist/mcp/manager.js.map +1 -0
- package/dist/mcp/record.d.ts +7 -0
- package/dist/mcp/record.js +20 -0
- package/dist/mcp/record.js.map +1 -0
- package/dist/mcp/stdio.d.ts +39 -0
- package/dist/mcp/stdio.js +382 -0
- package/dist/mcp/stdio.js.map +1 -0
- package/dist/mcp/types.d.ts +172 -0
- package/dist/mcp/types.js +2 -0
- package/dist/mcp/types.js.map +1 -0
- package/dist/memory/index.d.ts +2 -0
- package/dist/memory/index.js +3 -0
- package/dist/memory/index.js.map +1 -0
- package/dist/permissions/default-rules.d.ts +7 -0
- package/dist/permissions/default-rules.js +42 -0
- package/dist/permissions/default-rules.js.map +1 -0
- package/dist/permissions/errors.d.ts +11 -0
- package/dist/permissions/errors.js +14 -0
- package/dist/permissions/errors.js.map +1 -0
- package/dist/permissions/index.d.ts +9 -0
- package/dist/permissions/index.js +9 -0
- package/dist/permissions/index.js.map +1 -0
- package/dist/permissions/match.d.ts +33 -0
- package/dist/permissions/match.js +287 -0
- package/dist/permissions/match.js.map +1 -0
- package/dist/permissions/pipeline.d.ts +9 -0
- package/dist/permissions/pipeline.js +235 -0
- package/dist/permissions/pipeline.js.map +1 -0
- package/dist/permissions/rules.d.ts +22 -0
- package/dist/permissions/rules.js +74 -0
- package/dist/permissions/rules.js.map +1 -0
- package/dist/permissions/shadow.d.ts +5 -0
- package/dist/permissions/shadow.js +22 -0
- package/dist/permissions/shadow.js.map +1 -0
- package/dist/permissions/types.d.ts +104 -0
- package/dist/permissions/types.js +2 -0
- package/dist/permissions/types.js.map +1 -0
- package/dist/sandbox/base.d.ts +35 -0
- package/dist/sandbox/base.js +60 -0
- package/dist/sandbox/base.js.map +1 -0
- package/dist/sandbox/docker/index.d.ts +35 -0
- package/dist/sandbox/docker/index.js +448 -0
- package/dist/sandbox/docker/index.js.map +1 -0
- package/dist/sandbox/errors.d.ts +16 -0
- package/dist/sandbox/errors.js +22 -0
- package/dist/sandbox/errors.js.map +1 -0
- package/dist/sandbox/host-files.d.ts +63 -0
- package/dist/sandbox/host-files.js +248 -0
- package/dist/sandbox/host-files.js.map +1 -0
- package/dist/sandbox/index.d.ts +8 -0
- package/dist/sandbox/index.js +8 -0
- package/dist/sandbox/index.js.map +1 -0
- package/dist/sandbox/none.d.ts +17 -0
- package/dist/sandbox/none.js +108 -0
- package/dist/sandbox/none.js.map +1 -0
- package/dist/sandbox/process.d.ts +61 -0
- package/dist/sandbox/process.js +253 -0
- package/dist/sandbox/process.js.map +1 -0
- package/dist/sandbox/spawn-env.d.ts +20 -0
- package/dist/sandbox/spawn-env.js +128 -0
- package/dist/sandbox/spawn-env.js.map +1 -0
- package/dist/sandbox/srt/index.d.ts +35 -0
- package/dist/sandbox/srt/index.js +264 -0
- package/dist/sandbox/srt/index.js.map +1 -0
- package/dist/sandbox/srt/settings.d.ts +48 -0
- package/dist/sandbox/srt/settings.js +31 -0
- package/dist/sandbox/srt/settings.js.map +1 -0
- package/dist/sandbox/types.d.ts +88 -0
- package/dist/sandbox/types.js +6 -0
- package/dist/sandbox/types.js.map +1 -0
- package/dist/server/answers.d.ts +16 -0
- package/dist/server/answers.js +43 -0
- package/dist/server/answers.js.map +1 -0
- package/dist/server/connection.d.ts +99 -0
- package/dist/server/connection.js +309 -0
- package/dist/server/connection.js.map +1 -0
- package/dist/server/dispatcher.d.ts +86 -0
- package/dist/server/dispatcher.js +800 -0
- package/dist/server/dispatcher.js.map +1 -0
- package/dist/server/index.d.ts +13 -0
- package/dist/server/index.js +12 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/local-transport.d.ts +44 -0
- package/dist/server/local-transport.js +103 -0
- package/dist/server/local-transport.js.map +1 -0
- package/dist/server/outbox.d.ts +31 -0
- package/dist/server/outbox.js +130 -0
- package/dist/server/outbox.js.map +1 -0
- package/dist/server/params.d.ts +25 -0
- package/dist/server/params.js +112 -0
- package/dist/server/params.js.map +1 -0
- package/dist/server/protocol.schema.json +2448 -0
- package/dist/server/rpc-session.d.ts +43 -0
- package/dist/server/rpc-session.js +167 -0
- package/dist/server/rpc-session.js.map +1 -0
- package/dist/server/stdio-streams.d.ts +67 -0
- package/dist/server/stdio-streams.js +218 -0
- package/dist/server/stdio-streams.js.map +1 -0
- package/dist/server/stdio.d.ts +59 -0
- package/dist/server/stdio.js +189 -0
- package/dist/server/stdio.js.map +1 -0
- package/dist/server/websocket.d.ts +106 -0
- package/dist/server/websocket.js +327 -0
- package/dist/server/websocket.js.map +1 -0
- package/dist/session/approvals.d.ts +81 -0
- package/dist/session/approvals.js +217 -0
- package/dist/session/approvals.js.map +1 -0
- package/dist/session/code-call-log.d.ts +42 -0
- package/dist/session/code-call-log.js +63 -0
- package/dist/session/code-call-log.js.map +1 -0
- package/dist/session/code-call-result.d.ts +19 -0
- package/dist/session/code-call-result.js +95 -0
- package/dist/session/code-call-result.js.map +1 -0
- package/dist/session/code-call.d.ts +49 -0
- package/dist/session/code-call.js +345 -0
- package/dist/session/code-call.js.map +1 -0
- package/dist/session/effect-scope.d.ts +11 -0
- package/dist/session/effect-scope.js +10 -0
- package/dist/session/effect-scope.js.map +1 -0
- package/dist/session/errors.d.ts +19 -0
- package/dist/session/errors.js +27 -0
- package/dist/session/errors.js.map +1 -0
- package/dist/session/file-index.d.ts +8 -0
- package/dist/session/file-index.js +70 -0
- package/dist/session/file-index.js.map +1 -0
- package/dist/session/file-key-store.d.ts +16 -0
- package/dist/session/file-key-store.js +169 -0
- package/dist/session/file-key-store.js.map +1 -0
- package/dist/session/file-lock.d.ts +52 -0
- package/dist/session/file-lock.js +324 -0
- package/dist/session/file-lock.js.map +1 -0
- package/dist/session/index.d.ts +22 -0
- package/dist/session/index.js +20 -0
- package/dist/session/index.js.map +1 -0
- package/dist/session/jsonl-store.d.ts +37 -0
- package/dist/session/jsonl-store.js +386 -0
- package/dist/session/jsonl-store.js.map +1 -0
- package/dist/session/jsonl.d.ts +9 -0
- package/dist/session/jsonl.js +10 -0
- package/dist/session/jsonl.js.map +1 -0
- package/dist/session/lock.d.ts +19 -0
- package/dist/session/lock.js +2 -0
- package/dist/session/lock.js.map +1 -0
- package/dist/session/memory-store.d.ts +12 -0
- package/dist/session/memory-store.js +60 -0
- package/dist/session/memory-store.js.map +1 -0
- package/dist/session/migrate.d.ts +41 -0
- package/dist/session/migrate.js +86 -0
- package/dist/session/migrate.js.map +1 -0
- package/dist/session/pointer.d.ts +15 -0
- package/dist/session/pointer.js +22 -0
- package/dist/session/pointer.js.map +1 -0
- package/dist/session/rebuild.d.ts +53 -0
- package/dist/session/rebuild.js +230 -0
- package/dist/session/rebuild.js.map +1 -0
- package/dist/session/resume.d.ts +26 -0
- package/dist/session/resume.js +128 -0
- package/dist/session/resume.js.map +1 -0
- package/dist/session/retention.d.ts +97 -0
- package/dist/session/retention.js +702 -0
- package/dist/session/retention.js.map +1 -0
- package/dist/session/runner.d.ts +156 -0
- package/dist/session/runner.js +656 -0
- package/dist/session/runner.js.map +1 -0
- package/dist/session/scheduler.d.ts +47 -0
- package/dist/session/scheduler.js +85 -0
- package/dist/session/scheduler.js.map +1 -0
- package/dist/session/secret-key-store.d.ts +47 -0
- package/dist/session/secret-key-store.js +79 -0
- package/dist/session/secret-key-store.js.map +1 -0
- package/dist/session/session.d.ts +106 -0
- package/dist/session/session.js +353 -0
- package/dist/session/session.js.map +1 -0
- package/dist/session/sticky.d.ts +48 -0
- package/dist/session/sticky.js +232 -0
- package/dist/session/sticky.js.map +1 -0
- package/dist/session/store.d.ts +108 -0
- package/dist/session/store.js +163 -0
- package/dist/session/store.js.map +1 -0
- package/dist/telemetry/index.d.ts +2 -0
- package/dist/telemetry/index.js +3 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/testing/fake-sandbox.d.ts +34 -0
- package/dist/testing/fake-sandbox.js +221 -0
- package/dist/testing/fake-sandbox.js.map +1 -0
- package/dist/testing/index.d.ts +10 -0
- package/dist/testing/index.js +11 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/key-store-conformance.d.ts +22 -0
- package/dist/testing/key-store-conformance.js +97 -0
- package/dist/testing/key-store-conformance.js.map +1 -0
- package/dist/testing/run-cases.d.ts +21 -0
- package/dist/testing/run-cases.js +20 -0
- package/dist/testing/run-cases.js.map +1 -0
- package/dist/testing/sandbox-conformance.d.ts +64 -0
- package/dist/testing/sandbox-conformance.js +361 -0
- package/dist/testing/sandbox-conformance.js.map +1 -0
- package/dist/testing/scheduler-conformance.d.ts +32 -0
- package/dist/testing/scheduler-conformance.js +72 -0
- package/dist/testing/scheduler-conformance.js.map +1 -0
- package/dist/testing/store-conformance.d.ts +21 -0
- package/dist/testing/store-conformance.js +320 -0
- package/dist/testing/store-conformance.js.map +1 -0
- package/dist/tools/errors.d.ts +13 -0
- package/dist/tools/errors.js +17 -0
- package/dist/tools/errors.js.map +1 -0
- package/dist/tools/index.d.ts +8 -0
- package/dist/tools/index.js +8 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/registry.d.ts +3 -0
- package/dist/tools/registry.js +234 -0
- package/dist/tools/registry.js.map +1 -0
- package/dist/tools/tool-search.d.ts +30 -0
- package/dist/tools/tool-search.js +118 -0
- package/dist/tools/tool-search.js.map +1 -0
- package/dist/tools/types.d.ts +106 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/llms.txt +435 -0
- package/package.json +118 -3
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
import { HarnessError } from "../errors.js";
|
|
2
|
+
import { contextOf } from "./rebuild.js";
|
|
3
|
+
// A walk up the parents that goes on this long is a cycle in a corrupt log.
|
|
4
|
+
const MAX_PATH_ENTRIES = 1_000_000;
|
|
5
|
+
/**
|
|
6
|
+
* The prefix of the name of a file that holds part of a session, such as a revert's or a migration's file. A listing
|
|
7
|
+
* leaves such files out, because a person knows a session by its key.
|
|
8
|
+
*/
|
|
9
|
+
export const DERIVED = "~";
|
|
10
|
+
/** Whether a file id names a derived file. */
|
|
11
|
+
export const isDerivedFile = (file) => file.startsWith(DERIVED);
|
|
12
|
+
/** The HEAD a log leaves: each entry moves it to itself, and a `checkout` moves it to the entry it names. */
|
|
13
|
+
function headOf(entries) {
|
|
14
|
+
let head = null;
|
|
15
|
+
for (const entry of entries)
|
|
16
|
+
head = entry.type === "checkout" ? entry.headId : entry.id;
|
|
17
|
+
return head;
|
|
18
|
+
}
|
|
19
|
+
const entriesOf = async (store, key) => {
|
|
20
|
+
const found = [];
|
|
21
|
+
for await (const entry of store.load(key))
|
|
22
|
+
found.push(entry);
|
|
23
|
+
return found;
|
|
24
|
+
};
|
|
25
|
+
/** The fields a new file copies from a session's header, so every file of a session says what ran it. */
|
|
26
|
+
function inheritedFrom(header) {
|
|
27
|
+
return {
|
|
28
|
+
type: "session_header",
|
|
29
|
+
formatVersion: header.formatVersion,
|
|
30
|
+
harnessVersion: header.harnessVersion,
|
|
31
|
+
sdkVersion: header.sdkVersion,
|
|
32
|
+
defaultsHash: header.defaultsHash,
|
|
33
|
+
capabilities: [...header.capabilities],
|
|
34
|
+
ablationHash: header.ablationHash,
|
|
35
|
+
...(header.product === undefined ? {} : { product: { ...header.product } }),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** One session. Open it with `openSession()`. */
|
|
39
|
+
export class Session {
|
|
40
|
+
key;
|
|
41
|
+
#options;
|
|
42
|
+
#handle;
|
|
43
|
+
#now;
|
|
44
|
+
#newId;
|
|
45
|
+
#prefixes = new Map();
|
|
46
|
+
#prefix;
|
|
47
|
+
#file;
|
|
48
|
+
#entries;
|
|
49
|
+
#byId;
|
|
50
|
+
#head;
|
|
51
|
+
constructor(options, file, entries, handle) {
|
|
52
|
+
this.key = options.key;
|
|
53
|
+
this.#options = options;
|
|
54
|
+
this.#file = file;
|
|
55
|
+
this.#handle = handle;
|
|
56
|
+
this.#now = options.now ?? (() => new Date());
|
|
57
|
+
this.#newId = options.newId ?? (() => globalThis.crypto.randomUUID());
|
|
58
|
+
this.#entries = entries;
|
|
59
|
+
this.#byId = new Map(entries.map((entry) => [entry.id, entry]));
|
|
60
|
+
this.#head = headOf(entries);
|
|
61
|
+
}
|
|
62
|
+
/** Reads the session's current file, and takes the writer lock when the options have a lock. */
|
|
63
|
+
static async open(options) {
|
|
64
|
+
const handle = options.lock === undefined ? undefined : await options.lock.acquire(options.key);
|
|
65
|
+
if (handle === "would_block") {
|
|
66
|
+
throw new HarnessError("session_locked", `another writer holds the session ${JSON.stringify(options.key.sessionId)}`);
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
const file = (await options.index.get(options.key)) ?? options.key.sessionId;
|
|
70
|
+
const entries = await entriesOf(options.store, { userId: options.key.userId, sessionId: file });
|
|
71
|
+
return new Session(options, file, entries, handle);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
await handle?.release();
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** The id of the entry the next append follows, or `null` for a session with no entries yet. */
|
|
79
|
+
head() {
|
|
80
|
+
return this.#head;
|
|
81
|
+
}
|
|
82
|
+
/** The id of the file the session's log is in now. A revert or a migration changes it. */
|
|
83
|
+
file() {
|
|
84
|
+
return this.#file;
|
|
85
|
+
}
|
|
86
|
+
/** Whether this session may write: it was opened with a lock, and still holds it. */
|
|
87
|
+
writable() {
|
|
88
|
+
return this.#handle?.held() === true;
|
|
89
|
+
}
|
|
90
|
+
#physical(file) {
|
|
91
|
+
return { userId: this.key.userId, sessionId: file };
|
|
92
|
+
}
|
|
93
|
+
#requireWriter() {
|
|
94
|
+
if (this.#handle === undefined)
|
|
95
|
+
throw new HarnessError("session_read_only", "this session was opened without a lock");
|
|
96
|
+
if (!this.#handle.held())
|
|
97
|
+
throw new HarnessError("session_locked", "this session lost its writer lock, so it must stop writing");
|
|
98
|
+
}
|
|
99
|
+
#remember(stored) {
|
|
100
|
+
const fresh = stored.filter((entry) => !this.#byId.has(entry.id));
|
|
101
|
+
for (const entry of fresh) {
|
|
102
|
+
this.#byId.set(entry.id, entry);
|
|
103
|
+
this.#head = entry.type === "checkout" ? entry.headId : entry.id;
|
|
104
|
+
}
|
|
105
|
+
this.#entries = [...this.#entries, ...fresh];
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Appends entries to the session's current file and moves HEAD. The caller sets each entry's `parentId`, normally
|
|
109
|
+
* `head()` for the first and the entry before it for the rest. The append is guarded by the end of the log this session
|
|
110
|
+
* has seen, so a writer that lost the lock can't extend it.
|
|
111
|
+
*/
|
|
112
|
+
async append(entries) {
|
|
113
|
+
this.#requireWriter();
|
|
114
|
+
const expectedLastId = this.#entries.at(-1)?.id ?? null;
|
|
115
|
+
const stored = await this.#options.store.append(this.#physical(this.#file), entries, { expectedLastId });
|
|
116
|
+
this.#remember(stored);
|
|
117
|
+
return stored;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* The entries a file's session was made from: the path to the entry its header names in its parent file, and so on up
|
|
121
|
+
* through that file's own parent. An entry the parent wrote after the fork point is not in it. The path to a fork point
|
|
122
|
+
* never changes, because a log is append-only, so the result is kept.
|
|
123
|
+
*/
|
|
124
|
+
async #ancestry(file, entryId) {
|
|
125
|
+
const cacheKey = JSON.stringify([file, entryId]);
|
|
126
|
+
const cached = this.#prefixes.get(cacheKey);
|
|
127
|
+
if (cached !== undefined)
|
|
128
|
+
return cached;
|
|
129
|
+
const entries = await entriesOf(this.#options.store, this.#physical(file));
|
|
130
|
+
const byId = new Map(entries.map((entry) => [entry.id, entry]));
|
|
131
|
+
const header = entries[0];
|
|
132
|
+
const above = header?.type === "session_header" && header.spawn === undefined ? header.parent : undefined;
|
|
133
|
+
const path = [];
|
|
134
|
+
const seen = new Set();
|
|
135
|
+
let at = entryId;
|
|
136
|
+
while (at !== null) {
|
|
137
|
+
if (seen.has(at))
|
|
138
|
+
throw new HarnessError("session_corrupt", `the entries of the file ${file} have a cycle at ${at}`);
|
|
139
|
+
seen.add(at);
|
|
140
|
+
const entry = byId.get(at);
|
|
141
|
+
if (entry === undefined) {
|
|
142
|
+
if (above === undefined)
|
|
143
|
+
throw new HarnessError("entry_not_found", `no entry ${at} in the file ${file}`);
|
|
144
|
+
// A loop and not a spread, because a long prefix would be too many arguments for a call.
|
|
145
|
+
// An entry missing from this file is in an ancestor file. The walk continues there from `at`, which is the entry this
|
|
146
|
+
// file's header names when the missing entry is the fork point.
|
|
147
|
+
const prefix = await this.#ancestry(above.session, at);
|
|
148
|
+
for (let i = prefix.length - 1; i >= 0; i -= 1)
|
|
149
|
+
path.push(prefix[i]);
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
path.push(entry);
|
|
153
|
+
at = entry.parentId;
|
|
154
|
+
}
|
|
155
|
+
const result = path.reverse();
|
|
156
|
+
this.#prefixes.set(cacheKey, result);
|
|
157
|
+
return result;
|
|
158
|
+
}
|
|
159
|
+
/** The entries of the parent files that this session's current file continues, by id. Empty for a first file. */
|
|
160
|
+
async #inherited() {
|
|
161
|
+
if (this.#prefix !== undefined)
|
|
162
|
+
return this.#prefix;
|
|
163
|
+
const header = this.#entries[0];
|
|
164
|
+
const above = header?.type === "session_header" && header.spawn === undefined ? header.parent : undefined;
|
|
165
|
+
const prefix = new Map();
|
|
166
|
+
if (above !== undefined) {
|
|
167
|
+
for (const entry of await this.#ancestry(above.session, above.entryId))
|
|
168
|
+
prefix.set(entry.id, entry);
|
|
169
|
+
}
|
|
170
|
+
this.#prefix = prefix;
|
|
171
|
+
return prefix;
|
|
172
|
+
}
|
|
173
|
+
/** An entry of this session: one in its current file, or one in the prefix the file continues. */
|
|
174
|
+
async #find(id) {
|
|
175
|
+
return this.#byId.get(id) ?? (await this.#inherited()).get(id);
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* The entries from the root to `headId` (default HEAD), following `parentId` and crossing into a parent file when a
|
|
179
|
+
* fork's entry follows one in it. A fork's own header is left out, and so are the `checkout` entries, which move HEAD
|
|
180
|
+
* and are not part of the conversation.
|
|
181
|
+
*/
|
|
182
|
+
async path(headId = this.#head) {
|
|
183
|
+
const path = [];
|
|
184
|
+
const seen = new Set();
|
|
185
|
+
let at = headId;
|
|
186
|
+
while (at !== null) {
|
|
187
|
+
if (seen.has(at) || path.length > MAX_PATH_ENTRIES) {
|
|
188
|
+
throw new HarnessError("session_corrupt", `the entries of ${this.key.sessionId} have a cycle at ${at}`);
|
|
189
|
+
}
|
|
190
|
+
seen.add(at);
|
|
191
|
+
const entry = await this.#find(at);
|
|
192
|
+
if (entry === undefined)
|
|
193
|
+
throw new HarnessError("entry_not_found", `no entry ${at} in the session ${this.key.sessionId}`);
|
|
194
|
+
path.push(entry);
|
|
195
|
+
at = entry.parentId;
|
|
196
|
+
}
|
|
197
|
+
return path.reverse();
|
|
198
|
+
}
|
|
199
|
+
/** Whether the log's last entry is a `checkout`, so HEAD was moved and the path's end is not where the log ends. */
|
|
200
|
+
headMoved() {
|
|
201
|
+
return this.#entries.at(-1)?.type === "checkout";
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* The name of the branch HEAD is on: the file the log is in, and, after a checkout, that checkout's id, so a re-run
|
|
205
|
+
* that replays a call id gets a branch of its own.
|
|
206
|
+
*/
|
|
207
|
+
branch() {
|
|
208
|
+
const moved = this.#entries.findLast((entry) => entry.type === "checkout");
|
|
209
|
+
return moved === undefined ? this.#file : `${this.#file}@${moved.id}`;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* The SDK context the entries from the root to `headId` (default HEAD) stand for: the messages in order, and the
|
|
213
|
+
* system prompt of the latest turn, which is the one the model saw. Pass it to `continueRun()`, in any process,
|
|
214
|
+
* after a JSON round trip. A call the log shows without a result is left open, so `runTurn()` settles it first.
|
|
215
|
+
*/
|
|
216
|
+
async toContext(headId = this.#head) {
|
|
217
|
+
return contextOf(await this.path(headId));
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* The entries from the root to `headId` (default HEAD), in order, as a stored session shows them. It reads the log
|
|
221
|
+
* and nothing else: no model, tool or hook runs, so a playback is the same on every machine.
|
|
222
|
+
*/
|
|
223
|
+
async *playback(headId = this.#head) {
|
|
224
|
+
for (const entry of await this.path(headId))
|
|
225
|
+
yield entry;
|
|
226
|
+
}
|
|
227
|
+
#base() {
|
|
228
|
+
return { id: this.#newId(), timestamp: this.#now().toISOString(), origin: "harness" };
|
|
229
|
+
}
|
|
230
|
+
async #mustHave(entryId) {
|
|
231
|
+
if ((await this.#find(entryId)) === undefined) {
|
|
232
|
+
throw new HarnessError("entry_not_found", `no entry ${entryId} in the session ${this.key.sessionId}`);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
/** A fork or a revert needs a header to copy and an entry of this session to start from. */
|
|
236
|
+
async #canBranchFrom(entryId) {
|
|
237
|
+
this.#header();
|
|
238
|
+
await this.#mustHave(entryId);
|
|
239
|
+
}
|
|
240
|
+
/** Moves HEAD to `entryId` by appending a `checkout` entry, so a reload finds HEAD where it was left. */
|
|
241
|
+
async checkout(entryId) {
|
|
242
|
+
this.#requireWriter();
|
|
243
|
+
await this.#mustHave(entryId);
|
|
244
|
+
await this.append([{ ...this.#base(), parentId: this.#head, type: "checkout", headId: entryId }]);
|
|
245
|
+
}
|
|
246
|
+
#header() {
|
|
247
|
+
const header = this.#entries[0];
|
|
248
|
+
if (header?.type !== "session_header") {
|
|
249
|
+
throw new HarnessError("entry_not_found", `the session ${this.key.sessionId} has no entries to branch from yet`);
|
|
250
|
+
}
|
|
251
|
+
return header;
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Writes a new file that holds a header and, for a branch, a `checkout` of the entry it starts from. A child's header
|
|
255
|
+
* names the session and link entry that started it, and `spawn`, and has no `checkout`, because a child is its own
|
|
256
|
+
* log and not a continuation.
|
|
257
|
+
*/
|
|
258
|
+
async #writeFile(file, parent, spawn) {
|
|
259
|
+
const header = this.#header();
|
|
260
|
+
const headerId = this.#newId();
|
|
261
|
+
const entries = [
|
|
262
|
+
{
|
|
263
|
+
...this.#base(),
|
|
264
|
+
id: headerId,
|
|
265
|
+
parentId: null,
|
|
266
|
+
...inheritedFrom(header),
|
|
267
|
+
...(parent === undefined ? {} : { parent }),
|
|
268
|
+
...(spawn === undefined ? {} : { spawn }),
|
|
269
|
+
},
|
|
270
|
+
];
|
|
271
|
+
if (parent !== undefined && spawn === undefined) {
|
|
272
|
+
entries.push({ ...this.#base(), parentId: headerId, type: "checkout", headId: parent.entryId });
|
|
273
|
+
}
|
|
274
|
+
await this.#options.store.append(this.#physical(file), entries, { expectedLastId: null });
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Starts a new session from `entryId`: a new file whose header names this session's file and that entry as its parent,
|
|
278
|
+
* so the fork's `path()` includes everything up to the entry without copying it. This session is unchanged. The
|
|
279
|
+
* returned session is opened with the same options under a new id.
|
|
280
|
+
*/
|
|
281
|
+
async fork(entryId) {
|
|
282
|
+
this.#requireWriter();
|
|
283
|
+
await this.#canBranchFrom(entryId);
|
|
284
|
+
const sessionId = this.#newId();
|
|
285
|
+
await this.#writeFile(sessionId, { session: this.#file, entryId });
|
|
286
|
+
return Session.open({ ...this.#options, key: { userId: this.key.userId, sessionId } });
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Goes back to `entryId` in a new file and points the session at it. The new file's header names the old file as its
|
|
290
|
+
* parent, so nothing before the entry is lost, and the old file is not touched. A crash before the pointer moves
|
|
291
|
+
* leaves the old file in use. Returns this session, now on the new file.
|
|
292
|
+
*/
|
|
293
|
+
async revert(entryId) {
|
|
294
|
+
this.#requireWriter();
|
|
295
|
+
await this.#canBranchFrom(entryId);
|
|
296
|
+
const file = `${DERIVED}r${this.#newId()}`;
|
|
297
|
+
await this.#writeFile(file, { session: this.#file, entryId });
|
|
298
|
+
// The new file is read before anything changes, so a failure here leaves the session on the file it was on.
|
|
299
|
+
const entries = await entriesOf(this.#options.store, this.#physical(file));
|
|
300
|
+
await this.#options.index.set(this.key, file);
|
|
301
|
+
this.#file = file;
|
|
302
|
+
this.#entries = entries;
|
|
303
|
+
this.#byId = new Map(entries.map((entry) => [entry.id, entry]));
|
|
304
|
+
this.#head = headOf(entries);
|
|
305
|
+
this.#prefix = undefined;
|
|
306
|
+
return this;
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Starts the log of a subagent or a workflow step, and records the link in this session with a `subagent_link` entry
|
|
310
|
+
* that carries `spawningCallId` or `stepId`, whichever was given, and never both. If the link can't be written, for
|
|
311
|
+
* example because the lock was lost, the child's file stays in the store as a session no one links to, which retention
|
|
312
|
+
* removes; the same holds for a fork that can't be opened.
|
|
313
|
+
*/
|
|
314
|
+
async child(link) {
|
|
315
|
+
this.#requireWriter();
|
|
316
|
+
const { spawningCallId, stepId } = link;
|
|
317
|
+
if ((spawningCallId === undefined) === (stepId === undefined)) {
|
|
318
|
+
throw new HarnessError("invalid_session_entry", "a child link needs exactly one of spawningCallId and stepId");
|
|
319
|
+
}
|
|
320
|
+
const sessionId = this.#newId();
|
|
321
|
+
const linkId = this.#newId();
|
|
322
|
+
const spawn = spawningCallId === undefined ? { stepId: stepId } : { spawningCallId };
|
|
323
|
+
await this.#writeFile(sessionId, { session: this.#file, entryId: linkId }, spawn);
|
|
324
|
+
await this.append([
|
|
325
|
+
{
|
|
326
|
+
...this.#base(),
|
|
327
|
+
id: linkId,
|
|
328
|
+
parentId: this.#head,
|
|
329
|
+
type: "subagent_link",
|
|
330
|
+
childSession: sessionId,
|
|
331
|
+
...(spawningCallId === undefined ? {} : { spawningCallId }),
|
|
332
|
+
...(stepId === undefined ? {} : { stepId }),
|
|
333
|
+
},
|
|
334
|
+
]);
|
|
335
|
+
return Session.open({ ...this.#options, key: { userId: this.key.userId, sessionId } });
|
|
336
|
+
}
|
|
337
|
+
/** Gives up the writer lock, if the session holds one. */
|
|
338
|
+
async close() {
|
|
339
|
+
await this.#handle?.release();
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
/** Opens a session. With a `lock` it is the session's one writer, and without one it can only read. */
|
|
343
|
+
export function openSession(options) {
|
|
344
|
+
return Session.open(options);
|
|
345
|
+
}
|
|
346
|
+
/** The user's sessions, oldest first, without the files that only hold part of a session (a revert's or a migration's). */
|
|
347
|
+
export async function* listSessions(store, userId) {
|
|
348
|
+
for await (const summary of store.list(userId)) {
|
|
349
|
+
if (!isDerivedFile(summary.sessionId))
|
|
350
|
+
yield summary;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
//# sourceMappingURL=session.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session.js","sourceRoot":"","sources":["../../src/session/session.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAG5C,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAmBzC,4EAA4E;AAC5E,MAAM,gBAAgB,GAAG,SAAS,CAAC;AAEnC;;;GAGG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,GAAG,CAAC;AAE3B,8CAA8C;AAC9C,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,IAAY,EAAW,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;AAEjF,6GAA6G;AAC7G,SAAS,MAAM,CAAC,OAAgC;IAC9C,IAAI,IAAI,GAAkB,IAAI,CAAC;IAC/B,KAAK,MAAM,KAAK,IAAI,OAAO;QAAE,IAAI,GAAG,KAAK,CAAC,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC;IACxF,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,SAAS,GAAG,KAAK,EAAE,KAAmB,EAAE,GAAe,EAA2B,EAAE;IACxF,MAAM,KAAK,GAAmB,EAAE,CAAC;IACjC,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC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E,MAAM,EAAE,CAAC;aAC5C;SACF,CAAC,CAAC;QACH,OAAO,OAAO,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC;IACzF,CAAC;IAED,0DAA0D;IAC1D,KAAK,CAAC,KAAK;QACT,MAAM,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,CAAC;IAChC,CAAC;CACF;AAED,uGAAuG;AACvG,MAAM,UAAU,WAAW,CAAC,OAA2B;IACrD,OAAO,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAC/B,CAAC;AAED,2HAA2H;AAC3H,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,YAAY,CAAC,KAAmB,EAAE,MAAc;IACrE,IAAI,KAAK,EAAE,MAAM,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QAC/C,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,SAAS,CAAC;YAAE,MAAM,OAAO,CAAC;IACvD,CAAC;AACH,CAAC","sourcesContent":["/**\n * `Session`: one session's log with its HEAD, and the operations that branch it. The log is an append-only tree of\n * entries. HEAD is the entry the next append follows. A checkout, a fork and a revert write new entries or new files and\n * never rewrite one, so the only mutable state is the pointer to the session's current file (`SessionIndex`).\n */\nimport type { SessionEntry, SessionHeaderEntry } from \"@buildanagent/protocol\";\nimport type { Context } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport type { LockHandle, SessionLock } from \"./lock.js\";\nimport type { SessionIndex } from \"./pointer.js\";\nimport { contextOf } from \"./rebuild.js\";\nimport type { EntryInput, SessionKey, SessionStore, SessionSummary } from \"./store.js\";\n\n/** The options of `openSession()`. */\nexport interface OpenSessionOptions {\n readonly store: SessionStore;\n readonly index: SessionIndex;\n readonly key: SessionKey;\n /** With a lock, the session takes it and may write. Without one, the session is read-only: readers never lock. */\n readonly lock?: SessionLock;\n /** The clock for the entries a session writes itself. Default `new Date()`. */\n readonly now?: () => Date;\n /** Makes the ids of the entries and files a session writes itself. Default `crypto.randomUUID()`. */\n readonly newId?: () => string;\n}\n\n/** What links a child session to the session that started it: a tool call, or a workflow step. Give exactly one. */\nexport type ChildLink = { readonly spawningCallId: string } | { readonly stepId: string };\n\n// A walk up the parents that goes on this long is a cycle in a corrupt log.\nconst MAX_PATH_ENTRIES = 1_000_000;\n\n/**\n * The prefix of the name of a file that holds part of a session, such as a revert's or a migration's file. A listing\n * leaves such files out, because a person knows a session by its key.\n */\nexport const DERIVED = \"~\";\n\n/** Whether a file id names a derived file. */\nexport const isDerivedFile = (file: string): boolean => file.startsWith(DERIVED);\n\n/** The HEAD a log leaves: each entry moves it to itself, and a `checkout` moves it to the entry it names. */\nfunction headOf(entries: readonly SessionEntry[]): string | null {\n let head: string | null = null;\n for (const entry of entries) head = entry.type === \"checkout\" ? entry.headId : entry.id;\n return head;\n}\n\nconst entriesOf = async (store: SessionStore, key: SessionKey): Promise<SessionEntry[]> => {\n const found: SessionEntry[] = [];\n for await (const entry of store.load(key)) found.push(entry);\n return found;\n};\n\n/** The fields a new file copies from a session's header, so every file of a session says what ran it. */\nfunction inheritedFrom(\n header: SessionHeaderEntry,\n): Omit<SessionHeaderEntry, \"type\" | \"parent\"> & { type: \"session_header\" } {\n return {\n type: \"session_header\",\n formatVersion: header.formatVersion,\n harnessVersion: header.harnessVersion,\n sdkVersion: header.sdkVersion,\n defaultsHash: header.defaultsHash,\n capabilities: [...header.capabilities],\n ablationHash: header.ablationHash,\n ...(header.product === undefined ? {} : { product: { ...header.product } }),\n };\n}\n\n/** One session. Open it with `openSession()`. */\nexport class Session {\n readonly key: SessionKey;\n readonly #options: OpenSessionOptions;\n readonly #handle: LockHandle | undefined;\n readonly #now: () => Date;\n readonly #newId: () => string;\n readonly #prefixes = new Map<string, readonly SessionEntry[]>();\n #prefix: Map<string, SessionEntry> | undefined;\n #file: string;\n #entries: SessionEntry[];\n #byId: Map<string, SessionEntry>;\n #head: string | null;\n\n private constructor(\n options: OpenSessionOptions,\n file: string,\n entries: SessionEntry[],\n handle: LockHandle | undefined,\n ) {\n this.key = options.key;\n this.#options = options;\n this.#file = file;\n this.#handle = handle;\n this.#now = options.now ?? (() => new Date());\n this.#newId = options.newId ?? (() => globalThis.crypto.randomUUID());\n this.#entries = entries;\n this.#byId = new Map(entries.map((entry) => [entry.id, entry]));\n this.#head = headOf(entries);\n }\n\n /** Reads the session's current file, and takes the writer lock when the options have a lock. */\n static async open(options: OpenSessionOptions): Promise<Session> {\n const handle = options.lock === undefined ? undefined : await options.lock.acquire(options.key);\n if (handle === \"would_block\") {\n throw new HarnessError(\n \"session_locked\",\n `another writer holds the session ${JSON.stringify(options.key.sessionId)}`,\n );\n }\n try {\n const file = (await options.index.get(options.key)) ?? options.key.sessionId;\n const entries = await entriesOf(options.store, { userId: options.key.userId, sessionId: file });\n return new Session(options, file, entries, handle);\n } catch (error) {\n await handle?.release();\n throw error;\n }\n }\n\n /** The id of the entry the next append follows, or `null` for a session with no entries yet. */\n head(): string | null {\n return this.#head;\n }\n\n /** The id of the file the session's log is in now. A revert or a migration changes it. */\n file(): string {\n return this.#file;\n }\n\n /** Whether this session may write: it was opened with a lock, and still holds it. */\n writable(): boolean {\n return this.#handle?.held() === true;\n }\n\n #physical(file: string): SessionKey {\n return { userId: this.key.userId, sessionId: file };\n }\n\n #requireWriter(): void {\n if (this.#handle === undefined)\n throw new HarnessError(\"session_read_only\", \"this session was opened without a lock\");\n if (!this.#handle.held())\n throw new HarnessError(\"session_locked\", \"this session lost its writer lock, so it must stop writing\");\n }\n\n #remember(stored: readonly SessionEntry[]): void {\n const fresh = stored.filter((entry) => !this.#byId.has(entry.id));\n for (const entry of fresh) {\n this.#byId.set(entry.id, entry);\n this.#head = entry.type === \"checkout\" ? entry.headId : entry.id;\n }\n this.#entries = [...this.#entries, ...fresh];\n }\n\n /**\n * Appends entries to the session's current file and moves HEAD. The caller sets each entry's `parentId`, normally\n * `head()` for the first and the entry before it for the rest. The append is guarded by the end of the log this session\n * has seen, so a writer that lost the lock can't extend it.\n */\n async append(entries: readonly EntryInput[]): Promise<SessionEntry[]> {\n this.#requireWriter();\n const expectedLastId = this.#entries.at(-1)?.id ?? null;\n const stored = await this.#options.store.append(this.#physical(this.#file), entries, { expectedLastId });\n this.#remember(stored);\n return stored;\n }\n\n /**\n * The entries a file's session was made from: the path to the entry its header names in its parent file, and so on up\n * through that file's own parent. An entry the parent wrote after the fork point is not in it. The path to a fork point\n * never changes, because a log is append-only, so the result is kept.\n */\n async #ancestry(file: string, entryId: string): Promise<readonly SessionEntry[]> {\n const cacheKey = JSON.stringify([file, entryId]);\n const cached = this.#prefixes.get(cacheKey);\n if (cached !== undefined) return cached;\n const entries = await entriesOf(this.#options.store, this.#physical(file));\n const byId = new Map(entries.map((entry) => [entry.id, entry]));\n const header = entries[0];\n const above = header?.type === \"session_header\" && header.spawn === undefined ? header.parent : undefined;\n const path: SessionEntry[] = [];\n const seen = new Set<string>();\n let at: string | null = entryId;\n while (at !== null) {\n if (seen.has(at))\n throw new HarnessError(\"session_corrupt\", `the entries of the file ${file} have a cycle at ${at}`);\n seen.add(at);\n const entry = byId.get(at);\n if (entry === undefined) {\n if (above === undefined) throw new HarnessError(\"entry_not_found\", `no entry ${at} in the file ${file}`);\n // A loop and not a spread, because a long prefix would be too many arguments for a call.\n // An entry missing from this file is in an ancestor file. The walk continues there from `at`, which is the entry this\n // file's header names when the missing entry is the fork point.\n const prefix = await this.#ancestry(above.session, at);\n for (let i = prefix.length - 1; i >= 0; i -= 1) path.push(prefix[i] as SessionEntry);\n break;\n }\n path.push(entry);\n at = entry.parentId;\n }\n const result = path.reverse();\n this.#prefixes.set(cacheKey, result);\n return result;\n }\n\n /** The entries of the parent files that this session's current file continues, by id. Empty for a first file. */\n async #inherited(): Promise<Map<string, SessionEntry>> {\n if (this.#prefix !== undefined) return this.#prefix;\n const header = this.#entries[0];\n const above = header?.type === \"session_header\" && header.spawn === undefined ? header.parent : undefined;\n const prefix = new Map<string, SessionEntry>();\n if (above !== undefined) {\n for (const entry of await this.#ancestry(above.session, above.entryId)) prefix.set(entry.id, entry);\n }\n this.#prefix = prefix;\n return prefix;\n }\n\n /** An entry of this session: one in its current file, or one in the prefix the file continues. */\n async #find(id: string): Promise<SessionEntry | undefined> {\n return this.#byId.get(id) ?? (await this.#inherited()).get(id);\n }\n\n /**\n * The entries from the root to `headId` (default HEAD), following `parentId` and crossing into a parent file when a\n * fork's entry follows one in it. A fork's own header is left out, and so are the `checkout` entries, which move HEAD\n * and are not part of the conversation.\n */\n async path(headId: string | null = this.#head): Promise<SessionEntry[]> {\n const path: SessionEntry[] = [];\n const seen = new Set<string>();\n let at = headId;\n while (at !== null) {\n if (seen.has(at) || path.length > MAX_PATH_ENTRIES) {\n throw new HarnessError(\"session_corrupt\", `the entries of ${this.key.sessionId} have a cycle at ${at}`);\n }\n seen.add(at);\n const entry = await this.#find(at);\n if (entry === undefined)\n throw new HarnessError(\"entry_not_found\", `no entry ${at} in the session ${this.key.sessionId}`);\n path.push(entry);\n at = entry.parentId;\n }\n return path.reverse();\n }\n\n /** Whether the log's last entry is a `checkout`, so HEAD was moved and the path's end is not where the log ends. */\n headMoved(): boolean {\n return this.#entries.at(-1)?.type === \"checkout\";\n }\n\n /**\n * The name of the branch HEAD is on: the file the log is in, and, after a checkout, that checkout's id, so a re-run\n * that replays a call id gets a branch of its own.\n */\n branch(): string {\n const moved = this.#entries.findLast((entry) => entry.type === \"checkout\");\n return moved === undefined ? this.#file : `${this.#file}@${moved.id}`;\n }\n\n /**\n * The SDK context the entries from the root to `headId` (default HEAD) stand for: the messages in order, and the\n * system prompt of the latest turn, which is the one the model saw. Pass it to `continueRun()`, in any process,\n * after a JSON round trip. A call the log shows without a result is left open, so `runTurn()` settles it first.\n */\n async toContext(headId: string | null = this.#head): Promise<Context> {\n return contextOf(await this.path(headId));\n }\n\n /**\n * The entries from the root to `headId` (default HEAD), in order, as a stored session shows them. It reads the log\n * and nothing else: no model, tool or hook runs, so a playback is the same on every machine.\n */\n async *playback(headId: string | null = this.#head): AsyncGenerator<SessionEntry> {\n for (const entry of await this.path(headId)) yield entry;\n }\n\n #base(): { id: string; timestamp: string; origin: \"harness\" } {\n return { id: this.#newId(), timestamp: this.#now().toISOString(), origin: \"harness\" };\n }\n\n async #mustHave(entryId: string): Promise<void> {\n if ((await this.#find(entryId)) === undefined) {\n throw new HarnessError(\"entry_not_found\", `no entry ${entryId} in the session ${this.key.sessionId}`);\n }\n }\n\n /** A fork or a revert needs a header to copy and an entry of this session to start from. */\n async #canBranchFrom(entryId: string): Promise<void> {\n this.#header();\n await this.#mustHave(entryId);\n }\n\n /** Moves HEAD to `entryId` by appending a `checkout` entry, so a reload finds HEAD where it was left. */\n async checkout(entryId: string): Promise<void> {\n this.#requireWriter();\n await this.#mustHave(entryId);\n await this.append([{ ...this.#base(), parentId: this.#head, type: \"checkout\", headId: entryId }]);\n }\n\n #header(): SessionHeaderEntry {\n const header = this.#entries[0];\n if (header?.type !== \"session_header\") {\n throw new HarnessError(\"entry_not_found\", `the session ${this.key.sessionId} has no entries to branch from yet`);\n }\n return header;\n }\n\n /**\n * Writes a new file that holds a header and, for a branch, a `checkout` of the entry it starts from. A child's header\n * names the session and link entry that started it, and `spawn`, and has no `checkout`, because a child is its own\n * log and not a continuation.\n */\n async #writeFile(\n file: string,\n parent: { session: string; entryId: string } | undefined,\n spawn?: SessionHeaderEntry[\"spawn\"],\n ): Promise<void> {\n const header = this.#header();\n const headerId = this.#newId();\n const entries: EntryInput[] = [\n {\n ...this.#base(),\n id: headerId,\n parentId: null,\n ...inheritedFrom(header),\n ...(parent === undefined ? {} : { parent }),\n ...(spawn === undefined ? {} : { spawn }),\n },\n ];\n if (parent !== undefined && spawn === undefined) {\n entries.push({ ...this.#base(), parentId: headerId, type: \"checkout\", headId: parent.entryId });\n }\n await this.#options.store.append(this.#physical(file), entries, { expectedLastId: null });\n }\n\n /**\n * Starts a new session from `entryId`: a new file whose header names this session's file and that entry as its parent,\n * so the fork's `path()` includes everything up to the entry without copying it. This session is unchanged. The\n * returned session is opened with the same options under a new id.\n */\n async fork(entryId: string): Promise<Session> {\n this.#requireWriter();\n await this.#canBranchFrom(entryId);\n const sessionId = this.#newId();\n await this.#writeFile(sessionId, { session: this.#file, entryId });\n return Session.open({ ...this.#options, key: { userId: this.key.userId, sessionId } });\n }\n\n /**\n * Goes back to `entryId` in a new file and points the session at it. The new file's header names the old file as its\n * parent, so nothing before the entry is lost, and the old file is not touched. A crash before the pointer moves\n * leaves the old file in use. Returns this session, now on the new file.\n */\n async revert(entryId: string): Promise<Session> {\n this.#requireWriter();\n await this.#canBranchFrom(entryId);\n const file = `${DERIVED}r${this.#newId()}`;\n await this.#writeFile(file, { session: this.#file, entryId });\n // The new file is read before anything changes, so a failure here leaves the session on the file it was on.\n const entries = await entriesOf(this.#options.store, this.#physical(file));\n await this.#options.index.set(this.key, file);\n this.#file = file;\n this.#entries = entries;\n this.#byId = new Map(entries.map((entry) => [entry.id, entry]));\n this.#head = headOf(entries);\n this.#prefix = undefined;\n return this;\n }\n\n /**\n * Starts the log of a subagent or a workflow step, and records the link in this session with a `subagent_link` entry\n * that carries `spawningCallId` or `stepId`, whichever was given, and never both. If the link can't be written, for\n * example because the lock was lost, the child's file stays in the store as a session no one links to, which retention\n * removes; the same holds for a fork that can't be opened.\n */\n async child(link: ChildLink): Promise<Session> {\n this.#requireWriter();\n const { spawningCallId, stepId } = link as { spawningCallId?: string; stepId?: string };\n if ((spawningCallId === undefined) === (stepId === undefined)) {\n throw new HarnessError(\"invalid_session_entry\", \"a child link needs exactly one of spawningCallId and stepId\");\n }\n const sessionId = this.#newId();\n const linkId = this.#newId();\n const spawn = spawningCallId === undefined ? { stepId: stepId as string } : { spawningCallId };\n await this.#writeFile(sessionId, { session: this.#file, entryId: linkId }, spawn);\n await this.append([\n {\n ...this.#base(),\n id: linkId,\n parentId: this.#head,\n type: \"subagent_link\",\n childSession: sessionId,\n ...(spawningCallId === undefined ? {} : { spawningCallId }),\n ...(stepId === undefined ? {} : { stepId }),\n },\n ]);\n return Session.open({ ...this.#options, key: { userId: this.key.userId, sessionId } });\n }\n\n /** Gives up the writer lock, if the session holds one. */\n async close(): Promise<void> {\n await this.#handle?.release();\n }\n}\n\n/** Opens a session. With a `lock` it is the session's one writer, and without one it can only read. */\nexport function openSession(options: OpenSessionOptions): Promise<Session> {\n return Session.open(options);\n}\n\n/** The user's sessions, oldest first, without the files that only hold part of a session (a revert's or a migration's). */\nexport async function* listSessions(store: SessionStore, userId: string): AsyncGenerator<SessionSummary> {\n for await (const summary of store.list(userId)) {\n if (!isDerivedFile(summary.sessionId)) yield summary;\n }\n}\n"]}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sticky allowances and grouped approvals: what a person's `allow` may cover beyond the one call. A sticky allowance
|
|
3
|
+
* covers the same call again for a run or a session, matched by the tool and the call's input hash or, for a shell tool,
|
|
4
|
+
* by a command prefix. It never covers a command run through a shell, an interpreter or a wrapper, which would let any
|
|
5
|
+
* script through. It never covers anything that holds a secret, or a tool whose `approvalReuse` says each call needs a
|
|
6
|
+
* person. A prefix covers only a simple command, with no operator that starts a second one. A group is the requests of
|
|
7
|
+
* one step that share a tool and an input, answered once.
|
|
8
|
+
*/
|
|
9
|
+
import type { PermissionDecisionEntry, SessionEntry } from "@buildanagent/protocol";
|
|
10
|
+
import type { ApprovalReuse, ToolRegistry } from "../tools/types.js";
|
|
11
|
+
/** The command prefixes no sticky allowance may cover: each runs whatever text follows it. */
|
|
12
|
+
export declare const INTERPRETER_PREFIXES: readonly (readonly string[])[];
|
|
13
|
+
/** Whether the command is a single simple command, so a prefix says what it runs. */
|
|
14
|
+
export declare const isSimpleCommand: (command: string) => boolean;
|
|
15
|
+
/** A shell command with its spaces normalised outside quotes, so two spellings of one command hash alike. */
|
|
16
|
+
export declare const normalisedCommand: (command: string) => string;
|
|
17
|
+
/** Throws `approval_reuse_refused` unless the tool's `approvalReuse` lets one answer cover more than one call. */
|
|
18
|
+
export declare function checkReuse(tool: string, reuse: ApprovalReuse, kind: "sticky" | "group"): void;
|
|
19
|
+
/**
|
|
20
|
+
* Throws `sticky_refused` when an allowance on this call would cover code run through a shell, an interpreter or a
|
|
21
|
+
* wrapper, a prefix that is empty or that doesn't start the approved command, a command prefix on a call with no
|
|
22
|
+
* simple command, or a secret. `secrets` are the values the host's credential store knows.
|
|
23
|
+
*/
|
|
24
|
+
export declare function checkSticky(input: unknown, commandPrefix: readonly string[] | undefined, secrets: readonly string[]): void;
|
|
25
|
+
/** The id a request's group shares: the tool and the whole input, with a shell command's spaces normalised. */
|
|
26
|
+
export declare function groupIdOf(tool: string, input: unknown, inputHash: string): Promise<string>;
|
|
27
|
+
/** What `findSticky()` needs to know about the call: its tool, input and the policy version that asks about it. */
|
|
28
|
+
export interface StickyCall {
|
|
29
|
+
readonly tool: string;
|
|
30
|
+
readonly input: unknown;
|
|
31
|
+
readonly policyVersion?: string | undefined;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The id of the sticky `approval_resolved` entry that covers this call, if one does. A `run` allowance counts from the
|
|
35
|
+
* latest turn that started a run, so its resumes share it; a `session` allowance counts from the start of this
|
|
36
|
+
* session's own file, so a fork never inherits its parent's. An allowance given under another policy version is
|
|
37
|
+
* ignored, because the policy that asked is no longer the one a person approved under.
|
|
38
|
+
*/
|
|
39
|
+
export declare function findSticky(path: readonly SessionEntry[], call: StickyCall, registry: ToolRegistry): Promise<string | undefined>;
|
|
40
|
+
/**
|
|
41
|
+
* The `permission_decision` entry that records a sticky allowance letting a call run: an allow by `sticky`, naming the
|
|
42
|
+
* `approval_resolved` entry that covers the call. The pipeline's own entry for the ask stays in the log beside it.
|
|
43
|
+
*/
|
|
44
|
+
export declare function stickyDecision(call: {
|
|
45
|
+
readonly callId: string;
|
|
46
|
+
readonly tool: string;
|
|
47
|
+
readonly input: unknown;
|
|
48
|
+
}, coveredBy: string, policyVersion: string | undefined): Promise<PermissionDecisionEntry>;
|