@buildanagent/harness 0.1.0-alpha.29 → 0.1.0-alpha.31

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.
Files changed (84) hide show
  1. package/README.md +110 -3
  2. package/dist/credentials/addresses.d.ts +20 -0
  3. package/dist/credentials/addresses.js +93 -2
  4. package/dist/credentials/addresses.js.map +1 -1
  5. package/dist/credentials/egress-proxy.js +34 -4
  6. package/dist/credentials/egress-proxy.js.map +1 -1
  7. package/dist/errors.d.ts +6 -3
  8. package/dist/errors.js +5 -2
  9. package/dist/errors.js.map +1 -1
  10. package/dist/extensions/load.js +5 -2
  11. package/dist/extensions/load.js.map +1 -1
  12. package/dist/extensions/lock.d.ts +16 -2
  13. package/dist/extensions/lock.js +155 -21
  14. package/dist/extensions/lock.js.map +1 -1
  15. package/dist/extensions/mcp-pins-node.d.ts +16 -0
  16. package/dist/extensions/mcp-pins-node.js +18 -0
  17. package/dist/extensions/mcp-pins-node.js.map +1 -0
  18. package/dist/extensions/node.d.ts +4 -2
  19. package/dist/extensions/node.js +4 -2
  20. package/dist/extensions/node.js.map +1 -1
  21. package/dist/harness.d.ts +7 -1
  22. package/dist/harness.js.map +1 -1
  23. package/dist/mcp/connection.d.ts +9 -3
  24. package/dist/mcp/connection.js +192 -25
  25. package/dist/mcp/connection.js.map +1 -1
  26. package/dist/mcp/errors.d.ts +5 -2
  27. package/dist/mcp/errors.js.map +1 -1
  28. package/dist/mcp/guarded-fetch.d.ts +33 -0
  29. package/dist/mcp/guarded-fetch.js +391 -0
  30. package/dist/mcp/guarded-fetch.js.map +1 -0
  31. package/dist/mcp/http-node.d.ts +15 -0
  32. package/dist/mcp/http-node.js +179 -0
  33. package/dist/mcp/http-node.js.map +1 -0
  34. package/dist/mcp/index.d.ts +6 -3
  35. package/dist/mcp/index.js +5 -2
  36. package/dist/mcp/index.js.map +1 -1
  37. package/dist/mcp/manager.d.ts +4 -3
  38. package/dist/mcp/manager.js +432 -47
  39. package/dist/mcp/manager.js.map +1 -1
  40. package/dist/mcp/pins.d.ts +9 -0
  41. package/dist/mcp/pins.js +54 -0
  42. package/dist/mcp/pins.js.map +1 -0
  43. package/dist/mcp/record.js +6 -0
  44. package/dist/mcp/record.js.map +1 -1
  45. package/dist/mcp/remote-config.d.ts +20 -0
  46. package/dist/mcp/remote-config.js +208 -0
  47. package/dist/mcp/remote-config.js.map +1 -0
  48. package/dist/mcp/remote.d.ts +20 -0
  49. package/dist/mcp/remote.js +146 -0
  50. package/dist/mcp/remote.js.map +1 -0
  51. package/dist/mcp/types.d.ts +198 -8
  52. package/dist/mcp/types.js.map +1 -1
  53. package/dist/sandbox/escalation-table.d.ts +38 -0
  54. package/dist/sandbox/escalation-table.js +95 -0
  55. package/dist/sandbox/escalation-table.js.map +1 -0
  56. package/dist/sandbox/escalation.d.ts +191 -0
  57. package/dist/sandbox/escalation.js +370 -0
  58. package/dist/sandbox/escalation.js.map +1 -0
  59. package/dist/sandbox/index.d.ts +6 -3
  60. package/dist/sandbox/index.js +6 -3
  61. package/dist/sandbox/index.js.map +1 -1
  62. package/dist/sandbox/widen.d.ts +10 -0
  63. package/dist/sandbox/widen.js +150 -0
  64. package/dist/sandbox/widen.js.map +1 -0
  65. package/dist/server/protocol.schema.json +6 -3
  66. package/dist/session/approvals.d.ts +30 -1
  67. package/dist/session/approvals.js +12 -4
  68. package/dist/session/approvals.js.map +1 -1
  69. package/dist/session/code-call.d.ts +15 -1
  70. package/dist/session/code-call.js +2 -1
  71. package/dist/session/code-call.js.map +1 -1
  72. package/dist/session/escalation-log.d.ts +65 -0
  73. package/dist/session/escalation-log.js +84 -0
  74. package/dist/session/escalation-log.js.map +1 -0
  75. package/dist/session/rebuild.js +12 -3
  76. package/dist/session/rebuild.js.map +1 -1
  77. package/dist/session/runner.js +39 -6
  78. package/dist/session/runner.js.map +1 -1
  79. package/dist/tools/index.d.ts +1 -1
  80. package/dist/tools/index.js.map +1 -1
  81. package/dist/tools/types.d.ts +16 -0
  82. package/dist/tools/types.js.map +1 -1
  83. package/llms.txt +36 -2
  84. package/package.json +7 -6
@@ -0,0 +1,150 @@
1
+ /**
2
+ * The one place a sandbox policy grows: by exactly the path or host one denial named, and never to host-wide access.
3
+ * Only the escalation runner calls it, with the denial from a verified, signed record and the policy that record
4
+ * holds. No tool input or model output reaches it.
5
+ */
6
+ import { ipv4Of, isAddressLiteral, isLocalAddress } from "../credentials/addresses.js";
7
+ // A plain host name or address with an optional port: no wildcard, no scheme, no path and no user.
8
+ const HOST = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*(?::[0-9]{1,5})?$/;
9
+ const IPV6 = /^\[[0-9a-f:.]+\](?::[0-9]{1,5})?$/;
10
+ /** True for an absolute POSIX path in its tidy form, below the root: no `.`, `..`, empty segment or NUL. */
11
+ function isWidenablePath(target) {
12
+ if (!target.startsWith("/") || target === "/" || target.includes("\u0000"))
13
+ return false;
14
+ const parts = target.slice(1).split("/");
15
+ return parts.every((part) => part !== "" && part !== "." && part !== "..");
16
+ }
17
+ // Names that resolve to the host itself on common systems without asking DNS.
18
+ const LOCAL_NAMES = ["localhost", "localhost.localdomain", "ip6-localhost", "ip6-loopback"];
19
+ // A last label that a URL parser or `inet_aton()` reads as a number, which makes the whole host an IPv4 address.
20
+ const NUMERIC_LABEL = /^(?:0x[0-9a-f]*|[0-9]+)$/;
21
+ /**
22
+ * True for a host and optional port that a rerun may be allowed to reach. An address must be written in its one
23
+ * canonical form, so it can be compared with a deny entry: an IPv4 address as four decimal octets with no leading
24
+ * zero, and an IPv6 address that does not wrap an IPv4 one. A host whose last label is a number is an IPv4 address, so
25
+ * `127.1`, `2130706433` and `0x7f.1` are refused rather than read as names. A host that reaches the machine itself or
26
+ * its link is never widened, whatever `deny` says: `localhost` and the names under it, and the unspecified, loopback
27
+ * and link-local addresses, which hold the cloud metadata address.
28
+ */
29
+ function isWidenableHost(target) {
30
+ if (target.length > 255)
31
+ return false;
32
+ const host = hostOf(target);
33
+ if (IPV6.test(target))
34
+ return isAddressLiteral(host) && ipv4Of(host) === undefined && !isLocalAddress(host);
35
+ if (!HOST.test(target))
36
+ return false;
37
+ if (LOCAL_NAMES.includes(host) || host.endsWith(".localhost"))
38
+ return false;
39
+ const last = host.slice(host.lastIndexOf(".") + 1);
40
+ if (NUMERIC_LABEL.test(last))
41
+ return isAddressLiteral(host) && !isLocalAddress(host);
42
+ return true;
43
+ }
44
+ const KINDS = ["filesystem_read", "filesystem_write", "network"];
45
+ /** True when `value` has the shape of a `SandboxDenial`. A record read from the log is checked with it. */
46
+ export function isDenial(value) {
47
+ if (typeof value !== "object" || value === null)
48
+ return false;
49
+ const denial = value;
50
+ return (KINDS.includes(denial.kind) && typeof denial.target === "string" && typeof denial.reason === "string");
51
+ }
52
+ /** The host of a host-and-port entry, in lower case: brackets off an IPv6 address, and any `:port` and trailing dot off. */
53
+ function hostOf(entry) {
54
+ const lower = entry.trim().toLowerCase();
55
+ if (lower.startsWith("[")) {
56
+ const close = lower.indexOf("]");
57
+ return close < 0 ? lower : lower.slice(1, close);
58
+ }
59
+ const colon = lower.lastIndexOf(":");
60
+ // Two or more colons are an IPv6 address without brackets, which has no port to take off.
61
+ const host = colon >= 0 && lower.indexOf(":") === colon ? lower.slice(0, colon) : lower;
62
+ return host.endsWith(".") ? host.slice(0, -1) : host;
63
+ }
64
+ const isIpv6 = (host) => host.includes(":");
65
+ /** One part of an IPv4 address as `inet_aton()` reads it: decimal, octal after a `0`, or hex after `0x`. */
66
+ function looseOctets(part) {
67
+ if (/^0x[0-9a-f]*$/.test(part))
68
+ return part.length === 2 ? 0 : Number.parseInt(part.slice(2), 16);
69
+ if (/^0[0-7]+$/.test(part))
70
+ return Number.parseInt(part, 8);
71
+ return /^(?:0|[1-9][0-9]*)$/.test(part) ? Number(part) : undefined;
72
+ }
73
+ /**
74
+ * The IPv4 address a deny entry's host names in any form `inet_aton()` accepts (`127.1`, `2130706433`, `0x7f.0.0.1`,
75
+ * `0177.0.0.1`), or in an IPv6 form that wraps one, as a number. `undefined` when it names no IPv4 address.
76
+ */
77
+ function denyIpv4(pattern) {
78
+ if (isIpv6(pattern))
79
+ return ipv4Of(pattern);
80
+ const parts = pattern.split(".");
81
+ if (parts.length > 4)
82
+ return undefined;
83
+ const values = [];
84
+ for (const part of parts) {
85
+ const value = looseOctets(part);
86
+ if (value === undefined || !Number.isSafeInteger(value))
87
+ return undefined;
88
+ values.push(value);
89
+ }
90
+ const last = values.pop();
91
+ if (values.some((value) => value > 255) || last >= 256 ** (4 - values.length))
92
+ return undefined;
93
+ return values.reduce((sum, value, index) => sum + value * 256 ** (3 - index), 0) + last;
94
+ }
95
+ /**
96
+ * True when an entry of `deny` closes `target` on some port. An entry matches as `srt` matches a denied domain: `*`
97
+ * matches every host, `*.name` every name under `name` but not `name` itself, and any other entry the host alone, with
98
+ * case ignored. A `*.name` entry also closes an IPv4 address that ends in `.name`, which `srt` would not match. That
99
+ * errs towards not asking. An entry's port is ignored, so a host closed on one port is never widened on any. An IPv4
100
+ * target is closed by an entry that names the same address in any spelling, such as `127.1`, `2130706433` or an IPv6
101
+ * form that wraps it. An IPv6 address counts as closed while `deny` names any IPv6 address, because one address has
102
+ * many spellings. A loopback or link-local entry needs no rule of its own: `isWidenableHost()` refuses every such
103
+ * target. A name that DNS resolves to a closed address can't be seen here; the backend's own deny list covers it.
104
+ */
105
+ function isClosed(deny, target) {
106
+ const host = hostOf(target);
107
+ const address = isIpv6(host) ? undefined : ipv4Of(host);
108
+ return deny.some((entry) => {
109
+ const pattern = hostOf(entry);
110
+ if (pattern === "*")
111
+ return true;
112
+ if (isIpv6(host))
113
+ return isIpv6(pattern);
114
+ if (address !== undefined && denyIpv4(pattern) === address)
115
+ return true;
116
+ if (pattern.startsWith("*."))
117
+ return host.endsWith(pattern.slice(1));
118
+ return host === pattern;
119
+ });
120
+ }
121
+ const plus = (list, item) => (list.includes(item) ? [...list] : [...list, item]);
122
+ /**
123
+ * `policy` with exactly the denial's target added, or `undefined` when the denial can't be widened: a path that is the
124
+ * root, relative or untidy, a host with a wildcard or anything but a host and port, an address in a form other than
125
+ * its canonical one, a host that reaches the machine itself or its link (see `isWidenableHost()`), or a host an entry
126
+ * of the policy's own `network.deny` closes (see `isClosed()`), since the host closed it on purpose.
127
+ */
128
+ export function widenPolicy(policy, denial) {
129
+ const { readRoots, writeRoots, network } = policy;
130
+ const base = {
131
+ readRoots: [...readRoots],
132
+ writeRoots: [...writeRoots],
133
+ network: { allow: [...network.allow], deny: [...network.deny] },
134
+ };
135
+ switch (denial.kind) {
136
+ case "filesystem_read":
137
+ return isWidenablePath(denial.target) ? { ...base, readRoots: plus(readRoots, denial.target) } : undefined;
138
+ case "filesystem_write":
139
+ return isWidenablePath(denial.target) ? { ...base, writeRoots: plus(writeRoots, denial.target) } : undefined;
140
+ case "network": {
141
+ const host = denial.target;
142
+ if (!isWidenableHost(host) || isClosed(network.deny, host))
143
+ return undefined;
144
+ return { ...base, network: { ...base.network, allow: plus(network.allow, host) } };
145
+ }
146
+ default:
147
+ return undefined;
148
+ }
149
+ }
150
+ //# sourceMappingURL=widen.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"widen.js","sourceRoot":"","sources":["../../src/sandbox/widen.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,MAAM,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAGvF,mGAAmG;AACnG,MAAM,IAAI,GAAG,uGAAuG,CAAC;AACrH,MAAM,IAAI,GAAG,mCAAmC,CAAC;AAEjD,4GAA4G;AAC5G,SAAS,eAAe,CAAC,MAAc;IACrC,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC;QAAE,OAAO,KAAK,CAAC;IACzF,MAAM,KAAK,GAAG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AAE,OAAO,EAAE,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;QACrF,CAAC;QACD;YACE,OAAO,SAAS,CAAC;IACrB,CAAC;AACH,CAAC","sourcesContent":["/**\n * The one place a sandbox policy grows: by exactly the path or host one denial named, and never to host-wide access.\n * Only the escalation runner calls it, with the denial from a verified, signed record and the policy that record\n * holds. No tool input or model output reaches it.\n */\nimport { ipv4Of, isAddressLiteral, isLocalAddress } from \"../credentials/addresses.js\";\nimport type { SandboxDenial, SandboxPolicy } from \"./types.js\";\n\n// A plain host name or address with an optional port: no wildcard, no scheme, no path and no user.\nconst HOST = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*(?::[0-9]{1,5})?$/;\nconst IPV6 = /^\\[[0-9a-f:.]+\\](?::[0-9]{1,5})?$/;\n\n/** True for an absolute POSIX path in its tidy form, below the root: no `.`, `..`, empty segment or NUL. */\nfunction isWidenablePath(target: string): boolean {\n if (!target.startsWith(\"/\") || target === \"/\" || target.includes(\"\\u0000\")) return false;\n const parts = target.slice(1).split(\"/\");\n return parts.every((part) => part !== \"\" && part !== \".\" && part !== \"..\");\n}\n\n// Names that resolve to the host itself on common systems without asking DNS.\nconst LOCAL_NAMES: readonly string[] = [\"localhost\", \"localhost.localdomain\", \"ip6-localhost\", \"ip6-loopback\"];\n// A last label that a URL parser or `inet_aton()` reads as a number, which makes the whole host an IPv4 address.\nconst NUMERIC_LABEL = /^(?:0x[0-9a-f]*|[0-9]+)$/;\n\n/**\n * True for a host and optional port that a rerun may be allowed to reach. An address must be written in its one\n * canonical form, so it can be compared with a deny entry: an IPv4 address as four decimal octets with no leading\n * zero, and an IPv6 address that does not wrap an IPv4 one. A host whose last label is a number is an IPv4 address, so\n * `127.1`, `2130706433` and `0x7f.1` are refused rather than read as names. A host that reaches the machine itself or\n * its link is never widened, whatever `deny` says: `localhost` and the names under it, and the unspecified, loopback\n * and link-local addresses, which hold the cloud metadata address.\n */\nfunction isWidenableHost(target: string): boolean {\n if (target.length > 255) return false;\n const host = hostOf(target);\n if (IPV6.test(target)) return isAddressLiteral(host) && ipv4Of(host) === undefined && !isLocalAddress(host);\n if (!HOST.test(target)) return false;\n if (LOCAL_NAMES.includes(host) || host.endsWith(\".localhost\")) return false;\n const last = host.slice(host.lastIndexOf(\".\") + 1);\n if (NUMERIC_LABEL.test(last)) return isAddressLiteral(host) && !isLocalAddress(host);\n return true;\n}\n\nconst KINDS: readonly string[] = [\"filesystem_read\", \"filesystem_write\", \"network\"];\n\n/** True when `value` has the shape of a `SandboxDenial`. A record read from the log is checked with it. */\nexport function isDenial(value: unknown): value is SandboxDenial {\n if (typeof value !== \"object\" || value === null) return false;\n const denial = value as Record<string, unknown>;\n return (\n KINDS.includes(denial.kind as string) && typeof denial.target === \"string\" && typeof denial.reason === \"string\"\n );\n}\n\n/** The host of a host-and-port entry, in lower case: brackets off an IPv6 address, and any `:port` and trailing dot off. */\nfunction hostOf(entry: string): string {\n const lower = entry.trim().toLowerCase();\n if (lower.startsWith(\"[\")) {\n const close = lower.indexOf(\"]\");\n return close < 0 ? lower : lower.slice(1, close);\n }\n const colon = lower.lastIndexOf(\":\");\n // Two or more colons are an IPv6 address without brackets, which has no port to take off.\n const host = colon >= 0 && lower.indexOf(\":\") === colon ? lower.slice(0, colon) : lower;\n return host.endsWith(\".\") ? host.slice(0, -1) : host;\n}\n\nconst isIpv6 = (host: string): boolean => host.includes(\":\");\n\n/** One part of an IPv4 address as `inet_aton()` reads it: decimal, octal after a `0`, or hex after `0x`. */\nfunction looseOctets(part: string): number | undefined {\n if (/^0x[0-9a-f]*$/.test(part)) return part.length === 2 ? 0 : Number.parseInt(part.slice(2), 16);\n if (/^0[0-7]+$/.test(part)) return Number.parseInt(part, 8);\n return /^(?:0|[1-9][0-9]*)$/.test(part) ? Number(part) : undefined;\n}\n\n/**\n * The IPv4 address a deny entry's host names in any form `inet_aton()` accepts (`127.1`, `2130706433`, `0x7f.0.0.1`,\n * `0177.0.0.1`), or in an IPv6 form that wraps one, as a number. `undefined` when it names no IPv4 address.\n */\nfunction denyIpv4(pattern: string): number | undefined {\n if (isIpv6(pattern)) return ipv4Of(pattern);\n const parts = pattern.split(\".\");\n if (parts.length > 4) return undefined;\n const values: number[] = [];\n for (const part of parts) {\n const value = looseOctets(part);\n if (value === undefined || !Number.isSafeInteger(value)) return undefined;\n values.push(value);\n }\n const last = values.pop() as number;\n if (values.some((value) => value > 255) || last >= 256 ** (4 - values.length)) return undefined;\n return values.reduce((sum, value, index) => sum + value * 256 ** (3 - index), 0) + last;\n}\n\n/**\n * True when an entry of `deny` closes `target` on some port. An entry matches as `srt` matches a denied domain: `*`\n * matches every host, `*.name` every name under `name` but not `name` itself, and any other entry the host alone, with\n * case ignored. A `*.name` entry also closes an IPv4 address that ends in `.name`, which `srt` would not match. That\n * errs towards not asking. An entry's port is ignored, so a host closed on one port is never widened on any. An IPv4\n * target is closed by an entry that names the same address in any spelling, such as `127.1`, `2130706433` or an IPv6\n * form that wraps it. An IPv6 address counts as closed while `deny` names any IPv6 address, because one address has\n * many spellings. A loopback or link-local entry needs no rule of its own: `isWidenableHost()` refuses every such\n * target. A name that DNS resolves to a closed address can't be seen here; the backend's own deny list covers it.\n */\nfunction isClosed(deny: readonly string[], target: string): boolean {\n const host = hostOf(target);\n const address = isIpv6(host) ? undefined : ipv4Of(host);\n return deny.some((entry) => {\n const pattern = hostOf(entry);\n if (pattern === \"*\") return true;\n if (isIpv6(host)) return isIpv6(pattern);\n if (address !== undefined && denyIpv4(pattern) === address) return true;\n if (pattern.startsWith(\"*.\")) return host.endsWith(pattern.slice(1));\n return host === pattern;\n });\n}\n\nconst plus = (list: readonly string[], item: string): string[] => (list.includes(item) ? [...list] : [...list, item]);\n\n/**\n * `policy` with exactly the denial's target added, or `undefined` when the denial can't be widened: a path that is the\n * root, relative or untidy, a host with a wildcard or anything but a host and port, an address in a form other than\n * its canonical one, a host that reaches the machine itself or its link (see `isWidenableHost()`), or a host an entry\n * of the policy's own `network.deny` closes (see `isClosed()`), since the host closed it on purpose.\n */\nexport function widenPolicy(policy: SandboxPolicy, denial: SandboxDenial): SandboxPolicy | undefined {\n const { readRoots, writeRoots, network } = policy;\n const base = {\n readRoots: [...readRoots],\n writeRoots: [...writeRoots],\n network: { allow: [...network.allow], deny: [...network.deny] },\n };\n switch (denial.kind) {\n case \"filesystem_read\":\n return isWidenablePath(denial.target) ? { ...base, readRoots: plus(readRoots, denial.target) } : undefined;\n case \"filesystem_write\":\n return isWidenablePath(denial.target) ? { ...base, writeRoots: plus(writeRoots, denial.target) } : undefined;\n case \"network\": {\n const host = denial.target;\n if (!isWidenableHost(host) || isClosed(network.deny, host)) return undefined;\n return { ...base, network: { ...base.network, allow: plus(network.allow, host) } };\n }\n default:\n return undefined;\n }\n}\n"]}
@@ -1285,7 +1285,7 @@
1285
1285
  "$ref": "#/$defs/shape-edc9ba2d47"
1286
1286
  },
1287
1287
  {
1288
- "$ref": "#/$defs/shape-bd3038f936"
1288
+ "$ref": "#/$defs/shape-e3591bd29a"
1289
1289
  },
1290
1290
  {
1291
1291
  "$ref": "#/$defs/shape-16c3a65781"
@@ -2193,7 +2193,7 @@
2193
2193
  "required": ["id", "parentId", "seq", "timestamp", "origin", "type", "name", "path"],
2194
2194
  "additionalProperties": false
2195
2195
  },
2196
- "shape-bd3038f936": {
2196
+ "shape-e3591bd29a": {
2197
2197
  "type": "object",
2198
2198
  "properties": {
2199
2199
  "id": {
@@ -2230,11 +2230,14 @@
2230
2230
  "properties": {
2231
2231
  "transport": {
2232
2232
  "type": "string",
2233
- "enum": ["stdio", "in_process"]
2233
+ "enum": ["stdio", "in_process", "http", "sse"]
2234
2234
  },
2235
2235
  "commandHash": {
2236
2236
  "type": "string"
2237
2237
  },
2238
+ "urlHash": {
2239
+ "type": "string"
2240
+ },
2238
2241
  "era": {
2239
2242
  "type": "string",
2240
2243
  "enum": ["2026-07-28", "legacy"]
@@ -1,7 +1,17 @@
1
+ /**
2
+ * `createApprovals()`: the pause and resume of a call that waits for a person. A gate `ask` ends a turn
3
+ * `awaiting_approval` with the signed request in the log, as an `approval_requested` entry written before the harness's
4
+ * own observers hear of it, and a code call that asks writes the same entry. `pending()` reads the requests that still
5
+ * wait, and `resolve()` answers them from any process that can open the session and load the key ring, because the log
6
+ * holds everything the resume needs. A turn's answers resume the turn; a code call's answer runs the call with no model
7
+ * step. An answer may also cover more than its own call (sticky and grouped answers), and a quorum policy may need
8
+ * several answers before a call runs.
9
+ */
10
+ import type { SessionEntry } from "@buildanagent/protocol";
1
11
  import type { Resolution, SignedPendingRequest } from "@buildanagent/sdk";
2
12
  import type { CodeCallResult, Harness } from "../harness.js";
3
13
  import { type PendingApproval } from "./rebuild.js";
4
- import { type ResumeOptions, type TurnResult } from "./runner.js";
14
+ import { type ResolutionRecord, type ResumeOptions, type TurnResult } from "./runner.js";
5
15
  import type { Session } from "./session.js";
6
16
  /** What a quorum policy says about one request: its answers are enough, not yet, a refusal, or too old. */
7
17
  export type QuorumVerdict = "met" | "pending" | "rejected" | "expired";
@@ -77,5 +87,24 @@ export interface Approvals<H = unknown> {
77
87
  */
78
88
  resolve(session: Session, resolutions: readonly Resolution[], options?: ResolveOptions<H>): Promise<TurnResult | CodeCallResult>;
79
89
  }
90
+ /** The answers already written for each request, oldest first. */
91
+ export declare function answersByRequest(path: readonly SessionEntry[]): Map<string, Resolution[]>;
92
+ /** Refuses an answer set that can't be applied: no signer, an answer twice, a request that doesn't wait, a self-approval. */
93
+ export declare function checkAnswers<H>(harness: Harness<H>, waiting: ReadonlyMap<string, unknown>, resolutions: readonly Resolution[], requesterId: string | undefined): void;
94
+ /**
95
+ * What each waiting request gets once the quorum policy has looked at it: the answer the SDK applies for `met`, a denial
96
+ * for `rejected` and `expired`, and nothing for `pending`, whose new answers are marked as waited on so a crash
97
+ * of this resume never counts them as given. The records returned are the entries to write, denials by the policy
98
+ * included, so the log tells an expiry from any other refusal.
99
+ */
100
+ export declare function settled(policy: QuorumPolicy, waiting: readonly Pick<PendingApproval, "request">[], earlier: ReadonlyMap<string, Resolution[]>, records: readonly ResolutionRecord[]): Promise<{
101
+ forRun: Resolution[];
102
+ records: ResolutionRecord[];
103
+ }>;
104
+ /** The harness and quorum policy `approvals` was made with, or `undefined` for one `createApprovals()` did not make. */
105
+ export declare function approvalsBinding<H>(approvals: Approvals<H>): {
106
+ readonly harness: Harness<H>;
107
+ readonly quorum: QuorumPolicy;
108
+ } | undefined;
80
109
  /** Creates the approvals of `harness`, which needs a `signer` to check the requests it resumes. */
81
110
  export declare function createApprovals<H = unknown>(harness: Harness<H>, settings?: ApprovalsOptions): Approvals<H>;
@@ -48,7 +48,7 @@ function expandGroup(resolutions, groups, groupOf) {
48
48
  return [...out.values()];
49
49
  }
50
50
  /** The answers already written for each request, oldest first. */
51
- function answersByRequest(path) {
51
+ export function answersByRequest(path) {
52
52
  const answers = new Map();
53
53
  for (const entry of path) {
54
54
  if (entry.type === "approval_resolved") {
@@ -58,7 +58,7 @@ function answersByRequest(path) {
58
58
  return answers;
59
59
  }
60
60
  /** Refuses an answer set that can't be applied: no signer, an answer twice, a request that doesn't wait, a self-approval. */
61
- function checkAnswers(harness, waiting, resolutions, requesterId) {
61
+ export function checkAnswers(harness, waiting, resolutions, requesterId) {
62
62
  if (harness.signer === undefined) {
63
63
  throw new HarnessError("approval_unavailable", "the harness has no signer, so no approval can be checked");
64
64
  }
@@ -109,7 +109,7 @@ function outcomeOf(verdict, requestId, answers, fresh) {
109
109
  * of this resume never counts them as given. The records returned are the entries to write, denials by the policy
110
110
  * included, so the log tells an expiry from any other refusal.
111
111
  */
112
- async function settled(policy, waiting, earlier, records) {
112
+ export async function settled(policy, waiting, earlier, records) {
113
113
  const forRun = [];
114
114
  const out = [];
115
115
  for (const { request } of waiting) {
@@ -122,10 +122,16 @@ async function settled(policy, waiting, earlier, records) {
122
122
  }
123
123
  return { forRun, records: out };
124
124
  }
125
+ /** The harness and quorum policy each `Approvals` was made with, so a sandbox escalation shares them. */
126
+ const made = new WeakMap();
127
+ /** The harness and quorum policy `approvals` was made with, or `undefined` for one `createApprovals()` did not make. */
128
+ export function approvalsBinding(approvals) {
129
+ return made.get(approvals);
130
+ }
125
131
  /** Creates the approvals of `harness`, which needs a `signer` to check the requests it resumes. */
126
132
  export function createApprovals(harness, settings = {}) {
127
133
  const policy = settings.quorum ?? oneResolution;
128
- return {
134
+ const approvals = {
129
135
  async pending(session) {
130
136
  const path = await session.path();
131
137
  return [...pendingApprovals(path), ...pendingCodeCalls(path).map(({ request, input }) => ({ request, input }))];
@@ -150,6 +156,8 @@ export function createApprovals(harness, settings = {}) {
150
156
  return resumeTurn(session, harness, { ...options, resolutions: forRun, records: toWrite });
151
157
  },
152
158
  };
159
+ made.set(approvals, { harness: harness, quorum: policy });
160
+ return approvals;
153
161
  }
154
162
  const nameOf = (harness, tool) => harness.registry.get(tool)?.canonicalName ?? tool;
155
163
  const reuseOf = (harness, tool) => harness.registry.get(tool)?.approvalReuse ?? "both";
@@ -1 +1 @@
1
- {"version":3,"file":"approvals.js","sourceRoot":"","sources":["../../src/session/approvals.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAG5C,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAC1G,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAwB,MAAM,oBAAoB,CAAC;AAChG,OAAO,EAAwB,gBAAgB,EAAE,MAAM,cAAc,CAAC;AACtE,OAAO,EAA6C,UAAU,EAAmB,MAAM,aAAa,CAAC;AAErG,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAejE,MAAM,MAAM,GAAG,CAAC,UAAsB,EA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;IACrH,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,KAAK,UAAU,CAAC,SAAS,CAAoB,CAAC;IACnG,MAAM,oBAAoB,CAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;IAC3E,IAAI,OAAO,CAAC,KAAK,KAAK,IAAI;QAAE,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC;IACxG,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAC3G,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,gBAAgB,CAAC,IAAI,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;IAChF,MAAM,GAAG,GAAG,MAAM,iBAAiB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;IACvG,OAAO,cAAc,CACnB,OAAO,EACP,OAAO,EACP,IAAI,EACJ,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,EACvE,OAAO,CACR,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `createApprovals()`: the pause and resume of a call that waits for a person. A gate `ask` ends a turn\n * `awaiting_approval` with the signed request in the log, as an `approval_requested` entry written before the harness's\n * own observers hear of it, and a code call that asks writes the same entry. `pending()` reads the requests that still\n * wait, and `resolve()` answers them from any process that can open the session and load the key ring, because the log\n * holds everything the resume needs. A turn's answers resume the turn; a code call's answer runs the call with no model\n * step. An answer may also cover more than its own call (sticky and grouped answers), and a quorum policy may need\n * several answers before a call runs.\n */\nimport type { SessionEntry } from \"@buildanagent/protocol\";\nimport type { Resolution, SignedPendingRequest } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport type { CodeCallResult, Harness } from \"../harness.js\";\nimport type { ApprovalReuse } from \"../tools/types.js\";\nimport { checkCodeCallRequest, codeCallEffectKey, finishCodeCall, inCodeCallQueue } from \"./code-call.js\";\nimport { codeCallRequestIds, pendingCodeCalls, type WaitingCodeCall } from \"./code-call-log.js\";\nimport { type PendingApproval, pendingApprovals } from \"./rebuild.js\";\nimport { type ResolutionRecord, type ResumeOptions, resumeTurn, type TurnResult } from \"./runner.js\";\nimport type { Session } from \"./session.js\";\nimport { checkReuse, checkSticky, groupIdOf } from \"./sticky.js\";\n\n/** What a quorum policy says about one request: its answers are enough, not yet, a refusal, or too old. */\nexport type QuorumVerdict = \"met\" | \"pending\" | \"rejected\" | \"expired\";\n\n/**\n * Decides when a request has enough answers. `resolutions` are every answer written for the request so far, oldest\n * first. The policy keeps its own clock, so it can expire a request by age or because the policy changed. `met` runs\n * the call, `rejected` and `expired` turn it into a denial, and `pending` leaves it waiting.\n */\nexport interface QuorumPolicy {\n /** Decides one waiting request from every answer recorded for it so far, oldest first. */\n evaluate(request: SignedPendingRequest, resolutions: readonly Resolution[]): Promise<QuorumVerdict> | QuorumVerdict;\n}\n\nconst isDeny = (resolution: Resolution): boolean => \"decision\" in resolution && resolution.decision === \"deny\";\n\n/** The default policy: the latest answer decides. Any answer that is not a deny runs the call, and a deny refuses it. */\nexport const oneResolution: QuorumPolicy = {\n evaluate(_request, resolutions) {\n const latest = resolutions.at(-1);\n if (latest === undefined) return \"pending\";\n return isDeny(latest) ? \"rejected\" : \"met\";\n },\n};\n\n/**\n * A policy that needs `needed` allows from distinct approvers, named by `Resolution.by`. A deny as the latest answer\n * refuses the call, and the allows before it do not count. An allow with no `by` counts as one anonymous approver, so a\n * quorum above one needs the host to name them. Throws `invalid_permission_config` unless `needed` is a whole number\n * of at least one.\n */\nexport function quorumOf(needed: number): QuorumPolicy {\n if (!Number.isInteger(needed) || needed < 1) {\n throw new HarnessError(\n \"invalid_permission_config\",\n `a quorum needs a whole number of approvers of at least 1, got ${needed}`,\n );\n }\n return {\n evaluate(_request, resolutions) {\n if (resolutions.length === 0) return \"pending\";\n if (isDeny(resolutions.at(-1) as Resolution)) return \"rejected\";\n const approvers = new Set(\n resolutions.filter((resolution) => !isDeny(resolution)).map((resolution) => resolution.by ?? \"(unnamed)\"),\n );\n return approvers.size >= needed ? \"met\" : \"pending\";\n },\n };\n}\n\n/**\n * The settings a resume takes besides the answers: a turn's settings, and what the answers cover. A code call's\n * resolution reads `hostContext`, `signal`, `clock`, `newId`, `sticky`, `group` and `requesterId`, and ignores the\n * rest: it makes no model call, so `budgetUsd` and the model settings have nothing to apply to.\n */\nexport interface ResolveOptions<H = unknown> extends Omit<ResumeOptions<H>, \"resolutions\" | \"records\"> {\n /** Make each `allow` cover the same call again, for this run or for this session. */\n readonly sticky?: \"run\" | \"session\";\n /** For a shell tool, cover every command that starts with these words, not only the one approved. */\n readonly commandPrefix?: readonly string[];\n /** Apply each answer to every pending request of the step that has the same tool and the same input. */\n readonly group?: boolean;\n /** Who asked. An approver equal to it is refused: nobody approves their own request. */\n readonly requesterId?: string;\n}\n\n/** The options of `createApprovals()`. */\nexport interface ApprovalsOptions {\n /** When a request has enough answers. Default `oneResolution`. */\n readonly quorum?: QuorumPolicy;\n /** The secret values the host's credential store knows. A sticky allowance that covers one is refused. */\n readonly secrets?: () => readonly string[] | Promise<readonly string[]>;\n}\n\n/** The approvals of one harness. */\nexport interface Approvals<H = unknown> {\n /**\n * The requests of the session that still wait, each with the input its call would run with once approved: a paused\n * turn's, then the code calls', in the order they asked.\n */\n pending(session: Session): Promise<PendingApproval[]>;\n /**\n * Answers waiting requests and resumes the turn. Each answer is written as an `approval_resolved` entry first. The\n * quorum policy then decides each request: `met` goes to the SDK, which verifies the request's signature, call and\n * input, so a tampered request runs nothing and is asked again; `rejected` and `expired` become denials; `pending`\n * leaves the call waiting, and the turn ends `awaiting_approval` again. Each approved call goes through the permission\n * pipeline again, and a deny now turns the approval into a denial. Calling it with no answers evaluates the policy\n * for every request of a paused turn, which is how such a request expires. It leaves a code call's request waiting:\n * the policy decides that call when it is next answered, so a late allow for an expired call comes back `denied`.\n *\n * An answer to a code call's request resolves that call alone and returns a `CodeCallResult`. The request is checked\n * against its signature, the host context it binds and the call's recorded input before anything is written, and a\n * request that fails throws `approval_refused` and runs nothing. The answer is then written and the quorum policy\n * decides. `met` decides the call again with the pipeline, so a deny written since the pause wins, and then runs the\n * tool with `options.hostContext` and `options.signal`, with no model call; `rejected` and `expired` deny it; `pending`\n * returns `awaiting_approval`. A request whose call already has a result, or started before a crash, no longer waits,\n * so its tool runs at most once.\n *\n * Throws `approval_not_pending` for a request that does not wait, `approval_unavailable` without a signer,\n * `approver_is_requester` when an approver is the requester, `approval_reuse_refused` when a tool's `approvalReuse`\n * forbids a sticky or grouped answer, `sticky_refused` for an interpreter prefix or a secret, and `invalid_code_call`\n * for answers that name a code call together with any other request. The host fills `Resolution.by` only after it\n * has authenticated the approver; the harness trusts what it is given.\n */\n resolve(\n session: Session,\n resolutions: readonly Resolution[],\n options?: ResolveOptions<H>,\n ): Promise<TurnResult | CodeCallResult>;\n}\n\nconst decisionOf = (resolution: Resolution): \"allow\" | \"deny\" | undefined =>\n \"decision\" in resolution ? resolution.decision : undefined;\n\n/** Copies an answer to the other requests of its group, each with the same decision, reason and approver. */\nfunction expandGroup(\n resolutions: readonly Resolution[],\n groups: ReadonlyMap<string, string[]>,\n groupOf: ReadonlyMap<string, string>,\n): Resolution[] {\n const out = new Map<string, Resolution>(resolutions.map((resolution) => [resolution.requestId, resolution]));\n for (const resolution of resolutions) {\n for (const other of groups.get(groupOf.get(resolution.requestId) ?? \"\") ?? []) {\n if (!out.has(other)) out.set(other, { ...resolution, requestId: other });\n }\n }\n return [...out.values()];\n}\n\n/** The answers already written for each request, oldest first. */\nfunction answersByRequest(path: readonly SessionEntry[]): Map<string, Resolution[]> {\n const answers = new Map<string, Resolution[]>();\n for (const entry of path) {\n if (entry.type === \"approval_resolved\") {\n answers.set(entry.resolution.requestId, [...(answers.get(entry.resolution.requestId) ?? []), entry.resolution]);\n }\n }\n return answers;\n}\n\n/** Refuses an answer set that can't be applied: no signer, an answer twice, a request that doesn't wait, a self-approval. */\nfunction checkAnswers<H>(\n harness: Harness<H>,\n waiting: ReadonlyMap<string, PendingApproval>,\n resolutions: readonly Resolution[],\n requesterId: string | undefined,\n): void {\n if (harness.signer === undefined) {\n throw new HarnessError(\"approval_unavailable\", \"the harness has no signer, so no approval can be checked\");\n }\n const named = new Set<string>();\n for (const resolution of resolutions) {\n if (named.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `request ${resolution.requestId} is answered twice in one resume`);\n }\n named.add(resolution.requestId);\n if (!waiting.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `no request ${resolution.requestId} is waiting in this session`);\n }\n if (requesterId !== undefined && resolution.by === requesterId) {\n throw new HarnessError(\"approver_is_requester\", `the approver ${resolution.by} is the one who asked`);\n }\n }\n}\n\n/** The synthetic denial for a request the policy refused or let expire, with the record that puts it in the log. */\nfunction denial(requestId: string, verdict: \"rejected\" | \"expired\"): ResolutionRecord {\n const reason = verdict === \"expired\" ? \"the approval expired\" : \"the approval was rejected\";\n return { resolution: { requestId, decision: \"deny\", reason, by: \"policy\" } };\n}\n\n/** An answer without what it would cover: a sticky allowance only takes effect once the quorum is met and the call runs. */\nconst plain = ({ resolution, groupId }: ResolutionRecord): ResolutionRecord => ({\n resolution,\n ...(groupId === undefined ? {} : { groupId }),\n});\n\n/** What the SDK is given for one request, and the entries to write for it, once the quorum policy has decided. */\nfunction outcomeOf(\n verdict: QuorumVerdict,\n requestId: string,\n answers: readonly Resolution[],\n fresh: readonly ResolutionRecord[],\n): { forRun?: Resolution; records: ResolutionRecord[] } {\n const latest = answers.at(-1);\n if (verdict === \"met\" && latest !== undefined) {\n const given = answers.findLast((answer) => !isDeny(answer)) ?? latest;\n // A verdict that flips with no new answer (a clock, a policy) still writes the answer the run is given, unmarked.\n return { forRun: given, records: fresh.length > 0 ? [...fresh] : [{ resolution: given }] };\n }\n if (verdict === \"rejected\" || verdict === \"expired\") {\n // A person's own deny is already in the log; a refusal or an expiry by the policy gets an entry of its own.\n if (verdict === \"rejected\" && latest !== undefined && isDeny(latest))\n return { forRun: latest, records: fresh.map(plain) };\n const refusal = denial(requestId, verdict);\n return { forRun: refusal.resolution, records: [...fresh.map(plain), refusal] };\n }\n return { records: fresh.map((record) => ({ ...plain(record), quorum: \"pending\" as const })) };\n}\n\n/**\n * What each waiting request gets once the quorum policy has looked at it: the answer the SDK applies for `met`, a denial\n * for `rejected` and `expired`, and nothing for `pending`, whose new answers are marked as waited on so a crash\n * of this resume never counts them as given. The records returned are the entries to write, denials by the policy\n * included, so the log tells an expiry from any other refusal.\n */\nasync function settled(\n policy: QuorumPolicy,\n waiting: readonly PendingApproval[],\n earlier: ReadonlyMap<string, Resolution[]>,\n records: readonly ResolutionRecord[],\n): Promise<{ forRun: Resolution[]; records: ResolutionRecord[] }> {\n const forRun: Resolution[] = [];\n const out: ResolutionRecord[] = [];\n for (const { request } of waiting) {\n const fresh = records.filter((record) => record.resolution.requestId === request.id);\n const answers = [...(earlier.get(request.id) ?? []), ...fresh.map((record) => record.resolution)];\n const outcome = outcomeOf(await policy.evaluate(request, answers), request.id, answers, fresh);\n if (outcome.forRun !== undefined) forRun.push(outcome.forRun);\n out.push(...outcome.records);\n }\n return { forRun, records: out };\n}\n\n/** Creates the approvals of `harness`, which needs a `signer` to check the requests it resumes. */\nexport function createApprovals<H = unknown>(harness: Harness<H>, settings: ApprovalsOptions = {}): Approvals<H> {\n const policy = settings.quorum ?? oneResolution;\n return {\n async pending(session) {\n const path = await session.path();\n return [...pendingApprovals(path), ...pendingCodeCalls(path).map(({ request, input }) => ({ request, input }))];\n },\n async resolve(session, resolutions, options = {}) {\n if (options.sticky !== undefined && settings.quorum !== undefined) {\n throw new HarnessError(\n \"sticky_refused\",\n \"a sticky allowance needs the default policy: one approver's click would otherwise skip the quorum on every later call\",\n );\n }\n const path = await session.path();\n const codeRequests = codeCallRequestIds(path);\n if (resolutions.some((resolution) => codeRequests.has(resolution.requestId))) {\n if (resolutions.length !== 1) {\n throw new HarnessError(\n \"invalid_code_call\",\n \"a code call's request is answered on its own, in a resolve() that answers nothing else\",\n );\n }\n const only = resolutions[0] as Resolution;\n return inCodeCallQueue(session, () => resolveCodeCall(harness, session, policy, settings, only, options));\n }\n const waiting = pendingApprovals(path);\n checkAnswers(\n harness,\n new Map(waiting.map((entry) => [entry.request.id, entry])),\n resolutions,\n options.requesterId,\n );\n const records = await recordsFor(harness, waiting, resolutions, options, await (settings.secrets?.() ?? []));\n const { forRun, records: toWrite } = await settled(policy, waiting, answersByRequest(path), records);\n return resumeTurn(session, harness, { ...options, resolutions: forRun, records: toWrite });\n },\n };\n}\n\nconst nameOf = <H>(harness: Harness<H>, tool: string): string => harness.registry.get(tool)?.canonicalName ?? tool;\nconst reuseOf = <H>(harness: Harness<H>, tool: string): ApprovalReuse =>\n harness.registry.get(tool)?.approvalReuse ?? \"both\";\n\n/** The group each waiting request belongs to: its requests, and the id each request's group has. */\nasync function groupsOf<H>(harness: Harness<H>, waiting: readonly PendingApproval[]) {\n const groups = new Map<string, string[]>();\n const groupOf = new Map<string, string>();\n for (const { request, input } of waiting) {\n const id = await groupIdOf(nameOf(harness, request.tool), input, request.inputHash);\n groupOf.set(request.id, id);\n groups.set(id, [...(groups.get(id) ?? []), request.id]);\n }\n return { groups, groupOf };\n}\n\n/** One entry to write: the answer, and, for an allow that is sticky, what it covers once the refusals have passed. */\nfunction recordOf<H>(\n harness: Harness<H>,\n pending: PendingApproval,\n resolution: Resolution,\n groupId: string | undefined,\n options: ResolveOptions<H>,\n secrets: readonly string[],\n): ResolutionRecord {\n const grouped = groupId === undefined ? {} : { groupId };\n if (decisionOf(resolution) !== \"allow\" || options.sticky === undefined) return { resolution, ...grouped };\n const { request, input } = pending;\n checkReuse(request.tool, reuseOf(harness, request.tool), \"sticky\");\n checkSticky(input, options.commandPrefix, secrets);\n const match =\n options.commandPrefix === undefined\n ? { inputHash: request.inputHash }\n : { commandPrefix: [...options.commandPrefix] };\n const version = request.policyVersion === undefined ? {} : { policyVersion: request.policyVersion };\n return {\n resolution,\n sticky: options.sticky,\n allowance: { tool: nameOf(harness, request.tool), ...match, ...version },\n ...grouped,\n };\n}\n\n/** The entries to write: each answer, expanded to its group, with what it covers beyond its own call. */\nasync function recordsFor<H>(\n harness: Harness<H>,\n waiting: readonly PendingApproval[],\n resolutions: readonly Resolution[],\n options: ResolveOptions<H>,\n secrets: readonly string[],\n): Promise<ResolutionRecord[]> {\n const { groups, groupOf } =\n options.group === true ? await groupsOf(harness, waiting) : { groups: new Map(), groupOf: new Map() };\n const expanded = options.group === true ? expandGroup(resolutions, groups, groupOf) : [...resolutions];\n const byId = new Map(waiting.map((entry) => [entry.request.id, entry]));\n // Only a group that really joins requests needs its tool to allow one answer for several calls.\n for (const resolution of expanded) {\n const members = groups.get(groupOf.get(resolution.requestId) ?? \"\") ?? [];\n const tool = (byId.get(resolution.requestId) as PendingApproval).request.tool;\n if (members.length > 1) checkReuse(tool, reuseOf(harness, tool), \"group\");\n }\n return expanded.map((resolution) =>\n recordOf(\n harness,\n byId.get(resolution.requestId) as PendingApproval,\n resolution,\n groupOf.get(resolution.requestId),\n options,\n secrets,\n ),\n );\n}\n\n/**\n * Resolves one code call: the answer is checked against the call's signed request, written with what it covers, and\n * settled by the quorum policy, and the call then waits, is denied, or runs with no model step.\n */\nasync function resolveCodeCall<H>(\n harness: Harness<H>,\n session: Session,\n policy: QuorumPolicy,\n settings: ApprovalsOptions,\n resolution: Resolution,\n options: ResolveOptions<H>,\n): Promise<CodeCallResult> {\n const path = await session.path();\n const waiting = pendingCodeCalls(path);\n checkAnswers(harness, new Map(waiting.map((entry) => [entry.request.id, entry])), [resolution], options.requesterId);\n const call = waiting.find((entry) => entry.request.id === resolution.requestId) as WaitingCodeCall;\n await checkCodeCallRequest(harness, call, resolution, options.hostContext);\n if (options.group === true) checkReuse(call.request.tool, reuseOf(harness, call.request.tool), \"group\");\n const record = recordOf(harness, call, resolution, undefined, options, await (settings.secrets?.() ?? []));\n const outcome = await settled(policy, [call], answersByRequest(path), [record]);\n const key = await codeCallEffectKey(session, harness, harness.registry.get(call.call.tool), call.call);\n return finishCodeCall(\n harness,\n session,\n call,\n { forRun: outcome.forRun[0], records: outcome.records, effectKey: key },\n options,\n );\n}\n"]}
1
+ {"version":3,"file":"approvals.js","sourceRoot":"","sources":["../../src/session/approvals.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAG5C,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAC1G,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAwB,MAAM,oBAAoB,CAAC;AAChG,OAAO,EAAwB,gBAAgB,EAAE,MAAM,cAAc,CAAC;AACtE,OAAO,EAA6C,UAAU,EAAmB,MAAM,aAAa,CAAC;AAErG,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAejE,MAAM,MAAM,GAAG,CAAC,UAAsB,EAAW,EAAE,CAAC,UAAU,IAAI,UAAU,IAAI,UAAU,CAAC,QAAQ,KAAK,MAAM,CAAC;AAE/G,yHAAyH;AACzH,MAAM,CAAC,MAAM,aAAa,GAAiB;IACzC,QAAQ,CAAC,QAAQ,EAAE,WAAW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EAAE,OAAO,CAAC,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,EACvE,OAAO,CACR,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `createApprovals()`: the pause and resume of a call that waits for a person. A gate `ask` ends a turn\n * `awaiting_approval` with the signed request in the log, as an `approval_requested` entry written before the harness's\n * own observers hear of it, and a code call that asks writes the same entry. `pending()` reads the requests that still\n * wait, and `resolve()` answers them from any process that can open the session and load the key ring, because the log\n * holds everything the resume needs. A turn's answers resume the turn; a code call's answer runs the call with no model\n * step. An answer may also cover more than its own call (sticky and grouped answers), and a quorum policy may need\n * several answers before a call runs.\n */\nimport type { SessionEntry } from \"@buildanagent/protocol\";\nimport type { Resolution, SignedPendingRequest } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\nimport type { CodeCallResult, Harness } from \"../harness.js\";\nimport type { ApprovalReuse } from \"../tools/types.js\";\nimport { checkCodeCallRequest, codeCallEffectKey, finishCodeCall, inCodeCallQueue } from \"./code-call.js\";\nimport { codeCallRequestIds, pendingCodeCalls, type WaitingCodeCall } from \"./code-call-log.js\";\nimport { type PendingApproval, pendingApprovals } from \"./rebuild.js\";\nimport { type ResolutionRecord, type ResumeOptions, resumeTurn, type TurnResult } from \"./runner.js\";\nimport type { Session } from \"./session.js\";\nimport { checkReuse, checkSticky, groupIdOf } from \"./sticky.js\";\n\n/** What a quorum policy says about one request: its answers are enough, not yet, a refusal, or too old. */\nexport type QuorumVerdict = \"met\" | \"pending\" | \"rejected\" | \"expired\";\n\n/**\n * Decides when a request has enough answers. `resolutions` are every answer written for the request so far, oldest\n * first. The policy keeps its own clock, so it can expire a request by age or because the policy changed. `met` runs\n * the call, `rejected` and `expired` turn it into a denial, and `pending` leaves it waiting.\n */\nexport interface QuorumPolicy {\n /** Decides one waiting request from every answer recorded for it so far, oldest first. */\n evaluate(request: SignedPendingRequest, resolutions: readonly Resolution[]): Promise<QuorumVerdict> | QuorumVerdict;\n}\n\nconst isDeny = (resolution: Resolution): boolean => \"decision\" in resolution && resolution.decision === \"deny\";\n\n/** The default policy: the latest answer decides. Any answer that is not a deny runs the call, and a deny refuses it. */\nexport const oneResolution: QuorumPolicy = {\n evaluate(_request, resolutions) {\n const latest = resolutions.at(-1);\n if (latest === undefined) return \"pending\";\n return isDeny(latest) ? \"rejected\" : \"met\";\n },\n};\n\n/**\n * A policy that needs `needed` allows from distinct approvers, named by `Resolution.by`. A deny as the latest answer\n * refuses the call, and the allows before it do not count. An allow with no `by` counts as one anonymous approver, so a\n * quorum above one needs the host to name them. Throws `invalid_permission_config` unless `needed` is a whole number\n * of at least one.\n */\nexport function quorumOf(needed: number): QuorumPolicy {\n if (!Number.isInteger(needed) || needed < 1) {\n throw new HarnessError(\n \"invalid_permission_config\",\n `a quorum needs a whole number of approvers of at least 1, got ${needed}`,\n );\n }\n return {\n evaluate(_request, resolutions) {\n if (resolutions.length === 0) return \"pending\";\n if (isDeny(resolutions.at(-1) as Resolution)) return \"rejected\";\n const approvers = new Set(\n resolutions.filter((resolution) => !isDeny(resolution)).map((resolution) => resolution.by ?? \"(unnamed)\"),\n );\n return approvers.size >= needed ? \"met\" : \"pending\";\n },\n };\n}\n\n/**\n * The settings a resume takes besides the answers: a turn's settings, and what the answers cover. A code call's\n * resolution reads `hostContext`, `signal`, `clock`, `newId`, `sticky`, `group` and `requesterId`, and ignores the\n * rest: it makes no model call, so `budgetUsd` and the model settings have nothing to apply to.\n */\nexport interface ResolveOptions<H = unknown> extends Omit<ResumeOptions<H>, \"resolutions\" | \"records\"> {\n /** Make each `allow` cover the same call again, for this run or for this session. */\n readonly sticky?: \"run\" | \"session\";\n /** For a shell tool, cover every command that starts with these words, not only the one approved. */\n readonly commandPrefix?: readonly string[];\n /** Apply each answer to every pending request of the step that has the same tool and the same input. */\n readonly group?: boolean;\n /** Who asked. An approver equal to it is refused: nobody approves their own request. */\n readonly requesterId?: string;\n}\n\n/** The options of `createApprovals()`. */\nexport interface ApprovalsOptions {\n /** When a request has enough answers. Default `oneResolution`. */\n readonly quorum?: QuorumPolicy;\n /** The secret values the host's credential store knows. A sticky allowance that covers one is refused. */\n readonly secrets?: () => readonly string[] | Promise<readonly string[]>;\n}\n\n/** The approvals of one harness. */\nexport interface Approvals<H = unknown> {\n /**\n * The requests of the session that still wait, each with the input its call would run with once approved: a paused\n * turn's, then the code calls', in the order they asked.\n */\n pending(session: Session): Promise<PendingApproval[]>;\n /**\n * Answers waiting requests and resumes the turn. Each answer is written as an `approval_resolved` entry first. The\n * quorum policy then decides each request: `met` goes to the SDK, which verifies the request's signature, call and\n * input, so a tampered request runs nothing and is asked again; `rejected` and `expired` become denials; `pending`\n * leaves the call waiting, and the turn ends `awaiting_approval` again. Each approved call goes through the permission\n * pipeline again, and a deny now turns the approval into a denial. Calling it with no answers evaluates the policy\n * for every request of a paused turn, which is how such a request expires. It leaves a code call's request waiting:\n * the policy decides that call when it is next answered, so a late allow for an expired call comes back `denied`.\n *\n * An answer to a code call's request resolves that call alone and returns a `CodeCallResult`. The request is checked\n * against its signature, the host context it binds and the call's recorded input before anything is written, and a\n * request that fails throws `approval_refused` and runs nothing. The answer is then written and the quorum policy\n * decides. `met` decides the call again with the pipeline, so a deny written since the pause wins, and then runs the\n * tool with `options.hostContext` and `options.signal`, with no model call; `rejected` and `expired` deny it; `pending`\n * returns `awaiting_approval`. A request whose call already has a result, or started before a crash, no longer waits,\n * so its tool runs at most once.\n *\n * Throws `approval_not_pending` for a request that does not wait, `approval_unavailable` without a signer,\n * `approver_is_requester` when an approver is the requester, `approval_reuse_refused` when a tool's `approvalReuse`\n * forbids a sticky or grouped answer, `sticky_refused` for an interpreter prefix or a secret, and `invalid_code_call`\n * for answers that name a code call together with any other request. The host fills `Resolution.by` only after it\n * has authenticated the approver; the harness trusts what it is given.\n */\n resolve(\n session: Session,\n resolutions: readonly Resolution[],\n options?: ResolveOptions<H>,\n ): Promise<TurnResult | CodeCallResult>;\n}\n\nconst decisionOf = (resolution: Resolution): \"allow\" | \"deny\" | undefined =>\n \"decision\" in resolution ? resolution.decision : undefined;\n\n/** Copies an answer to the other requests of its group, each with the same decision, reason and approver. */\nfunction expandGroup(\n resolutions: readonly Resolution[],\n groups: ReadonlyMap<string, string[]>,\n groupOf: ReadonlyMap<string, string>,\n): Resolution[] {\n const out = new Map<string, Resolution>(resolutions.map((resolution) => [resolution.requestId, resolution]));\n for (const resolution of resolutions) {\n for (const other of groups.get(groupOf.get(resolution.requestId) ?? \"\") ?? []) {\n if (!out.has(other)) out.set(other, { ...resolution, requestId: other });\n }\n }\n return [...out.values()];\n}\n\n/** The answers already written for each request, oldest first. */\nexport function answersByRequest(path: readonly SessionEntry[]): Map<string, Resolution[]> {\n const answers = new Map<string, Resolution[]>();\n for (const entry of path) {\n if (entry.type === \"approval_resolved\") {\n answers.set(entry.resolution.requestId, [...(answers.get(entry.resolution.requestId) ?? []), entry.resolution]);\n }\n }\n return answers;\n}\n\n/** Refuses an answer set that can't be applied: no signer, an answer twice, a request that doesn't wait, a self-approval. */\nexport function checkAnswers<H>(\n harness: Harness<H>,\n waiting: ReadonlyMap<string, unknown>,\n resolutions: readonly Resolution[],\n requesterId: string | undefined,\n): void {\n if (harness.signer === undefined) {\n throw new HarnessError(\"approval_unavailable\", \"the harness has no signer, so no approval can be checked\");\n }\n const named = new Set<string>();\n for (const resolution of resolutions) {\n if (named.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `request ${resolution.requestId} is answered twice in one resume`);\n }\n named.add(resolution.requestId);\n if (!waiting.has(resolution.requestId)) {\n throw new HarnessError(\"approval_not_pending\", `no request ${resolution.requestId} is waiting in this session`);\n }\n if (requesterId !== undefined && resolution.by === requesterId) {\n throw new HarnessError(\"approver_is_requester\", `the approver ${resolution.by} is the one who asked`);\n }\n }\n}\n\n/** The synthetic denial for a request the policy refused or let expire, with the record that puts it in the log. */\nfunction denial(requestId: string, verdict: \"rejected\" | \"expired\"): ResolutionRecord {\n const reason = verdict === \"expired\" ? \"the approval expired\" : \"the approval was rejected\";\n return { resolution: { requestId, decision: \"deny\", reason, by: \"policy\" } };\n}\n\n/** An answer without what it would cover: a sticky allowance only takes effect once the quorum is met and the call runs. */\nconst plain = ({ resolution, groupId }: ResolutionRecord): ResolutionRecord => ({\n resolution,\n ...(groupId === undefined ? {} : { groupId }),\n});\n\n/** What the SDK is given for one request, and the entries to write for it, once the quorum policy has decided. */\nfunction outcomeOf(\n verdict: QuorumVerdict,\n requestId: string,\n answers: readonly Resolution[],\n fresh: readonly ResolutionRecord[],\n): { forRun?: Resolution; records: ResolutionRecord[] } {\n const latest = answers.at(-1);\n if (verdict === \"met\" && latest !== undefined) {\n const given = answers.findLast((answer) => !isDeny(answer)) ?? latest;\n // A verdict that flips with no new answer (a clock, a policy) still writes the answer the run is given, unmarked.\n return { forRun: given, records: fresh.length > 0 ? [...fresh] : [{ resolution: given }] };\n }\n if (verdict === \"rejected\" || verdict === \"expired\") {\n // A person's own deny is already in the log; a refusal or an expiry by the policy gets an entry of its own.\n if (verdict === \"rejected\" && latest !== undefined && isDeny(latest))\n return { forRun: latest, records: fresh.map(plain) };\n const refusal = denial(requestId, verdict);\n return { forRun: refusal.resolution, records: [...fresh.map(plain), refusal] };\n }\n return { records: fresh.map((record) => ({ ...plain(record), quorum: \"pending\" as const })) };\n}\n\n/**\n * What each waiting request gets once the quorum policy has looked at it: the answer the SDK applies for `met`, a denial\n * for `rejected` and `expired`, and nothing for `pending`, whose new answers are marked as waited on so a crash\n * of this resume never counts them as given. The records returned are the entries to write, denials by the policy\n * included, so the log tells an expiry from any other refusal.\n */\nexport async function settled(\n policy: QuorumPolicy,\n waiting: readonly Pick<PendingApproval, \"request\">[],\n earlier: ReadonlyMap<string, Resolution[]>,\n records: readonly ResolutionRecord[],\n): Promise<{ forRun: Resolution[]; records: ResolutionRecord[] }> {\n const forRun: Resolution[] = [];\n const out: ResolutionRecord[] = [];\n for (const { request } of waiting) {\n const fresh = records.filter((record) => record.resolution.requestId === request.id);\n const answers = [...(earlier.get(request.id) ?? []), ...fresh.map((record) => record.resolution)];\n const outcome = outcomeOf(await policy.evaluate(request, answers), request.id, answers, fresh);\n if (outcome.forRun !== undefined) forRun.push(outcome.forRun);\n out.push(...outcome.records);\n }\n return { forRun, records: out };\n}\n\n/** The harness and quorum policy each `Approvals` was made with, so a sandbox escalation shares them. */\nconst made = new WeakMap<object, { readonly harness: Harness<never>; readonly quorum: QuorumPolicy }>();\n\n/** The harness and quorum policy `approvals` was made with, or `undefined` for one `createApprovals()` did not make. */\nexport function approvalsBinding<H>(\n approvals: Approvals<H>,\n): { readonly harness: Harness<H>; readonly quorum: QuorumPolicy } | undefined {\n return made.get(approvals) as { readonly harness: Harness<H>; readonly quorum: QuorumPolicy } | undefined;\n}\n\n/** Creates the approvals of `harness`, which needs a `signer` to check the requests it resumes. */\nexport function createApprovals<H = unknown>(harness: Harness<H>, settings: ApprovalsOptions = {}): Approvals<H> {\n const policy = settings.quorum ?? oneResolution;\n const approvals: Approvals<H> = {\n async pending(session) {\n const path = await session.path();\n return [...pendingApprovals(path), ...pendingCodeCalls(path).map(({ request, input }) => ({ request, input }))];\n },\n async resolve(session, resolutions, options = {}) {\n if (options.sticky !== undefined && settings.quorum !== undefined) {\n throw new HarnessError(\n \"sticky_refused\",\n \"a sticky allowance needs the default policy: one approver's click would otherwise skip the quorum on every later call\",\n );\n }\n const path = await session.path();\n const codeRequests = codeCallRequestIds(path);\n if (resolutions.some((resolution) => codeRequests.has(resolution.requestId))) {\n if (resolutions.length !== 1) {\n throw new HarnessError(\n \"invalid_code_call\",\n \"a code call's request is answered on its own, in a resolve() that answers nothing else\",\n );\n }\n const only = resolutions[0] as Resolution;\n return inCodeCallQueue(session, () => resolveCodeCall(harness, session, policy, settings, only, options));\n }\n const waiting = pendingApprovals(path);\n checkAnswers(\n harness,\n new Map(waiting.map((entry) => [entry.request.id, entry])),\n resolutions,\n options.requesterId,\n );\n const records = await recordsFor(harness, waiting, resolutions, options, await (settings.secrets?.() ?? []));\n const { forRun, records: toWrite } = await settled(policy, waiting, answersByRequest(path), records);\n return resumeTurn(session, harness, { ...options, resolutions: forRun, records: toWrite });\n },\n };\n made.set(approvals, { harness: harness as Harness<never>, quorum: policy });\n return approvals;\n}\n\nconst nameOf = <H>(harness: Harness<H>, tool: string): string => harness.registry.get(tool)?.canonicalName ?? tool;\nconst reuseOf = <H>(harness: Harness<H>, tool: string): ApprovalReuse =>\n harness.registry.get(tool)?.approvalReuse ?? \"both\";\n\n/** The group each waiting request belongs to: its requests, and the id each request's group has. */\nasync function groupsOf<H>(harness: Harness<H>, waiting: readonly PendingApproval[]) {\n const groups = new Map<string, string[]>();\n const groupOf = new Map<string, string>();\n for (const { request, input } of waiting) {\n const id = await groupIdOf(nameOf(harness, request.tool), input, request.inputHash);\n groupOf.set(request.id, id);\n groups.set(id, [...(groups.get(id) ?? []), request.id]);\n }\n return { groups, groupOf };\n}\n\n/** One entry to write: the answer, and, for an allow that is sticky, what it covers once the refusals have passed. */\nfunction recordOf<H>(\n harness: Harness<H>,\n pending: PendingApproval,\n resolution: Resolution,\n groupId: string | undefined,\n options: ResolveOptions<H>,\n secrets: readonly string[],\n): ResolutionRecord {\n const grouped = groupId === undefined ? {} : { groupId };\n if (decisionOf(resolution) !== \"allow\" || options.sticky === undefined) return { resolution, ...grouped };\n const { request, input } = pending;\n checkReuse(request.tool, reuseOf(harness, request.tool), \"sticky\");\n checkSticky(input, options.commandPrefix, secrets);\n const match =\n options.commandPrefix === undefined\n ? { inputHash: request.inputHash }\n : { commandPrefix: [...options.commandPrefix] };\n const version = request.policyVersion === undefined ? {} : { policyVersion: request.policyVersion };\n return {\n resolution,\n sticky: options.sticky,\n allowance: { tool: nameOf(harness, request.tool), ...match, ...version },\n ...grouped,\n };\n}\n\n/** The entries to write: each answer, expanded to its group, with what it covers beyond its own call. */\nasync function recordsFor<H>(\n harness: Harness<H>,\n waiting: readonly PendingApproval[],\n resolutions: readonly Resolution[],\n options: ResolveOptions<H>,\n secrets: readonly string[],\n): Promise<ResolutionRecord[]> {\n const { groups, groupOf } =\n options.group === true ? await groupsOf(harness, waiting) : { groups: new Map(), groupOf: new Map() };\n const expanded = options.group === true ? expandGroup(resolutions, groups, groupOf) : [...resolutions];\n const byId = new Map(waiting.map((entry) => [entry.request.id, entry]));\n // Only a group that really joins requests needs its tool to allow one answer for several calls.\n for (const resolution of expanded) {\n const members = groups.get(groupOf.get(resolution.requestId) ?? \"\") ?? [];\n const tool = (byId.get(resolution.requestId) as PendingApproval).request.tool;\n if (members.length > 1) checkReuse(tool, reuseOf(harness, tool), \"group\");\n }\n return expanded.map((resolution) =>\n recordOf(\n harness,\n byId.get(resolution.requestId) as PendingApproval,\n resolution,\n groupOf.get(resolution.requestId),\n options,\n secrets,\n ),\n );\n}\n\n/**\n * Resolves one code call: the answer is checked against the call's signed request, written with what it covers, and\n * settled by the quorum policy, and the call then waits, is denied, or runs with no model step.\n */\nasync function resolveCodeCall<H>(\n harness: Harness<H>,\n session: Session,\n policy: QuorumPolicy,\n settings: ApprovalsOptions,\n resolution: Resolution,\n options: ResolveOptions<H>,\n): Promise<CodeCallResult> {\n const path = await session.path();\n const waiting = pendingCodeCalls(path);\n checkAnswers(harness, new Map(waiting.map((entry) => [entry.request.id, entry])), [resolution], options.requesterId);\n const call = waiting.find((entry) => entry.request.id === resolution.requestId) as WaitingCodeCall;\n await checkCodeCallRequest(harness, call, resolution, options.hostContext);\n if (options.group === true) checkReuse(call.request.tool, reuseOf(harness, call.request.tool), \"group\");\n const record = recordOf(harness, call, resolution, undefined, options, await (settings.secrets?.() ?? []));\n const outcome = await settled(policy, [call], answersByRequest(path), [record]);\n const key = await codeCallEffectKey(session, harness, harness.registry.get(call.call.tool), call.call);\n return finishCodeCall(\n harness,\n session,\n call,\n { forRun: outcome.forRun[0], records: outcome.records, effectKey: key },\n options,\n );\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import type { Origin, SessionEntry } from "@buildanagent/protocol";
1
2
  import { type Resolution } from "@buildanagent/sdk";
2
3
  import type { Clock } from "@buildanagent/sdk/testing";
3
4
  import type { CodeCall, CodeCallResult, Harness } from "../harness.js";
@@ -5,8 +6,19 @@ import type { RegisteredTool } from "../tools/types.js";
5
6
  import { type WaitingCodeCall } from "./code-call-log.js";
6
7
  import { type ResolutionRecord } from "./runner.js";
7
8
  import type { Session } from "./session.js";
9
+ import type { EntryInput } from "./store.js";
10
+ type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
11
+ /** An entry to write, without the fields the writer fills in. */
12
+ export type Body = DistributiveOmit<EntryInput, "id" | "parentId" | "timestamp" | "origin">;
13
+ /** How a code call, or a sandbox escalation, writes: one entry at a time after the one before, with its ids and clock. */
14
+ export interface Io {
15
+ readonly session: Session;
16
+ write(origin: Origin, body: Body, id?: string): Promise<SessionEntry>;
17
+ readonly newId: () => string;
18
+ readonly clock: Clock;
19
+ }
8
20
  /** The settings both a call and its resolution take: where its ids and time come from. */
9
- interface IoOptions {
21
+ export interface IoOptions {
10
22
  readonly clock?: Clock;
11
23
  readonly newId?: () => string;
12
24
  }
@@ -15,6 +27,8 @@ interface RunOptions<H> extends IoOptions {
15
27
  readonly hostContext?: H;
16
28
  readonly signal?: AbortSignal;
17
29
  }
30
+ /** A writer for `session` with the given ids and clock, defaulting to random ids and the system clock. */
31
+ export declare function ioOf(session: Session, options: IoOptions): Io;
18
32
  /** Runs `task` after every code call of `session` that this process started before it. */
19
33
  export declare function inCodeCallQueue<T>(session: Session, task: () => Promise<T>): Promise<T>;
20
34
  /**
@@ -15,7 +15,8 @@ import { recordSessionStart } from "./runner.js";
15
15
  import { findSticky, stickyDecision } from "./sticky.js";
16
16
  // The SDK's default nesting cap, so a tool that starts an agent from a code call nests as it would in a run.
17
17
  const MAX_DEPTH = 2;
18
- function ioOf(session, options) {
18
+ /** A writer for `session` with the given ids and clock, defaulting to random ids and the system clock. */
19
+ export function ioOf(session, options) {
19
20
  const newId = options.newId ?? (() => globalThis.crypto.randomUUID());
20
21
  const clock = options.clock ?? { now: () => new Date().toISOString() };
21
22
  return {