@hasna/infinity 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/LICENSE +3 -0
  2. package/README.md +331 -0
  3. package/dist/cli.js +2965 -0
  4. package/dist/http-api.js +6448 -0
  5. package/dist/index.js +28536 -0
  6. package/dist/migrate.js +346 -0
  7. package/dist/self-hosted-migrate.js +2064 -0
  8. package/dist/self-hosted.js +13180 -0
  9. package/dist/types/authcapsules/codewith-local.d.ts +109 -0
  10. package/dist/types/authcapsules/infinity-agent-policy.d.ts +57 -0
  11. package/dist/types/authcapsules/os-isolated-runner.d.ts +87 -0
  12. package/dist/types/authority/authority.d.ts +342 -0
  13. package/dist/types/authority/effect-journal.d.ts +205 -0
  14. package/dist/types/authority/mutation-journal.d.ts +163 -0
  15. package/dist/types/authority/mutation-tuple.d.ts +26 -0
  16. package/dist/types/authority/state.d.ts +75 -0
  17. package/dist/types/authority/store.d.ts +15 -0
  18. package/dist/types/brokers/checkpoint/archive.d.ts +21 -0
  19. package/dist/types/brokers/checkpoint/bundle.d.ts +22 -0
  20. package/dist/types/brokers/checkpoint/bytes.d.ts +4 -0
  21. package/dist/types/brokers/checkpoint/clean-verifier-finalization.d.ts +62 -0
  22. package/dist/types/brokers/checkpoint/clean-verifier.d.ts +145 -0
  23. package/dist/types/brokers/checkpoint/final-trust-authority.d.ts +55 -0
  24. package/dist/types/brokers/checkpoint/idempotency.d.ts +25 -0
  25. package/dist/types/brokers/checkpoint/journaled-store.d.ts +9 -0
  26. package/dist/types/brokers/checkpoint/manifest-signature.d.ts +135 -0
  27. package/dist/types/brokers/checkpoint/manifest.d.ts +57 -0
  28. package/dist/types/brokers/checkpoint/s3-store.d.ts +215 -0
  29. package/dist/types/brokers/checkpoint/seal-authority.d.ts +86 -0
  30. package/dist/types/brokers/checkpoint/service.d.ts +198 -0
  31. package/dist/types/brokers/checkpoint/signing-message.d.ts +22 -0
  32. package/dist/types/brokers/checkpoint/store.d.ts +76 -0
  33. package/dist/types/brokers/checkpoint/verifier-cleanup-authority.d.ts +108 -0
  34. package/dist/types/brokers/checkpoint/verifier-cleanup.d.ts +391 -0
  35. package/dist/types/brokers/checkpoint/verifier.d.ts +225 -0
  36. package/dist/types/brokers/composition.d.ts +86 -0
  37. package/dist/types/brokers/git/github-app.d.ts +216 -0
  38. package/dist/types/brokers/git/promotion.d.ts +418 -0
  39. package/dist/types/brokers/persistence/contracts.d.ts +77 -0
  40. package/dist/types/brokers/persistence/memory.d.ts +5 -0
  41. package/dist/types/brokers/persistence/migration.d.ts +6 -0
  42. package/dist/types/brokers/persistence/postgres.d.ts +74 -0
  43. package/dist/types/cli/main.d.ts +2 -0
  44. package/dist/types/cli/operation-journal.d.ts +47 -0
  45. package/dist/types/cli/run.d.ts +15 -0
  46. package/dist/types/client/operator-client.d.ts +100 -0
  47. package/dist/types/contracts/dtos.d.ts +198 -0
  48. package/dist/types/contracts/events.d.ts +45 -0
  49. package/dist/types/contracts/fence.d.ts +39 -0
  50. package/dist/types/contracts/operations.d.ts +91 -0
  51. package/dist/types/contracts/runspec.d.ts +75 -0
  52. package/dist/types/contracts/validators.d.ts +8 -0
  53. package/dist/types/core/clock.d.ts +12 -0
  54. package/dist/types/core/errors.d.ts +18 -0
  55. package/dist/types/core/ids.d.ts +10 -0
  56. package/dist/types/core/int64.d.ts +7 -0
  57. package/dist/types/core/strict-json.d.ts +8 -0
  58. package/dist/types/core/validation.d.ts +25 -0
  59. package/dist/types/golden/disposable-task.d.ts +108 -0
  60. package/dist/types/golden/source-pins.d.ts +77 -0
  61. package/dist/types/http/api.d.ts +52 -0
  62. package/dist/types/http/bearer-auth.d.ts +8 -0
  63. package/dist/types/http/main.d.ts +3 -0
  64. package/dist/types/http/self-hosted-main.d.ts +17 -0
  65. package/dist/types/index.d.ts +65 -0
  66. package/dist/types/mcp/schema.d.ts +7 -0
  67. package/dist/types/node-agent/agent.d.ts +174 -0
  68. package/dist/types/node-agent/contracts.d.ts +119 -0
  69. package/dist/types/node-agent/macos-service.d.ts +33 -0
  70. package/dist/types/node-agent/service-cli.d.ts +26 -0
  71. package/dist/types/persistence/composition.d.ts +49 -0
  72. package/dist/types/persistence/migrate-main.d.ts +2 -0
  73. package/dist/types/persistence/migrations.d.ts +30 -0
  74. package/dist/types/persistence/postgres-accounts-operation.d.ts +26 -0
  75. package/dist/types/persistence/postgres-authority.d.ts +69 -0
  76. package/dist/types/persistence/postgres-external-mutation-journal.d.ts +22 -0
  77. package/dist/types/persistence/postgres-json.d.ts +1 -0
  78. package/dist/types/persistence/postgres-mutation-journal.d.ts +31 -0
  79. package/dist/types/persistence/postgres-reconciler.d.ts +34 -0
  80. package/dist/types/persistence/postgres-sandbox-dispatch-authority.d.ts +9 -0
  81. package/dist/types/persistence/self-hosted-migrate-main.d.ts +2 -0
  82. package/dist/types/ports/accounts-operation.d.ts +336 -0
  83. package/dist/types/ports/accounts.d.ts +293 -0
  84. package/dist/types/ports/sandbox-dispatch-authority.d.ts +154 -0
  85. package/dist/types/ports/sandboxes.d.ts +40 -0
  86. package/dist/types/providers/sandbox-dispatch.d.ts +143 -0
  87. package/dist/types/runtime/config.d.ts +61 -0
  88. package/dist/types/runtime/postgres.d.ts +18 -0
  89. package/dist/types/runtime/provider-activation.d.ts +45 -0
  90. package/dist/types/runtime/server.d.ts +68 -0
  91. package/dist/types/testing/accounts-fake.d.ts +31 -0
  92. package/dist/types/testing/fakes.d.ts +2 -0
  93. package/dist/types/testing/node-control-plane-fake.d.ts +20 -0
  94. package/dist/types/testing/reference.d.ts +27 -0
  95. package/dist/types/testing/sandboxes-fake.d.ts +22 -0
  96. package/evidence/provider-live-daytona-v3.json +1 -0
  97. package/evidence/provider-live-e2b-v3.json +1 -0
  98. package/evidence/provider-production-route-daytona-v1.json +1 -0
  99. package/evidence/provider-production-route-e2b-v1.json +1 -0
  100. package/migrations/0001_authority.sql +689 -0
  101. package/migrations/0002_effect_step_global_owner.sql +2 -0
  102. package/migrations/0003_effect_journal_observed_head.sql +34 -0
  103. package/migrations/0004_authority_mutation_journal_binding.sql +15 -0
  104. package/migrations/20260710_checkpoint_broker_v1.sql +163 -0
  105. package/migrations/20260711_accounts_operation_v1.sql +137 -0
  106. package/migrations/20260711_checkpoint_trust_v2.sql +17 -0
  107. package/migrations/20260711_verifier_cleanup_v2.sql +169 -0
  108. package/migrations/20260711_z_accounts_claim_authority_v2.sql +172 -0
  109. package/migrations/20260711_zz_sandbox_dispatch_authority_v1.sql +143 -0
  110. package/migrations/20260712_sandbox_dispatch_authority_v2.sql +58 -0
  111. package/migrations/external-journal/0001_external_authority_mutation_journal.sql +175 -0
  112. package/package.json +47 -0
package/dist/cli.js ADDED
@@ -0,0 +1,2965 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/core/strict-json.ts
5
+ import { createHash } from "crypto";
6
+
7
+ // src/core/errors.ts
8
+ class InfinityError extends Error {
9
+ code;
10
+ status;
11
+ retryable;
12
+ details;
13
+ constructor(code, message, options = {}) {
14
+ super(message, { cause: options.cause });
15
+ this.name = "InfinityError";
16
+ this.code = code;
17
+ this.status = options.status ?? 400;
18
+ this.retryable = options.retryable ?? false;
19
+ this.details = Object.freeze({ ...options.details ?? {} });
20
+ }
21
+ }
22
+
23
+ // src/core/validation.ts
24
+ function isPlainObject(value) {
25
+ if (value === null || typeof value !== "object" || Array.isArray(value))
26
+ return false;
27
+ const prototype = Object.getPrototypeOf(value);
28
+ return prototype === Object.prototype || prototype === null;
29
+ }
30
+ function closedObject(value, label, required, optional = []) {
31
+ if (!isPlainObject(value))
32
+ throw invalid(`${label} must be an object`);
33
+ const allowed = new Set([...required, ...optional]);
34
+ for (const key of Object.keys(value)) {
35
+ if (!allowed.has(key))
36
+ throw invalid(`${label} contains an unknown field`);
37
+ }
38
+ for (const key of required) {
39
+ if (!Object.hasOwn(value, key))
40
+ throw invalid(`${label}.${key} is required`);
41
+ }
42
+ return value;
43
+ }
44
+ function stringValue(value, label, options = {}) {
45
+ if (typeof value !== "string")
46
+ throw invalid(`${label} must be a string`);
47
+ if (value.normalize("NFC") !== value)
48
+ throw invalid(`${label} must use NFC normalization`);
49
+ if (value.length < (options.min ?? 1))
50
+ throw invalid(`${label} is too short`);
51
+ if (value.length > (options.max ?? 256))
52
+ throw invalid(`${label} is too long`);
53
+ if (options.pattern && !options.pattern.test(value))
54
+ throw invalid(`${label} has an invalid format`);
55
+ return value;
56
+ }
57
+ var IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9:_-]*$/;
58
+ var DIGEST_PATTERN = /^sha256:[a-f0-9]{64}$/;
59
+ var CREDENTIAL_CARRIER_PATTERN_SOURCE = "^(?:[sS][kK]-[A-Za-z0-9]|[gG][hH][pPoOuUsSrR]_|[gG][iI][tT][hH][uU][bB]_[pP][aA][tT]_|[xX][oO][xX][bBaApPrRsS]-|[aA][kKsS][iI][aA][0-9A-Za-z]|[aA][iI][zZ][aA]|[nN][pP][mM]_|[xX][aA][iI]-|[cC][tT][xX]7[sS][kK]-)";
60
+ var CREDENTIAL_CARRIER_PATTERN = new RegExp(CREDENTIAL_CARRIER_PATTERN_SOURCE);
61
+ function identifier(value, label) {
62
+ const parsed = stringValue(value, label, { max: 96, pattern: IDENTIFIER_PATTERN });
63
+ if (CREDENTIAL_CARRIER_PATTERN.test(parsed)) {
64
+ throw invalid(`${label} resembles credential material and is not a valid public identifier`);
65
+ }
66
+ if (parsed.length > 48 && /^[A-Za-z0-9]+$/.test(parsed)) {
67
+ throw invalid(`${label} is an unstructured high-entropy secret-carrier candidate`);
68
+ }
69
+ return parsed;
70
+ }
71
+ function digest(value, label) {
72
+ return stringValue(value, label, { min: 71, max: 71, pattern: DIGEST_PATTERN });
73
+ }
74
+ function positiveInteger(value, label, maximum = Number.MAX_SAFE_INTEGER) {
75
+ if (!Number.isSafeInteger(value) || value <= 0 || value > maximum) {
76
+ throw invalid(`${label} must be a positive safe integer`);
77
+ }
78
+ return value;
79
+ }
80
+ function nonnegativeInteger(value, label, maximum = Number.MAX_SAFE_INTEGER) {
81
+ if (!Number.isSafeInteger(value) || value < 0 || value > maximum) {
82
+ throw invalid(`${label} must be a nonnegative safe integer`);
83
+ }
84
+ return value;
85
+ }
86
+ function enumValue(value, label, values) {
87
+ if (typeof value !== "string" || !values.includes(value)) {
88
+ throw invalid(`${label} must be one of ${values.join(", ")}`);
89
+ }
90
+ return value;
91
+ }
92
+ function stringArray(value, label, options = {}) {
93
+ if (!Array.isArray(value))
94
+ throw invalid(`${label} must be an array`);
95
+ if (!options.allowEmpty && value.length === 0)
96
+ throw invalid(`${label} must not be empty`);
97
+ if (value.length > (options.maxItems ?? 64))
98
+ throw invalid(`${label} has too many items`);
99
+ const parser = options.item ?? ((entry, itemLabel) => identifier(entry, itemLabel));
100
+ const parsed = value.map((entry, index) => parser(entry, `${label}[${index}]`));
101
+ if (new Set(parsed).size !== parsed.length)
102
+ throw invalid(`${label} must not contain duplicates`);
103
+ return parsed;
104
+ }
105
+ var RFC3339_MILLIS = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
106
+ function timestamp(value, label) {
107
+ const parsed = stringValue(value, label, { min: 24, max: 24, pattern: RFC3339_MILLIS });
108
+ const millis = Date.parse(parsed);
109
+ if (!Number.isFinite(millis) || new Date(millis).toISOString() !== parsed) {
110
+ throw invalid(`${label} must be a canonical UTC timestamp`);
111
+ }
112
+ return parsed;
113
+ }
114
+ function invalid(message) {
115
+ return new InfinityError("invalid_input", message, { status: 2 });
116
+ }
117
+ function deepFreeze(value) {
118
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
119
+ Object.freeze(value);
120
+ for (const nested of Object.values(value))
121
+ deepFreeze(nested);
122
+ }
123
+ return value;
124
+ }
125
+
126
+ // src/core/strict-json.ts
127
+ var strictDocuments = new WeakSet;
128
+ var strictDocumentDigests = new WeakMap;
129
+
130
+ class StrictJsonParser {
131
+ source;
132
+ index = 0;
133
+ constructor(source) {
134
+ this.source = source;
135
+ }
136
+ parse() {
137
+ this.skipWhitespace();
138
+ const value = this.parseValue();
139
+ this.skipWhitespace();
140
+ if (this.index !== this.source.length)
141
+ throw invalid(`JSON has trailing data at byte ${this.index}`);
142
+ if (value !== null && typeof value === "object")
143
+ strictDocumentDigests.set(value, digestCanonical(value));
144
+ return value;
145
+ }
146
+ parseValue() {
147
+ this.skipWhitespace();
148
+ const char = this.source[this.index];
149
+ if (char === "{")
150
+ return this.parseObject();
151
+ if (char === "[")
152
+ return this.parseArray();
153
+ if (char === '"')
154
+ return this.parseString();
155
+ if (char === "t")
156
+ return this.parseLiteral("true", true);
157
+ if (char === "f")
158
+ return this.parseLiteral("false", false);
159
+ if (char === "n")
160
+ return this.parseLiteral("null", null);
161
+ if (char === "-" || char !== undefined && char >= "0" && char <= "9")
162
+ return this.parseNumber();
163
+ throw invalid(`invalid JSON value at byte ${this.index}`);
164
+ }
165
+ parseObject() {
166
+ this.index += 1;
167
+ const result = Object.create(null);
168
+ const seen = new Set;
169
+ this.skipWhitespace();
170
+ if (this.source[this.index] === "}") {
171
+ this.index += 1;
172
+ strictDocuments.add(result);
173
+ strictDocumentDigests.set(result, digestCanonical(result));
174
+ return result;
175
+ }
176
+ while (true) {
177
+ this.skipWhitespace();
178
+ if (this.source[this.index] !== '"')
179
+ throw invalid(`object key expected at byte ${this.index}`);
180
+ const key = this.parseString();
181
+ if (seen.has(key))
182
+ throw invalid("duplicate JSON key");
183
+ seen.add(key);
184
+ this.skipWhitespace();
185
+ if (this.source[this.index] !== ":")
186
+ throw invalid(`':' expected after object key at byte ${this.index}`);
187
+ this.index += 1;
188
+ result[key] = this.parseValue();
189
+ this.skipWhitespace();
190
+ const delimiter = this.source[this.index];
191
+ if (delimiter === "}") {
192
+ this.index += 1;
193
+ strictDocuments.add(result);
194
+ strictDocumentDigests.set(result, digestCanonical(result));
195
+ return result;
196
+ }
197
+ if (delimiter !== ",")
198
+ throw invalid(`',' or '}' expected at byte ${this.index}`);
199
+ this.index += 1;
200
+ }
201
+ }
202
+ parseArray() {
203
+ this.index += 1;
204
+ const result = [];
205
+ this.skipWhitespace();
206
+ if (this.source[this.index] === "]") {
207
+ this.index += 1;
208
+ strictDocuments.add(result);
209
+ strictDocumentDigests.set(result, digestCanonical(result));
210
+ return result;
211
+ }
212
+ while (true) {
213
+ result.push(this.parseValue());
214
+ this.skipWhitespace();
215
+ const delimiter = this.source[this.index];
216
+ if (delimiter === "]") {
217
+ this.index += 1;
218
+ strictDocuments.add(result);
219
+ strictDocumentDigests.set(result, digestCanonical(result));
220
+ return result;
221
+ }
222
+ if (delimiter !== ",")
223
+ throw invalid(`',' or ']' expected at byte ${this.index}`);
224
+ this.index += 1;
225
+ }
226
+ }
227
+ parseString() {
228
+ const start = this.index;
229
+ this.index += 1;
230
+ let escaped = false;
231
+ while (this.index < this.source.length) {
232
+ const char = this.source[this.index];
233
+ if (escaped) {
234
+ escaped = false;
235
+ this.index += 1;
236
+ continue;
237
+ }
238
+ if (char === "\\") {
239
+ escaped = true;
240
+ this.index += 1;
241
+ continue;
242
+ }
243
+ if (char === '"') {
244
+ this.index += 1;
245
+ let value;
246
+ try {
247
+ value = JSON.parse(this.source.slice(start, this.index));
248
+ } catch (error) {
249
+ throw invalid(`invalid JSON string at byte ${start}`);
250
+ }
251
+ if (value.normalize("NFC") !== value)
252
+ throw invalid(`JSON strings must use NFC normalization at byte ${start}`);
253
+ if (hasUnpairedSurrogate(value))
254
+ throw invalid(`JSON strings must not contain unpaired surrogates at byte ${start}`);
255
+ return value;
256
+ }
257
+ if (char !== undefined && char.charCodeAt(0) < 32)
258
+ throw invalid(`control character in JSON string at byte ${this.index}`);
259
+ this.index += 1;
260
+ }
261
+ throw invalid(`unterminated JSON string at byte ${start}`);
262
+ }
263
+ parseNumber() {
264
+ const rest = this.source.slice(this.index);
265
+ const match = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(rest);
266
+ if (!match)
267
+ throw invalid(`invalid JSON number at byte ${this.index}`);
268
+ const token = match[0];
269
+ this.index += token.length;
270
+ if (!/[.eE]/.test(token)) {
271
+ if (token === "-0")
272
+ throw invalid("negative zero is not canonical JSON");
273
+ const integer = BigInt(token);
274
+ if (integer >= BigInt(Number.MIN_SAFE_INTEGER) && integer <= BigInt(Number.MAX_SAFE_INTEGER))
275
+ return Number(integer);
276
+ return integer;
277
+ }
278
+ const value = Number(token);
279
+ if (!Number.isFinite(value))
280
+ throw invalid(`JSON number must be finite at byte ${this.index - token.length}`);
281
+ if (Object.is(value, -0))
282
+ throw invalid("negative zero is not canonical JSON");
283
+ const significand = token.split(/[eE]/, 1)[0] ?? token;
284
+ if (value === 0 && /[1-9]/.test(significand))
285
+ throw invalid("JSON number underflow would lose information");
286
+ if (JSON.stringify(value) !== token)
287
+ throw invalid("JSON number is non-canonical or loses information");
288
+ return value;
289
+ }
290
+ parseLiteral(token, value) {
291
+ if (!this.source.startsWith(token, this.index))
292
+ throw invalid(`invalid JSON literal at byte ${this.index}`);
293
+ this.index += token.length;
294
+ return value;
295
+ }
296
+ skipWhitespace() {
297
+ while (this.index < this.source.length && /[\t\n\r ]/.test(this.source[this.index] ?? ""))
298
+ this.index += 1;
299
+ }
300
+ }
301
+ function parseStrictJson(source) {
302
+ return new StrictJsonParser(source).parse();
303
+ }
304
+ function canonicalJson(value) {
305
+ if (value === null)
306
+ return "null";
307
+ if (typeof value === "boolean")
308
+ return value ? "true" : "false";
309
+ if (typeof value === "string") {
310
+ if (value.normalize("NFC") !== value)
311
+ throw invalid("canonical JSON strings must use NFC normalization");
312
+ if (hasUnpairedSurrogate(value))
313
+ throw invalid("canonical JSON strings must not contain unpaired surrogates");
314
+ return JSON.stringify(value);
315
+ }
316
+ if (typeof value === "number") {
317
+ if (!Number.isFinite(value) || Object.is(value, -0))
318
+ throw invalid("canonical JSON numbers must be finite and not negative zero");
319
+ if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
320
+ throw invalid("canonical JSON integer Numbers must be safe integers; use bigint for exact wider values");
321
+ }
322
+ return JSON.stringify(value);
323
+ }
324
+ if (typeof value === "bigint")
325
+ return value.toString(10);
326
+ if (Array.isArray(value)) {
327
+ for (let index = 0;index < value.length; index += 1) {
328
+ if (!Object.hasOwn(value, index))
329
+ throw invalid("canonical JSON arrays must not be sparse");
330
+ }
331
+ return `[${value.map((entry) => canonicalJson(entry)).join(",")}]`;
332
+ }
333
+ if (!isPlainObject(value))
334
+ throw invalid("canonical JSON accepts only JSON-compatible values");
335
+ const entries = Object.keys(value).sort().map((key) => {
336
+ if (key.normalize("NFC") !== key)
337
+ throw invalid("canonical JSON keys must use NFC normalization");
338
+ if (hasUnpairedSurrogate(key))
339
+ throw invalid("canonical JSON keys must not contain unpaired surrogates");
340
+ const nested = value[key];
341
+ if (nested === undefined)
342
+ throw invalid("canonical JSON object contains an undefined field");
343
+ return `${JSON.stringify(key)}:${canonicalJson(nested)}`;
344
+ });
345
+ return `{${entries.join(",")}}`;
346
+ }
347
+ function hasUnpairedSurrogate(value) {
348
+ for (let index = 0;index < value.length; index += 1) {
349
+ const unit = value.charCodeAt(index);
350
+ if (unit >= 55296 && unit <= 56319) {
351
+ const next = value.charCodeAt(index + 1);
352
+ if (!(next >= 56320 && next <= 57343))
353
+ return true;
354
+ index += 1;
355
+ } else if (unit >= 56320 && unit <= 57343) {
356
+ return true;
357
+ }
358
+ }
359
+ return false;
360
+ }
361
+ function digestCanonical(value) {
362
+ return `sha256:${createHash("sha256").update(canonicalJson(value), "utf8").digest("hex")}`;
363
+ }
364
+
365
+ // src/core/int64.ts
366
+ var INT64_MAX = 9223372036854775807n;
367
+ function positiveInt64(value, label) {
368
+ if (typeof value === "number") {
369
+ if (!Number.isSafeInteger(value) || value <= 0)
370
+ throw invalid(`${label} must be a positive signed 64-bit integer`);
371
+ return value;
372
+ }
373
+ if (typeof value === "bigint" && value > 0n && value <= INT64_MAX) {
374
+ return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : value;
375
+ }
376
+ throw invalid(`${label} must be a positive signed 64-bit integer`);
377
+ }
378
+ function incrementInt64(value, label) {
379
+ const incremented = BigInt(value) + 1n;
380
+ if (incremented > INT64_MAX)
381
+ throw invalid(`${label} reached signed 64-bit exhaustion`);
382
+ return incremented <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(incremented) : incremented;
383
+ }
384
+ function int64Equal(left, right) {
385
+ return BigInt(left) === BigInt(right);
386
+ }
387
+
388
+ // src/contracts/operations.ts
389
+ var MAX_POSTGRES_INTEGER = 2147483647;
390
+ var MAX_REVISION = MAX_POSTGRES_INTEGER;
391
+ var MAX_MUTABLE_IF_REVISION = MAX_REVISION - 1;
392
+ var CANCEL_RECOVERY_LEASE_DURATION_MS = 300000;
393
+ var RUN_STATES = [
394
+ "admitted",
395
+ "active",
396
+ "cancel_requested",
397
+ "finalizing",
398
+ "succeeded",
399
+ "failed",
400
+ "canceled",
401
+ "lost_uncheckpointed",
402
+ "discarded_uncheckpointed"
403
+ ];
404
+ var ATTEMPT_PHASES = [
405
+ "queued",
406
+ "lane_leased",
407
+ "sandbox_allocating",
408
+ "running",
409
+ "checkpointed",
410
+ "verifying",
411
+ "finalizing",
412
+ "terminal"
413
+ ];
414
+ var ATTEMPT_OUTCOMES = [
415
+ "succeeded",
416
+ "failed_retryable",
417
+ "failed_permanent",
418
+ "canceled",
419
+ "lost_uncheckpointed",
420
+ "discarded_uncheckpointed",
421
+ "policy_denied",
422
+ "budget_exhausted"
423
+ ];
424
+ function isPublicMutationCommand(value) {
425
+ return value === "run.submit" || value === "run.cancel" || value === "run.retry";
426
+ }
427
+ function parsePublicMutationResultExpectation(value) {
428
+ try {
429
+ const expectation = integrityObject(value, "public mutation result expectation");
430
+ const command = enumValue(expectation.command, "public mutation result expectation.command", ["run.submit", "run.cancel", "run.retry"]);
431
+ if (command === "run.submit") {
432
+ integrityClosed(expectation, ["command", "run_spec_digest", "authority_epoch", "route_epoch"], [], "run.submit result expectation");
433
+ return deepFreeze({
434
+ command,
435
+ run_spec_digest: digest(expectation.run_spec_digest, "result expectation.run_spec_digest"),
436
+ authority_epoch: positiveInt64(expectation.authority_epoch, "result expectation.authority_epoch"),
437
+ route_epoch: positiveInt64(expectation.route_epoch, "result expectation.route_epoch")
438
+ });
439
+ }
440
+ integrityClosed(expectation, command === "run.cancel" ? [
441
+ "command",
442
+ "run_id",
443
+ "attempt_id",
444
+ "attempt_number",
445
+ "expected_run_revision",
446
+ "expected_attempt_revision",
447
+ "recovery_lease_duration_ms",
448
+ "prior_lease"
449
+ ] : ["command", "run_id", "predecessor_attempt_id", "expected_attempt_number", "expected_run_revision"], [], `${command} result expectation`);
450
+ const expectedRunRevision = positiveInteger(expectation.expected_run_revision, "result expectation.expected_run_revision", MAX_REVISION);
451
+ if (command === "run.cancel") {
452
+ const priorLease = integrityObject(expectation.prior_lease, "run.cancel result expectation.prior_lease");
453
+ const leaseState = enumValue(priorLease.state, "run.cancel result expectation.prior_lease.state", ["none", "selected"]);
454
+ integrityClosed(priorLease, leaseState === "none" ? ["state"] : ["state", "attempt_lease_id", "lease_epoch"], [], "run.cancel result expectation.prior_lease");
455
+ return deepFreeze({
456
+ command,
457
+ run_id: identifier(expectation.run_id, "result expectation.run_id"),
458
+ attempt_id: identifier(expectation.attempt_id, "result expectation.attempt_id"),
459
+ attempt_number: positiveInteger(expectation.attempt_number, "result expectation.attempt_number", MAX_POSTGRES_INTEGER),
460
+ expected_run_revision: expectedRunRevision,
461
+ expected_attempt_revision: positiveInteger(expectation.expected_attempt_revision, "result expectation.expected_attempt_revision", MAX_REVISION),
462
+ recovery_lease_duration_ms: exactCancelRecoveryLeaseDuration(expectation.recovery_lease_duration_ms, "result expectation.recovery_lease_duration_ms"),
463
+ prior_lease: leaseState === "none" ? { state: leaseState } : {
464
+ state: leaseState,
465
+ attempt_lease_id: identifier(priorLease.attempt_lease_id, "result expectation.prior_lease.attempt_lease_id"),
466
+ lease_epoch: positiveInt64(priorLease.lease_epoch, "result expectation.prior_lease.lease_epoch")
467
+ }
468
+ });
469
+ }
470
+ return deepFreeze({
471
+ command,
472
+ run_id: identifier(expectation.run_id, "result expectation.run_id"),
473
+ predecessor_attempt_id: identifier(expectation.predecessor_attempt_id, "result expectation.predecessor_attempt_id"),
474
+ expected_attempt_number: positiveInteger(expectation.expected_attempt_number, "result expectation.expected_attempt_number", MAX_POSTGRES_INTEGER),
475
+ expected_run_revision: expectedRunRevision
476
+ });
477
+ } catch (error) {
478
+ throw asIntegrityFailure(error, "public mutation result expectation failed integrity validation");
479
+ }
480
+ }
481
+ function parsePublicMutationResult(command, value, expectedOperationId, expectation) {
482
+ try {
483
+ const result = integrityObject(value, `${command} result`);
484
+ const operationId = identifier(result.operation_id, `${command} result.operation_id`);
485
+ if (operationId !== expectedOperationId) {
486
+ throw integrity("Infinity mutation success inner operation ID differs from its protected operation");
487
+ }
488
+ if (command === "run.submit") {
489
+ integrityClosed(result, [
490
+ "operation_id",
491
+ "run_spec_id",
492
+ "run_spec_digest",
493
+ "run_id",
494
+ "attempt_id",
495
+ "attempt_number",
496
+ "attempt_phase",
497
+ "state",
498
+ "run_revision",
499
+ "attempt_revision",
500
+ "authority_epoch",
501
+ "route_epoch",
502
+ "idempotency"
503
+ ], [], "run.submit result");
504
+ identifier(result.run_spec_id, "run.submit result.run_spec_id");
505
+ digest(result.run_spec_digest, "run.submit result.run_spec_digest");
506
+ identifier(result.run_id, "run.submit result.run_id");
507
+ identifier(result.attempt_id, "run.submit result.attempt_id");
508
+ positiveInteger(result.attempt_number, "run.submit result.attempt_number", MAX_POSTGRES_INTEGER);
509
+ enumValue(result.attempt_phase, "run.submit result.attempt_phase", ATTEMPT_PHASES);
510
+ enumValue(result.state, "run.submit result.state", RUN_STATES);
511
+ positiveInteger(result.run_revision, "run.submit result.run_revision", MAX_REVISION);
512
+ positiveInteger(result.attempt_revision, "run.submit result.attempt_revision", MAX_REVISION);
513
+ positiveInt64(result.authority_epoch, "run.submit result.authority_epoch");
514
+ positiveInt64(result.route_epoch, "run.submit result.route_epoch");
515
+ } else {
516
+ const leaseFields = [
517
+ "attempt_lease_id",
518
+ "lease_epoch",
519
+ "lease_holder_principal",
520
+ "lease_issued_at",
521
+ "lease_expires_at",
522
+ "lease_duration_ms"
523
+ ];
524
+ integrityClosed(result, [
525
+ "operation_id",
526
+ "run_id",
527
+ "attempt_id",
528
+ "attempt_number",
529
+ "state",
530
+ "outcome",
531
+ "run_revision",
532
+ "attempt_revision",
533
+ "idempotency"
534
+ ], leaseFields, `${command} result`);
535
+ identifier(result.run_id, `${command} result.run_id`);
536
+ identifier(result.attempt_id, `${command} result.attempt_id`);
537
+ positiveInteger(result.attempt_number, `${command} result.attempt_number`, MAX_POSTGRES_INTEGER);
538
+ enumValue(result.state, `${command} result.state`, RUN_STATES);
539
+ if (result.outcome !== null)
540
+ enumValue(result.outcome, `${command} result.outcome`, ATTEMPT_OUTCOMES);
541
+ positiveInteger(result.run_revision, `${command} result.run_revision`, MAX_REVISION);
542
+ positiveInteger(result.attempt_revision, `${command} result.attempt_revision`, MAX_REVISION);
543
+ const present = leaseFields.filter((field) => Object.hasOwn(result, field)).length;
544
+ if (present !== 0 && present !== leaseFields.length) {
545
+ throw integrity(`Infinity ${command} result has a partial lease tuple`);
546
+ }
547
+ if (present !== 0) {
548
+ identifier(result.attempt_lease_id, `${command} result.attempt_lease_id`);
549
+ positiveInt64(result.lease_epoch, `${command} result.lease_epoch`);
550
+ identifier(result.lease_holder_principal, `${command} result.lease_holder_principal`);
551
+ timestamp(result.lease_issued_at, `${command} result.lease_issued_at`);
552
+ timestamp(result.lease_expires_at, `${command} result.lease_expires_at`);
553
+ positiveInteger(result.lease_duration_ms, `${command} result.lease_duration_ms`, MAX_POSTGRES_INTEGER);
554
+ }
555
+ }
556
+ const idempotency = integrityObject(result.idempotency, `${command} result.idempotency`);
557
+ integrityClosed(idempotency, ["replayed"], [], `${command} result.idempotency`);
558
+ if (typeof idempotency.replayed !== "boolean") {
559
+ throw integrity(`Infinity ${command} result has an invalid idempotency receipt`);
560
+ }
561
+ assertIntrinsicResultPostconditions(command, result);
562
+ if (expectation !== undefined)
563
+ assertExpectedResultBindings(command, result, expectation);
564
+ return deepFreeze({ ...result });
565
+ } catch (error) {
566
+ throw asIntegrityFailure(error, `Infinity ${command} result failed integrity validation`);
567
+ }
568
+ }
569
+ function assertExpectedResultBindings(command, result, expectation) {
570
+ if (expectation.command !== command)
571
+ throw integrity("Infinity mutation result expectation command differs from the response command");
572
+ if (expectation.command === "run.submit") {
573
+ if (result.run_spec_digest !== expectation.run_spec_digest || !int64Equal(result.authority_epoch, expectation.authority_epoch) || !int64Equal(result.route_epoch, expectation.route_epoch) || result.state !== "admitted" || result.attempt_phase !== "queued" || result.attempt_number !== 1 || result.run_revision !== 1 || result.attempt_revision !== 1) {
574
+ throw integrity("Infinity run.submit result differs from the exact admitted request binding");
575
+ }
576
+ return;
577
+ }
578
+ if (result.run_id !== expectation.run_id) {
579
+ throw integrity(`Infinity ${command} result run ID differs from the protected request`);
580
+ }
581
+ const leaseFields = [
582
+ "attempt_lease_id",
583
+ "lease_epoch",
584
+ "lease_holder_principal",
585
+ "lease_issued_at",
586
+ "lease_expires_at",
587
+ "lease_duration_ms"
588
+ ];
589
+ const present = leaseFields.filter((field) => Object.hasOwn(result, field)).length;
590
+ if (expectation.command === "run.cancel") {
591
+ const expectedLeaseEpoch = expectation.prior_lease.state === "none" ? 1 : incrementInt64(expectation.prior_lease.lease_epoch, "run.cancel result expected lease_epoch");
592
+ if (result.attempt_id !== expectation.attempt_id || result.attempt_number !== expectation.attempt_number || result.state !== "cancel_requested" || result.lease_holder_principal !== "service:cancel-recovery" || result.run_revision !== expectation.expected_run_revision || result.attempt_revision !== expectation.expected_attempt_revision || result.lease_duration_ms !== expectation.recovery_lease_duration_ms || !int64Equal(result.lease_epoch, expectedLeaseEpoch) || expectation.prior_lease.state === "selected" && result.attempt_lease_id === expectation.prior_lease.attempt_lease_id || present !== leaseFields.length) {
593
+ throw integrity("Infinity run.cancel result differs from the exact cancellation request binding");
594
+ }
595
+ return;
596
+ }
597
+ if (result.attempt_id === expectation.predecessor_attempt_id || result.attempt_number !== expectation.expected_attempt_number || result.state !== "active" || result.outcome !== null || result.run_revision !== expectation.expected_run_revision || result.attempt_number < 2 || result.attempt_revision !== 1 || present !== 0) {
598
+ throw integrity("Infinity run.retry result is not a fresh unleased active attempt");
599
+ }
600
+ }
601
+ function assertIntrinsicResultPostconditions(command, result) {
602
+ if (command === "run.submit") {
603
+ if (result.state !== "admitted" || result.attempt_phase !== "queued" || result.attempt_number !== 1 || result.run_revision !== 1 || result.attempt_revision !== 1) {
604
+ throw integrity("Infinity run.submit result violates intrinsic admission postconditions");
605
+ }
606
+ return;
607
+ }
608
+ const leaseFields = [
609
+ "attempt_lease_id",
610
+ "lease_epoch",
611
+ "lease_holder_principal",
612
+ "lease_issued_at",
613
+ "lease_expires_at",
614
+ "lease_duration_ms"
615
+ ];
616
+ const present = leaseFields.filter((field) => Object.hasOwn(result, field)).length;
617
+ if (command === "run.cancel") {
618
+ const issuedAt = Date.parse(result.lease_issued_at);
619
+ const expiresAt = Date.parse(result.lease_expires_at);
620
+ if (result.state !== "cancel_requested" || result.run_revision < 2 || result.attempt_revision === 1 || present !== leaseFields.length || result.lease_holder_principal !== "service:cancel-recovery" || result.lease_duration_ms !== CANCEL_RECOVERY_LEASE_DURATION_MS || expiresAt - issuedAt !== CANCEL_RECOVERY_LEASE_DURATION_MS) {
621
+ throw integrity("Infinity run.cancel result violates intrinsic cancellation recovery postconditions");
622
+ }
623
+ return;
624
+ }
625
+ if (result.state !== "active" || result.outcome !== null || result.run_revision < 2 || result.attempt_number < 2 || result.attempt_revision !== 1 || present !== 0) {
626
+ throw integrity("Infinity run.retry result violates intrinsic fresh-attempt postconditions");
627
+ }
628
+ }
629
+ function exactCancelRecoveryLeaseDuration(value, label) {
630
+ const parsed = positiveInteger(value, label, MAX_POSTGRES_INTEGER);
631
+ if (parsed !== CANCEL_RECOVERY_LEASE_DURATION_MS) {
632
+ throw integrity(`${label} must equal the fixed cancellation recovery lease duration`);
633
+ }
634
+ return CANCEL_RECOVERY_LEASE_DURATION_MS;
635
+ }
636
+ function parsePublicOperationResolution(value, expectedOperationId, expectation) {
637
+ try {
638
+ const resolution = integrityObject(value, "operation resolution");
639
+ const operationId = identifier(resolution.operation_id, "operation resolution.operation_id");
640
+ if (operationId !== expectedOperationId) {
641
+ throw integrity("Infinity resolution response operation ID does not match the protected request");
642
+ }
643
+ const status = enumValue(resolution.status, "operation resolution.status", ["committed", "in_flight", "aborted", "unknown"]);
644
+ if (status === "unknown") {
645
+ integrityClosed(resolution, ["operation_id", "status"], [], "unknown operation resolution");
646
+ return deepFreeze({ operation_id: operationId, status });
647
+ }
648
+ const required = status === "committed" ? ["operation_id", "status", "operation_binding", "result"] : ["operation_id", "status", "operation_binding"];
649
+ integrityClosed(resolution, required, [], `${status} operation resolution`);
650
+ const binding = integrityObject(resolution.operation_binding, "operation resolution.operation_binding");
651
+ integrityClosed(binding, ["command", "idempotency_key", "scope_digest", "request_hash"], [], "operation binding");
652
+ const command = enumValue(binding.command, "operation binding.command", ["run.submit", "run.cancel", "run.retry"]);
653
+ const parsedBinding = {
654
+ command,
655
+ idempotency_key: identifier(binding.idempotency_key, "operation binding.idempotency_key"),
656
+ scope_digest: digest(binding.scope_digest, "operation binding.scope_digest"),
657
+ request_hash: digest(binding.request_hash, "operation binding.request_hash")
658
+ };
659
+ if (status === "committed") {
660
+ const result = parsePublicMutationResult(command, resolution.result, operationId, expectation);
661
+ return deepFreeze({ operation_id: operationId, status, operation_binding: parsedBinding, result });
662
+ }
663
+ return deepFreeze({ operation_id: operationId, status, operation_binding: parsedBinding });
664
+ } catch (error) {
665
+ throw asIntegrityFailure(error, "Infinity operation resolution failed integrity validation");
666
+ }
667
+ }
668
+ function integrityObject(value, label) {
669
+ if (!isPlainObject(value))
670
+ throw integrity(`Infinity ${label} must be an object`);
671
+ return value;
672
+ }
673
+ function integrityClosed(value, required, optional, label) {
674
+ const allowed = new Set([...required, ...optional]);
675
+ if (Object.keys(value).some((field) => !allowed.has(field)) || required.some((field) => !Object.hasOwn(value, field))) {
676
+ throw integrity(`Infinity ${label} is not a closed complete object`);
677
+ }
678
+ }
679
+ function integrity(message, cause) {
680
+ return new InfinityError("integrity_failure", message, { status: 502, cause });
681
+ }
682
+ function asIntegrityFailure(error, fallback) {
683
+ if (error instanceof InfinityError && error.code === "integrity_failure")
684
+ return error;
685
+ return integrity(error instanceof Error ? error.message : fallback, error);
686
+ }
687
+
688
+ // src/contracts/runspec.ts
689
+ var DATA_CLASSES = ["public", "internal_non_sensitive", "confidential"];
690
+ var OUTPUT_CLASSES = ["patch", "test_receipt", "checkpoint", "evidence", "none"];
691
+ var EVIDENCE_CLASSES = ["checkpoint_seal", "test_receipt", "verification_receipt", "secret_scan_receipt", "cleanup_receipt"];
692
+ var OBJECT_FORMATS = ["sha1", "sha256"];
693
+ var identifierSchema = {
694
+ type: "string",
695
+ minLength: 1,
696
+ maxLength: 96,
697
+ pattern: "^[A-Za-z0-9][A-Za-z0-9:_-]*$",
698
+ not: {
699
+ anyOf: [
700
+ { pattern: CREDENTIAL_CARRIER_PATTERN_SOURCE },
701
+ { minLength: 49, pattern: "^[A-Za-z0-9]+$" }
702
+ ]
703
+ }
704
+ };
705
+ var digestSchema = {
706
+ type: "string",
707
+ minLength: 71,
708
+ maxLength: 71,
709
+ pattern: "^sha256:[a-f0-9]{64}$"
710
+ };
711
+ var RUN_SPEC_INPUT_SCHEMA = deepFreeze({
712
+ type: "object",
713
+ additionalProperties: false,
714
+ required: [
715
+ "api_version",
716
+ "kind",
717
+ "canonicalization_version",
718
+ "metadata",
719
+ "source",
720
+ "environment",
721
+ "policy",
722
+ "task"
723
+ ],
724
+ properties: {
725
+ api_version: { const: "infinity.runspec/v1alpha1" },
726
+ kind: { const: "RunSpec" },
727
+ canonicalization_version: { const: "infinity.canonical-json/v1" },
728
+ metadata: {
729
+ type: "object",
730
+ additionalProperties: false,
731
+ required: ["project_id", "logical_work_key"],
732
+ properties: {
733
+ project_id: identifierSchema,
734
+ logical_work_key: identifierSchema
735
+ }
736
+ },
737
+ source: {
738
+ type: "object",
739
+ additionalProperties: false,
740
+ required: ["repository_id", "object_format", "commit_sha", "expected_base_sha"],
741
+ properties: {
742
+ repository_id: identifierSchema,
743
+ object_format: { enum: OBJECT_FORMATS },
744
+ commit_sha: { type: "string", pattern: "^(?:[a-f0-9]{40}|[a-f0-9]{64})$" },
745
+ expected_base_sha: { type: "string", pattern: "^(?:[a-f0-9]{40}|[a-f0-9]{64})$" }
746
+ },
747
+ allOf: [
748
+ {
749
+ if: { properties: { object_format: { const: "sha1" } } },
750
+ then: {
751
+ properties: {
752
+ commit_sha: { type: "string", pattern: "^[a-f0-9]{40}$" },
753
+ expected_base_sha: { type: "string", pattern: "^[a-f0-9]{40}$" }
754
+ }
755
+ }
756
+ },
757
+ {
758
+ if: { properties: { object_format: { const: "sha256" } } },
759
+ then: {
760
+ properties: {
761
+ commit_sha: { type: "string", pattern: "^[a-f0-9]{64}$" },
762
+ expected_base_sha: { type: "string", pattern: "^[a-f0-9]{64}$" }
763
+ }
764
+ }
765
+ }
766
+ ]
767
+ },
768
+ environment: {
769
+ type: "object",
770
+ additionalProperties: false,
771
+ required: ["image_digest"],
772
+ properties: { image_digest: digestSchema }
773
+ },
774
+ policy: {
775
+ type: "object",
776
+ additionalProperties: false,
777
+ required: [
778
+ "data_class",
779
+ "network_policy_digest",
780
+ "lane_policy_class",
781
+ "budget",
782
+ "approval_policy_id",
783
+ "cancellation_policy_id",
784
+ "checkpoint_policy_id",
785
+ "verification_policy_id",
786
+ "cleanup_policy_id",
787
+ "steering",
788
+ "policy_decision_digest",
789
+ "repository_automation_policy_digest"
790
+ ],
791
+ properties: {
792
+ data_class: { enum: DATA_CLASSES },
793
+ capabilities: {
794
+ type: "array",
795
+ maxItems: 64,
796
+ uniqueItems: true,
797
+ items: identifierSchema
798
+ },
799
+ network_policy_digest: digestSchema,
800
+ lane_policy_class: identifierSchema,
801
+ budget: {
802
+ type: "object",
803
+ additionalProperties: false,
804
+ required: ["wall_time_ms", "resource_units", "cost_minor_units"],
805
+ properties: {
806
+ wall_time_ms: { type: "integer", minimum: 1, maximum: 86400000 },
807
+ resource_units: { type: "integer", minimum: 1, maximum: 1e6 },
808
+ cost_minor_units: { type: "integer", minimum: 0, maximum: 1e9 }
809
+ }
810
+ },
811
+ approval_policy_id: identifierSchema,
812
+ retry_policy: {
813
+ type: "object",
814
+ additionalProperties: false,
815
+ required: ["max_attempts", "retryable_reasons"],
816
+ properties: {
817
+ max_attempts: { type: "integer", minimum: 1, maximum: 10 },
818
+ retryable_reasons: {
819
+ type: "array",
820
+ maxItems: 16,
821
+ uniqueItems: true,
822
+ items: identifierSchema
823
+ }
824
+ }
825
+ },
826
+ cancellation_policy_id: identifierSchema,
827
+ checkpoint_policy_id: identifierSchema,
828
+ verification_policy_id: identifierSchema,
829
+ cleanup_policy_id: identifierSchema,
830
+ steering: {
831
+ type: "object",
832
+ additionalProperties: false,
833
+ required: ["allowed_media_types", "max_bytes"],
834
+ properties: {
835
+ allowed_media_types: {
836
+ type: "array",
837
+ maxItems: 16,
838
+ uniqueItems: true,
839
+ items: {
840
+ type: "string",
841
+ minLength: 1,
842
+ maxLength: 80,
843
+ pattern: "^[a-z0-9.+-]+/[a-z0-9.+-]+$"
844
+ }
845
+ },
846
+ max_bytes: { type: "integer", minimum: 1, maximum: 1048576 }
847
+ }
848
+ },
849
+ policy_decision_digest: digestSchema,
850
+ repository_automation_policy_digest: digestSchema
851
+ }
852
+ },
853
+ task: {
854
+ type: "object",
855
+ additionalProperties: false,
856
+ required: ["expected_outputs", "expected_evidence"],
857
+ properties: {
858
+ input_artifacts: {
859
+ type: "array",
860
+ maxItems: 128,
861
+ items: {
862
+ type: "object",
863
+ additionalProperties: false,
864
+ required: ["artifact_id", "digest"],
865
+ properties: {
866
+ artifact_id: identifierSchema,
867
+ digest: digestSchema
868
+ }
869
+ }
870
+ },
871
+ expected_outputs: {
872
+ type: "array",
873
+ minItems: 1,
874
+ maxItems: 16,
875
+ uniqueItems: true,
876
+ items: { enum: OUTPUT_CLASSES }
877
+ },
878
+ expected_evidence: {
879
+ type: "array",
880
+ minItems: 1,
881
+ maxItems: 16,
882
+ uniqueItems: true,
883
+ items: { enum: EVIDENCE_CLASSES }
884
+ }
885
+ }
886
+ }
887
+ }
888
+ });
889
+ function parseRunSpec(value) {
890
+ const root = closedObject(value, "RunSpec", [
891
+ "api_version",
892
+ "kind",
893
+ "canonicalization_version",
894
+ "metadata",
895
+ "source",
896
+ "environment",
897
+ "policy",
898
+ "task"
899
+ ]);
900
+ if (root.api_version !== "infinity.runspec/v1alpha1")
901
+ throw invalid("RunSpec.api_version is unsupported");
902
+ if (root.kind !== "RunSpec")
903
+ throw invalid("RunSpec.kind must be RunSpec");
904
+ if (root.canonicalization_version !== "infinity.canonical-json/v1")
905
+ throw invalid("RunSpec.canonicalization_version is unsupported");
906
+ const metadata = closedObject(root.metadata, "RunSpec.metadata", [
907
+ "project_id",
908
+ "logical_work_key"
909
+ ]);
910
+ const logicalWorkKey = identifier(metadata.logical_work_key, "RunSpec.metadata.logical_work_key");
911
+ const source = closedObject(root.source, "RunSpec.source", [
912
+ "repository_id",
913
+ "object_format",
914
+ "commit_sha",
915
+ "expected_base_sha"
916
+ ]);
917
+ const objectFormat = enumValue(source.object_format, "RunSpec.source.object_format", OBJECT_FORMATS);
918
+ const oidLength = objectFormat === "sha1" ? 40 : 64;
919
+ const oidPattern = new RegExp(`^[a-f0-9]{${oidLength}}$`);
920
+ const commitSha = stringValue(source.commit_sha, "RunSpec.source.commit_sha", { min: oidLength, max: oidLength, pattern: oidPattern });
921
+ const expectedBaseSha = stringValue(source.expected_base_sha, "RunSpec.source.expected_base_sha", { min: oidLength, max: oidLength, pattern: oidPattern });
922
+ const environment = closedObject(root.environment, "RunSpec.environment", ["image_digest"]);
923
+ const policy = closedObject(root.policy, "RunSpec.policy", [
924
+ "data_class",
925
+ "network_policy_digest",
926
+ "lane_policy_class",
927
+ "budget",
928
+ "approval_policy_id",
929
+ "cancellation_policy_id",
930
+ "checkpoint_policy_id",
931
+ "verification_policy_id",
932
+ "cleanup_policy_id",
933
+ "steering",
934
+ "policy_decision_digest",
935
+ "repository_automation_policy_digest"
936
+ ], ["capabilities", "retry_policy"]);
937
+ const budget = closedObject(policy.budget, "RunSpec.policy.budget", [
938
+ "wall_time_ms",
939
+ "resource_units",
940
+ "cost_minor_units"
941
+ ]);
942
+ const steering = closedObject(policy.steering, "RunSpec.policy.steering", ["allowed_media_types", "max_bytes"]);
943
+ const retry = policy.retry_policy === undefined ? { max_attempts: 1, retryable_reasons: [] } : parseRetryPolicy(policy.retry_policy);
944
+ const task = closedObject(root.task, "RunSpec.task", ["expected_outputs", "expected_evidence"], ["input_artifacts"]);
945
+ const artifactInputs = task.input_artifacts ?? [];
946
+ if (!Array.isArray(artifactInputs) || artifactInputs.length > 128)
947
+ throw invalid("RunSpec.task.input_artifacts must be a bounded array");
948
+ const inputArtifacts = artifactInputs.map((entry, index) => {
949
+ const artifact = closedObject(entry, `RunSpec.task.input_artifacts[${index}]`, ["artifact_id", "digest"]);
950
+ return {
951
+ artifact_id: identifier(artifact.artifact_id, `RunSpec.task.input_artifacts[${index}].artifact_id`),
952
+ digest: digest(artifact.digest, `RunSpec.task.input_artifacts[${index}].digest`)
953
+ };
954
+ });
955
+ if (new Set(inputArtifacts.map((entry) => entry.artifact_id)).size !== inputArtifacts.length) {
956
+ throw invalid("RunSpec.task.input_artifacts contains duplicate artifact IDs");
957
+ }
958
+ const parsed = {
959
+ api_version: "infinity.runspec/v1alpha1",
960
+ kind: "RunSpec",
961
+ canonicalization_version: "infinity.canonical-json/v1",
962
+ metadata: {
963
+ project_id: identifier(metadata.project_id, "RunSpec.metadata.project_id"),
964
+ logical_work_key: logicalWorkKey
965
+ },
966
+ source: {
967
+ repository_id: identifier(source.repository_id, "RunSpec.source.repository_id"),
968
+ object_format: objectFormat,
969
+ commit_sha: commitSha,
970
+ expected_base_sha: expectedBaseSha
971
+ },
972
+ environment: { image_digest: digest(environment.image_digest, "RunSpec.environment.image_digest") },
973
+ policy: {
974
+ data_class: enumValue(policy.data_class, "RunSpec.policy.data_class", DATA_CLASSES),
975
+ capabilities: stringArray(policy.capabilities ?? [], "RunSpec.policy.capabilities", { allowEmpty: true, maxItems: 64 }),
976
+ network_policy_digest: digest(policy.network_policy_digest, "RunSpec.policy.network_policy_digest"),
977
+ lane_policy_class: identifier(policy.lane_policy_class, "RunSpec.policy.lane_policy_class"),
978
+ budget: {
979
+ wall_time_ms: positiveInteger(budget.wall_time_ms, "RunSpec.policy.budget.wall_time_ms", 86400000),
980
+ resource_units: positiveInteger(budget.resource_units, "RunSpec.policy.budget.resource_units", 1e6),
981
+ cost_minor_units: nonnegativeInteger(budget.cost_minor_units, "RunSpec.policy.budget.cost_minor_units", 1e9)
982
+ },
983
+ approval_policy_id: identifier(policy.approval_policy_id, "RunSpec.policy.approval_policy_id"),
984
+ retry_policy: retry,
985
+ cancellation_policy_id: identifier(policy.cancellation_policy_id, "RunSpec.policy.cancellation_policy_id"),
986
+ checkpoint_policy_id: identifier(policy.checkpoint_policy_id, "RunSpec.policy.checkpoint_policy_id"),
987
+ verification_policy_id: identifier(policy.verification_policy_id, "RunSpec.policy.verification_policy_id"),
988
+ cleanup_policy_id: identifier(policy.cleanup_policy_id, "RunSpec.policy.cleanup_policy_id"),
989
+ steering: {
990
+ allowed_media_types: stringArray(steering.allowed_media_types, "RunSpec.policy.steering.allowed_media_types", {
991
+ allowEmpty: true,
992
+ maxItems: 16,
993
+ item: (entry, label) => stringValue(entry, label, { max: 80, pattern: /^[a-z0-9.+-]+\/[a-z0-9.+-]+$/ })
994
+ }),
995
+ max_bytes: positiveInteger(steering.max_bytes, "RunSpec.policy.steering.max_bytes", 1048576)
996
+ },
997
+ policy_decision_digest: digest(policy.policy_decision_digest, "RunSpec.policy.policy_decision_digest"),
998
+ repository_automation_policy_digest: digest(policy.repository_automation_policy_digest, "RunSpec.policy.repository_automation_policy_digest")
999
+ },
1000
+ task: {
1001
+ input_artifacts: inputArtifacts,
1002
+ expected_outputs: stringArray(task.expected_outputs, "RunSpec.task.expected_outputs", {
1003
+ maxItems: 16,
1004
+ item: (entry, label) => enumValue(entry, label, OUTPUT_CLASSES)
1005
+ }),
1006
+ expected_evidence: stringArray(task.expected_evidence, "RunSpec.task.expected_evidence", {
1007
+ maxItems: 16,
1008
+ item: (entry, label) => enumValue(entry, label, EVIDENCE_CLASSES)
1009
+ })
1010
+ }
1011
+ };
1012
+ return deepFreeze(parsed);
1013
+ }
1014
+ function parseRetryPolicy(value) {
1015
+ const retry = closedObject(value, "RunSpec.policy.retry_policy", ["max_attempts", "retryable_reasons"]);
1016
+ return {
1017
+ max_attempts: positiveInteger(retry.max_attempts, "RunSpec.policy.retry_policy.max_attempts", 10),
1018
+ retryable_reasons: stringArray(retry.retryable_reasons, "RunSpec.policy.retry_policy.retryable_reasons", {
1019
+ allowEmpty: true,
1020
+ maxItems: 16
1021
+ })
1022
+ };
1023
+ }
1024
+ function runSpecDigest(spec) {
1025
+ return digestCanonical(spec);
1026
+ }
1027
+
1028
+ // src/client/operator-client.ts
1029
+ var operatorHttpStatuses = new WeakMap;
1030
+ function operatorEnvelopeHttpStatus(envelope) {
1031
+ return operatorHttpStatuses.get(envelope);
1032
+ }
1033
+ function inheritOperatorEnvelopeHttpStatus(source, target) {
1034
+ const status = operatorHttpStatuses.get(source);
1035
+ if (status !== undefined)
1036
+ operatorHttpStatuses.set(target, status);
1037
+ return target;
1038
+ }
1039
+
1040
+ class OperatorHttpClient {
1041
+ fetchImpl;
1042
+ endpoint;
1043
+ constructor(endpoint, fetchImpl = fetch) {
1044
+ this.fetchImpl = fetchImpl;
1045
+ const parsed = new URL(endpoint);
1046
+ const loopbackHttp = parsed.protocol === "http:" && ["127.0.0.1", "::1", "localhost"].includes(parsed.hostname);
1047
+ if (parsed.protocol !== "https:" && !loopbackHttp)
1048
+ throw new Error("Infinity endpoint must use HTTPS or explicit loopback HTTP");
1049
+ if (parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash) {
1050
+ throw new Error("Infinity endpoint must be a credential-free origin");
1051
+ }
1052
+ this.endpoint = parsed;
1053
+ }
1054
+ version() {
1055
+ return this.request("GET", "/v1/version", "version");
1056
+ }
1057
+ doctor() {
1058
+ return this.request("GET", "/v1/doctor", "doctor");
1059
+ }
1060
+ listCapabilities() {
1061
+ return this.request("GET", "/v1/capabilities", "capability.list");
1062
+ }
1063
+ validateRun(spec) {
1064
+ return this.request("POST", "/v1/run-specs:validate", "run.validate", spec);
1065
+ }
1066
+ planRun(spec) {
1067
+ return this.request("POST", "/v1/run-specs:plan", "run.plan", spec);
1068
+ }
1069
+ submitRun(request) {
1070
+ return this.request("POST", "/v1/runs", "run.submit", {
1071
+ authority_epoch: request.authorityEpoch,
1072
+ route_lineage_id: request.routeLineageId,
1073
+ route_id: request.routeId,
1074
+ route_epoch: request.routeEpoch,
1075
+ spec: request.spec
1076
+ }, request, undefined, {
1077
+ command: "run.submit",
1078
+ run_spec_digest: runSpecDigest(parseRunSpec(request.spec)),
1079
+ authority_epoch: request.authorityEpoch,
1080
+ route_epoch: request.routeEpoch
1081
+ });
1082
+ }
1083
+ getRun(runId) {
1084
+ return this.request("GET", `/v1/runs/${encodeURIComponent(runId)}`, "run.get");
1085
+ }
1086
+ listRuns(options) {
1087
+ const query = new URLSearchParams;
1088
+ if (options.limit !== undefined)
1089
+ query.set("limit", String(options.limit));
1090
+ if (options.cursor !== undefined)
1091
+ query.set("cursor", options.cursor);
1092
+ const suffix = query.size === 0 ? "" : `?${query.toString()}`;
1093
+ return this.request("GET", `/v1/runs${suffix}`, "run.list");
1094
+ }
1095
+ waitRun(runId, timeoutMs) {
1096
+ const query = new URLSearchParams({ timeout_ms: String(timeoutMs) });
1097
+ return this.request("GET", `/v1/runs/${encodeURIComponent(runId)}:wait?${query.toString()}`, "run.wait");
1098
+ }
1099
+ readRunEvents(runId, options) {
1100
+ const query = new URLSearchParams({
1101
+ cursor: options.cursor,
1102
+ limit: String(options.limit),
1103
+ wait_ms: String(options.waitMs)
1104
+ });
1105
+ return this.request("GET", `/v1/runs/${encodeURIComponent(runId)}/events?${query.toString()}`, "run.events.read");
1106
+ }
1107
+ cancelRun(request) {
1108
+ const leaseSelector = serializeLeaseSelector(request);
1109
+ return this.request("POST", `/v1/runs/${encodeURIComponent(request.runId)}:cancel`, "run.cancel", {
1110
+ authority_epoch: request.authorityEpoch,
1111
+ if_revision: request.ifRevision,
1112
+ attempt_id: request.attemptId,
1113
+ if_attempt_number: request.expectedAttemptNumber,
1114
+ if_attempt_revision: request.expectedAttemptRevision,
1115
+ ...leaseSelector,
1116
+ reason_code: request.reasonCode
1117
+ }, request, undefined, {
1118
+ command: "run.cancel",
1119
+ run_id: request.runId,
1120
+ attempt_id: request.attemptId,
1121
+ attempt_number: request.expectedAttemptNumber,
1122
+ expected_run_revision: nextExpectedRunRevision(request.ifRevision),
1123
+ expected_attempt_revision: nextExpectedAttemptRevision(request.expectedAttemptRevision),
1124
+ recovery_lease_duration_ms: CANCEL_RECOVERY_LEASE_DURATION_MS,
1125
+ prior_lease: request.attemptLeaseId === undefined ? { state: "none" } : {
1126
+ state: "selected",
1127
+ attempt_lease_id: request.attemptLeaseId,
1128
+ lease_epoch: request.leaseEpoch
1129
+ }
1130
+ });
1131
+ }
1132
+ retryRun(request) {
1133
+ const leaseSelector = serializeLeaseSelector(request);
1134
+ return this.request("POST", `/v1/runs/${encodeURIComponent(request.runId)}:retry`, "run.retry", {
1135
+ authority_epoch: request.authorityEpoch,
1136
+ if_revision: request.ifRevision,
1137
+ attempt_id: request.attemptId,
1138
+ if_attempt_number: request.expectedAttemptNumber,
1139
+ if_attempt_revision: request.expectedAttemptRevision,
1140
+ ...leaseSelector
1141
+ }, request, undefined, {
1142
+ command: "run.retry",
1143
+ run_id: request.runId,
1144
+ predecessor_attempt_id: request.attemptId,
1145
+ expected_attempt_number: nextExpectedAttemptNumber(request.expectedAttemptNumber),
1146
+ expected_run_revision: nextExpectedRunRevision(request.ifRevision)
1147
+ });
1148
+ }
1149
+ authorizeSandboxDispatch(request) {
1150
+ return this.request("POST", "/v1/sandbox-dispatch-authorizations", "sandbox-dispatch.authorize", request);
1151
+ }
1152
+ dispatchProductionSandbox(request) {
1153
+ return this.request("POST", "/v1/production-sandbox-dispatches", "sandbox-dispatch.production-dispatch", request);
1154
+ }
1155
+ resolveOperation(operationId) {
1156
+ return this.request("GET", `/v1/operations/${encodeURIComponent(operationId)}`, "operation.resolve", undefined, undefined, operationId);
1157
+ }
1158
+ async request(method, path, expectedCommand, body, mutation, expectedResolutionOperationId, resultExpectation) {
1159
+ const url = new URL(path, this.endpoint);
1160
+ const requestId = `request-${crypto.randomUUID()}`;
1161
+ const headers = new Headers({ "x-request-id": requestId });
1162
+ if (body !== undefined)
1163
+ headers.set("content-type", "application/json");
1164
+ if (mutation) {
1165
+ headers.set("x-infinity-operation-id", mutation.operationId);
1166
+ headers.set("idempotency-key", mutation.idempotencyKey);
1167
+ }
1168
+ const response = await this.fetchImpl(url, {
1169
+ method,
1170
+ headers,
1171
+ ...body === undefined ? {} : { body: canonicalJson(body) },
1172
+ redirect: "error"
1173
+ });
1174
+ const parsed = parseOperatorEnvelope(await readBoundedResponse(response), response.status);
1175
+ if (parsed.request_id !== requestId || parsed.command !== expectedCommand) {
1176
+ throw new InfinityError("protocol_incompatible", "Infinity response correlation does not match the protected request", { status: 502 });
1177
+ }
1178
+ if (mutation) {
1179
+ const missingBeforeReservation = !parsed.ok && parsed.operation_id === undefined && isOperatorPreReservationFailure(parsed);
1180
+ if (!missingBeforeReservation && parsed.operation_id !== mutation.operationId) {
1181
+ throw new InfinityError("integrity_failure", "Infinity mutation response operation ID does not match the protected request", { status: 502 });
1182
+ }
1183
+ if (parsed.ok) {
1184
+ if (!isPublicMutationCommand(expectedCommand)) {
1185
+ throw new InfinityError("protocol_incompatible", "Infinity returned success for an unsupported mutation command", { status: 502 });
1186
+ }
1187
+ parsePublicMutationResult(expectedCommand, parsed.data, mutation.operationId, resultExpectation);
1188
+ }
1189
+ }
1190
+ if (expectedResolutionOperationId && parsed.ok) {
1191
+ const data = parsed.data;
1192
+ if (!isPlainObject(data) || data.operation_id !== expectedResolutionOperationId) {
1193
+ throw new InfinityError("integrity_failure", "Infinity resolution response operation ID does not match the protected request", { status: 502 });
1194
+ }
1195
+ parsePublicOperationResolution(data, expectedResolutionOperationId);
1196
+ }
1197
+ return parsed;
1198
+ }
1199
+ }
1200
+ function serializeLeaseSelector(request) {
1201
+ const hasAttemptLeaseId = request.attemptLeaseId !== undefined;
1202
+ const hasLeaseEpoch = request.leaseEpoch !== undefined;
1203
+ if (hasAttemptLeaseId !== hasLeaseEpoch) {
1204
+ throw new InfinityError("invalid_input", "attempt_lease_id and lease_epoch must be supplied together");
1205
+ }
1206
+ if (!hasAttemptLeaseId)
1207
+ return {};
1208
+ return {
1209
+ attempt_lease_id: identifier(request.attemptLeaseId, "attempt_lease_id"),
1210
+ lease_epoch: request.leaseEpoch
1211
+ };
1212
+ }
1213
+ function nextExpectedRunRevision(value) {
1214
+ const current = positiveInteger(value, "if_revision", MAX_MUTABLE_IF_REVISION);
1215
+ return current + 1;
1216
+ }
1217
+ function nextExpectedAttemptRevision(value) {
1218
+ const current = positiveInteger(value, "if_attempt_revision", MAX_MUTABLE_IF_REVISION);
1219
+ return current + 1;
1220
+ }
1221
+ function nextExpectedAttemptNumber(value) {
1222
+ const current = positiveInteger(value, "if_attempt_number", MAX_MUTABLE_IF_REVISION);
1223
+ return current + 1;
1224
+ }
1225
+ var MAXIMUM_RESPONSE_BYTES = 1048576;
1226
+ async function readBoundedResponse(response) {
1227
+ const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
1228
+ if (contentType !== "application/json")
1229
+ throw incompatible("Infinity API response content type is incompatible");
1230
+ const declaredLength = response.headers.get("content-length");
1231
+ if (declaredLength !== null && (!/^\d+$/.test(declaredLength) || Number(declaredLength) > MAXIMUM_RESPONSE_BYTES)) {
1232
+ throw incompatible("Infinity API response exceeds the byte limit");
1233
+ }
1234
+ if (!response.body)
1235
+ throw incompatible("Infinity API response body is missing");
1236
+ const reader = response.body.getReader();
1237
+ const chunks = [];
1238
+ let total = 0;
1239
+ while (true) {
1240
+ const item = await reader.read();
1241
+ if (item.done)
1242
+ break;
1243
+ total += item.value.byteLength;
1244
+ if (total > MAXIMUM_RESPONSE_BYTES) {
1245
+ await reader.cancel();
1246
+ throw incompatible("Infinity API response exceeds the byte limit");
1247
+ }
1248
+ chunks.push(item.value);
1249
+ }
1250
+ if (total === 0)
1251
+ throw incompatible("Infinity API response body is empty");
1252
+ const bytes = new Uint8Array(total);
1253
+ let offset = 0;
1254
+ for (const chunk of chunks) {
1255
+ bytes.set(chunk, offset);
1256
+ offset += chunk.byteLength;
1257
+ }
1258
+ try {
1259
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1260
+ } catch (error) {
1261
+ throw incompatible("Infinity API response is not valid UTF-8", error);
1262
+ }
1263
+ }
1264
+ function parseOperatorEnvelope(source, status) {
1265
+ try {
1266
+ const value = parseStrictJson(source);
1267
+ const root = closedObject(value, "operator envelope", [
1268
+ "schema_version",
1269
+ "ok",
1270
+ "request_id",
1271
+ "command",
1272
+ "server_time",
1273
+ "warnings",
1274
+ "next_actions"
1275
+ ], ["operation_id", "data", "error"]);
1276
+ if (root.schema_version !== "infinity.operator/v1")
1277
+ throw incompatible("Infinity API schema version is incompatible");
1278
+ if (typeof root.ok !== "boolean")
1279
+ throw incompatible("Infinity API envelope ok must be boolean");
1280
+ const requestId = identifier(root.request_id, "operator envelope request_id");
1281
+ const command = stringValue(root.command, "operator envelope command", { max: 80, pattern: /^[a-z][a-z0-9.:-]*$/ });
1282
+ const serverTime = timestamp(root.server_time, "operator envelope server_time");
1283
+ const operationId = root.operation_id === undefined ? undefined : identifier(root.operation_id, "operator envelope operation_id");
1284
+ const warnings = boundedArray(root.warnings, "operator envelope warnings");
1285
+ const nextActions = boundedArray(root.next_actions, "operator envelope next_actions");
1286
+ const statusIsSuccess = status >= 200 && status < 300;
1287
+ if (statusIsSuccess !== root.ok)
1288
+ throw incompatible("Infinity API HTTP status and envelope outcome disagree");
1289
+ if (root.ok) {
1290
+ if (root.error !== undefined || !Object.hasOwn(root, "data"))
1291
+ throw incompatible("Infinity API success envelope is incomplete");
1292
+ return rememberHttpStatus(deepFreeze({
1293
+ schema_version: "infinity.operator/v1",
1294
+ ok: true,
1295
+ request_id: requestId,
1296
+ command,
1297
+ server_time: serverTime,
1298
+ ...operationId === undefined ? {} : { operation_id: operationId },
1299
+ data: root.data,
1300
+ warnings,
1301
+ next_actions: nextActions
1302
+ }), status);
1303
+ }
1304
+ if (root.data !== undefined)
1305
+ throw incompatible("Infinity API error envelope contains success-only fields");
1306
+ const error = closedObject(root.error, "operator envelope error", [
1307
+ "code",
1308
+ "message",
1309
+ "retryable",
1310
+ "retry_after_ms",
1311
+ "details",
1312
+ "remediation"
1313
+ ]);
1314
+ if (typeof error.retryable !== "boolean")
1315
+ throw incompatible("Infinity API error retryable must be boolean");
1316
+ if (error.retry_after_ms !== null)
1317
+ nonnegativeInteger(error.retry_after_ms, "operator envelope retry_after_ms");
1318
+ if (!isPlainObject(error.details))
1319
+ throw incompatible("Infinity API error details must be an object");
1320
+ const code = stringValue(error.code, "operator envelope error code", { max: 80, pattern: /^[a-z][a-z0-9_]*$/ });
1321
+ if (!allowedErrorStatuses(code).includes(status)) {
1322
+ throw incompatible("Infinity API error code and HTTP status are incompatible");
1323
+ }
1324
+ return rememberHttpStatus(deepFreeze({
1325
+ schema_version: "infinity.operator/v1",
1326
+ ok: false,
1327
+ request_id: requestId,
1328
+ command,
1329
+ server_time: serverTime,
1330
+ ...operationId === undefined ? {} : { operation_id: operationId },
1331
+ error: {
1332
+ code,
1333
+ message: stringValue(error.message, "operator envelope error message", { max: 500 }),
1334
+ retryable: error.retryable,
1335
+ retry_after_ms: error.retry_after_ms,
1336
+ details: deepFreeze({ ...error.details }),
1337
+ remediation: stringValue(error.remediation, "operator envelope remediation", { max: 500 })
1338
+ },
1339
+ warnings,
1340
+ next_actions: nextActions
1341
+ }), status);
1342
+ } catch (error) {
1343
+ if (error instanceof InfinityError && ["protocol_incompatible", "integrity_failure"].includes(error.code))
1344
+ throw error;
1345
+ throw incompatible("Infinity API returned an incompatible envelope", error);
1346
+ }
1347
+ }
1348
+ function rememberHttpStatus(envelope, status) {
1349
+ operatorHttpStatuses.set(envelope, status);
1350
+ return envelope;
1351
+ }
1352
+ function isOperatorPreReservationFailure(envelope) {
1353
+ if (envelope.ok || !envelope.error || !isPlainObject(envelope.error.details))
1354
+ return false;
1355
+ return envelope.error.details.operation_reservation === "not_started";
1356
+ }
1357
+ function allowedErrorStatuses(code) {
1358
+ const byCode = {
1359
+ invalid_input: [400],
1360
+ not_found: [404],
1361
+ idempotency_key_reused: [409],
1362
+ operation_id_conflict: [409],
1363
+ logical_work_conflict: [409],
1364
+ authority_epoch_mismatch: [409],
1365
+ stale_revision: [409],
1366
+ stale_lease_epoch: [409],
1367
+ state_conflict: [409, 412, 503],
1368
+ policy_denied: [403, 412],
1369
+ approval_required: [412],
1370
+ approval_digest_mismatch: [412],
1371
+ capability_denied: [403, 503],
1372
+ integrity_failure: [412],
1373
+ capacity_unavailable: [409, 429, 503],
1374
+ protocol_incompatible: [400, 502],
1375
+ internal_error: [500, 503]
1376
+ };
1377
+ return byCode[code] ?? [];
1378
+ }
1379
+ function boundedArray(value, label) {
1380
+ if (!Array.isArray(value) || value.length > 64)
1381
+ throw incompatible(`${label} must be a bounded array`);
1382
+ return structuredClone(value);
1383
+ }
1384
+ function incompatible(message, cause) {
1385
+ return new InfinityError("protocol_incompatible", message, { status: 502, cause });
1386
+ }
1387
+
1388
+ // src/core/ids.ts
1389
+ import { randomBytes } from "crypto";
1390
+
1391
+ class RandomIdFactory {
1392
+ next(prefix) {
1393
+ return `${prefix}-${randomBytes(16).toString("hex")}`;
1394
+ }
1395
+ }
1396
+
1397
+ // src/core/clock.ts
1398
+ class SystemClock {
1399
+ now() {
1400
+ return new Date;
1401
+ }
1402
+ }
1403
+
1404
+ // src/authority/mutation-tuple.ts
1405
+ function submitRunMutationTuple(input) {
1406
+ return {
1407
+ scope: {
1408
+ route_lineage_id: input.routeLineageId,
1409
+ logical_work_key: input.spec.metadata.logical_work_key
1410
+ },
1411
+ request: {
1412
+ run_spec_digest: runSpecDigest(input.spec),
1413
+ route_id: input.routeId,
1414
+ route_epoch: input.routeEpoch
1415
+ }
1416
+ };
1417
+ }
1418
+ function mutationRequestHash(input) {
1419
+ return digestCanonical({
1420
+ command: input.command,
1421
+ scope: input.scope,
1422
+ input: input.request,
1423
+ authority_epoch: input.authorityEpoch,
1424
+ idempotency_key: input.idempotencyKey
1425
+ });
1426
+ }
1427
+
1428
+ // src/cli/operation-journal.ts
1429
+ import { Database } from "bun:sqlite";
1430
+ import { chmodSync, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync } from "fs";
1431
+ import { dirname, join } from "path";
1432
+ import { userInfo } from "os";
1433
+ var CLI_MUTATION_CONSEQUENCE_SCHEMA_VERSION = "infinity.cli-mutation-consequence/v1";
1434
+ function defaultCliOperationJournalPath() {
1435
+ return join(userInfo().homedir, ".local", "state", "infinity", "operator-journal.sqlite");
1436
+ }
1437
+
1438
+ class DurableCliOperationJournal {
1439
+ path;
1440
+ ids;
1441
+ clock;
1442
+ database;
1443
+ constructor(path, ids, clock) {
1444
+ this.path = path;
1445
+ this.ids = ids;
1446
+ this.clock = clock;
1447
+ }
1448
+ async prepare(value) {
1449
+ closedObject(value, "CLI operation intent", [
1450
+ "command",
1451
+ "idempotencyKey",
1452
+ "scope",
1453
+ "request",
1454
+ "authorityRequestHash",
1455
+ "resultExpectation"
1456
+ ]);
1457
+ const command = stringValue(value.command, "CLI operation command", { max: 64, pattern: /^[a-z][a-z0-9.]+$/ });
1458
+ const idempotencyKey = identifier(value.idempotencyKey, "idempotency_key");
1459
+ if (!isPlainObject(value.scope) || !isPlainObject(value.request)) {
1460
+ throw new InfinityError("invalid_input", "CLI operation scope and request must be closed objects");
1461
+ }
1462
+ const scopeDigest = digestCanonical(value.scope);
1463
+ const requestDigest = digestCanonical(value.request);
1464
+ const authorityRequestHash = digest(value.authorityRequestHash, "CLI authority request hash");
1465
+ const resultExpectation = parsePublicMutationResultExpectation(value.resultExpectation);
1466
+ if (resultExpectation.command !== command) {
1467
+ throw new InfinityError("integrity_failure", "CLI result expectation command differs from its mutation command");
1468
+ }
1469
+ const resultExpectationText = canonicalJson(resultExpectation);
1470
+ const resultExpectationDigest = digestCanonical(resultExpectation);
1471
+ const database = this.open();
1472
+ const prepare = database.transaction(() => {
1473
+ const prior = database.query(`
1474
+ SELECT operation_id, request_digest, authority_request_hash, result_expectation, result_expectation_digest
1475
+ FROM prepared_operations
1476
+ WHERE command = ? AND idempotency_key = ? AND scope_digest = ?
1477
+ `).get(command, idempotencyKey, scopeDigest);
1478
+ if (prior) {
1479
+ if (prior.request_digest !== requestDigest) {
1480
+ throw new InfinityError("idempotency_key_reused", "CLI idempotency tuple was reused with another request", { status: 409 });
1481
+ }
1482
+ if (prior.authority_request_hash !== null && prior.authority_request_hash !== authorityRequestHash) {
1483
+ throw new InfinityError("idempotency_key_reused", "CLI idempotency tuple was reused with another authority request", { status: 409 });
1484
+ }
1485
+ if (prior.result_expectation !== null && prior.result_expectation !== resultExpectationText) {
1486
+ throw new InfinityError("idempotency_key_reused", "CLI idempotency tuple was reused with another result expectation", { status: 409 });
1487
+ }
1488
+ if (prior.result_expectation_digest !== null && prior.result_expectation_digest !== resultExpectationDigest) {
1489
+ throw new InfinityError("integrity_failure", "CLI result expectation digest conflicts with its canonical bytes");
1490
+ }
1491
+ if (prior.authority_request_hash === null || prior.result_expectation === null || prior.result_expectation_digest === null) {
1492
+ const recovered = database.query(`
1493
+ UPDATE prepared_operations SET
1494
+ authority_request_hash = COALESCE(authority_request_hash, ?),
1495
+ result_expectation = COALESCE(result_expectation, ?),
1496
+ result_expectation_digest = COALESCE(result_expectation_digest, ?),
1497
+ updated_at = ?
1498
+ WHERE operation_id = ?
1499
+ AND (authority_request_hash IS NULL OR authority_request_hash = ?)
1500
+ AND (result_expectation IS NULL OR result_expectation = ?)
1501
+ AND (result_expectation_digest IS NULL OR result_expectation_digest = ?)
1502
+ `).run(authorityRequestHash, resultExpectationText, resultExpectationDigest, this.clock.now().toISOString(), prior.operation_id, authorityRequestHash, resultExpectationText, resultExpectationDigest);
1503
+ if (recovered.changes !== 1) {
1504
+ throw new InfinityError("integrity_failure", "legacy CLI operation recovery lost its compare-and-swap");
1505
+ }
1506
+ }
1507
+ return {
1508
+ operationId: prior.operation_id,
1509
+ command,
1510
+ idempotencyKey,
1511
+ scopeDigest,
1512
+ requestDigest,
1513
+ authorityRequestHash,
1514
+ resultExpectation,
1515
+ replayed: true
1516
+ };
1517
+ }
1518
+ const operationId = identifier(this.ids.next("operation"), "operation_id");
1519
+ database.query(`
1520
+ INSERT INTO prepared_operations
1521
+ (operation_id, command, idempotency_key, scope_digest, request_digest, authority_request_hash,
1522
+ result_expectation, result_expectation_digest, state, response_digest, created_at, updated_at)
1523
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'prepared', NULL, ?, ?)
1524
+ `).run(operationId, command, idempotencyKey, scopeDigest, requestDigest, authorityRequestHash, resultExpectationText, resultExpectationDigest, this.clock.now().toISOString(), this.clock.now().toISOString());
1525
+ return {
1526
+ operationId,
1527
+ command,
1528
+ idempotencyKey,
1529
+ scopeDigest,
1530
+ requestDigest,
1531
+ authorityRequestHash,
1532
+ resultExpectation,
1533
+ replayed: false
1534
+ };
1535
+ });
1536
+ return prepare.immediate();
1537
+ }
1538
+ async recordResponse(operationIdInput, envelope) {
1539
+ const operationId = identifier(operationIdInput, "operation_id");
1540
+ const database = this.open();
1541
+ const record = database.transaction(() => {
1542
+ const row = database.query(`
1543
+ SELECT command, result_expectation, result_expectation_digest,
1544
+ state, response_digest, response_consequence
1545
+ FROM prepared_operations WHERE operation_id = ?
1546
+ `).get(operationId);
1547
+ if (!row)
1548
+ throw new InfinityError("integrity_failure", "CLI response has no durable pre-dispatch operation");
1549
+ if (envelope.command !== row.command || envelope.operation_id !== operationId) {
1550
+ throw new InfinityError("integrity_failure", "CLI response correlation differs from its durable operation");
1551
+ }
1552
+ if (!envelope.ok) {
1553
+ return;
1554
+ }
1555
+ const resultExpectation = parseStoredResultExpectation(row.command, row.result_expectation, row.result_expectation_digest);
1556
+ const consequence = canonicalMutationConsequence(row.command, operationId, envelope.data, resultExpectation);
1557
+ const consequenceText = canonicalJson(consequence);
1558
+ const responseDigest = digestCanonical(consequence);
1559
+ if (row.state === "responded") {
1560
+ if (row.response_consequence === null) {
1561
+ const legacyDigest = legacySuccessfulResponseDigest(envelope);
1562
+ if (row.response_digest !== legacyDigest) {
1563
+ throw new InfinityError("integrity_failure", "CLI operation received conflicting legacy response bytes");
1564
+ }
1565
+ const recovered = database.query(`
1566
+ UPDATE prepared_operations SET response_digest = ?, response_consequence = ?, updated_at = ?
1567
+ WHERE operation_id = ? AND state = 'responded' AND response_digest = ?
1568
+ AND response_consequence IS NULL
1569
+ `).run(responseDigest, consequenceText, this.clock.now().toISOString(), operationId, legacyDigest);
1570
+ if (recovered.changes !== 1) {
1571
+ throw new InfinityError("integrity_failure", "CLI legacy response recovery lost its compare-and-swap");
1572
+ }
1573
+ } else if (row.response_digest !== responseDigest || row.response_consequence !== consequenceText) {
1574
+ throw new InfinityError("integrity_failure", "CLI operation received conflicting canonical consequence bytes");
1575
+ }
1576
+ return;
1577
+ }
1578
+ const updated = database.query(`
1579
+ UPDATE prepared_operations SET state = 'responded', response_digest = ?,
1580
+ response_consequence = ?, updated_at = ?
1581
+ WHERE operation_id = ? AND state = 'prepared'
1582
+ `).run(responseDigest, consequenceText, this.clock.now().toISOString(), operationId);
1583
+ if (updated.changes !== 1)
1584
+ throw new InfinityError("integrity_failure", "CLI response state compare-and-swap failed");
1585
+ });
1586
+ record.immediate();
1587
+ }
1588
+ read(operationIdInput) {
1589
+ const operationId = identifier(operationIdInput, "operation_id");
1590
+ const row = this.open().query(`
1591
+ SELECT operation_id, command, idempotency_key, scope_digest, request_digest, authority_request_hash,
1592
+ result_expectation, result_expectation_digest, state, response_digest, response_consequence
1593
+ FROM prepared_operations WHERE operation_id = ?
1594
+ `).get(operationId);
1595
+ if (!row)
1596
+ throw new InfinityError("not_found", "CLI operation is not in the local journal", { status: 404 });
1597
+ if (row.authority_request_hash === null || row.result_expectation === null || row.result_expectation_digest === null) {
1598
+ throw new InfinityError("state_conflict", "legacy CLI operation requires an exact mutation-command replay before it can be resolved", { status: 409 });
1599
+ }
1600
+ const authorityRequestHash = digest(row.authority_request_hash, "CLI authority request hash");
1601
+ const resultExpectation = parseStoredResultExpectation(row.command, row.result_expectation, row.result_expectation_digest);
1602
+ if (row.state === "responded") {
1603
+ if (row.response_digest === null || row.response_consequence === null) {
1604
+ throw new InfinityError("state_conflict", "legacy CLI success requires an exact command replay before resolution", {
1605
+ status: 409
1606
+ });
1607
+ }
1608
+ const responseDigest = digest(row.response_digest, "CLI response consequence digest");
1609
+ const storedConsequence = parseStoredMutationConsequence(row.response_consequence, row.command, row.operation_id, resultExpectation);
1610
+ if (digestCanonical(storedConsequence) !== responseDigest) {
1611
+ throw new InfinityError("integrity_failure", "CLI stored response consequence differs from its digest");
1612
+ }
1613
+ } else if (row.response_digest !== null || row.response_consequence !== null) {
1614
+ throw new InfinityError("integrity_failure", "CLI prepared operation carries response-only bytes");
1615
+ }
1616
+ return {
1617
+ operationId: row.operation_id,
1618
+ command: row.command,
1619
+ idempotencyKey: row.idempotency_key,
1620
+ scopeDigest: row.scope_digest,
1621
+ requestDigest: row.request_digest,
1622
+ authorityRequestHash,
1623
+ resultExpectation,
1624
+ replayed: true,
1625
+ state: row.state,
1626
+ responseDigest: row.response_digest
1627
+ };
1628
+ }
1629
+ close() {
1630
+ this.database?.close(false);
1631
+ this.database = undefined;
1632
+ }
1633
+ open() {
1634
+ if (this.database)
1635
+ return this.database;
1636
+ if (this.path !== ":memory:")
1637
+ prepareOwnerOnlyPath(this.path);
1638
+ const created = this.path !== ":memory:" && !existsSync(this.path);
1639
+ const database = new Database(this.path, { create: true, strict: true });
1640
+ database.exec("PRAGMA journal_mode = DELETE; PRAGMA synchronous = FULL; PRAGMA foreign_keys = ON;");
1641
+ database.exec(`
1642
+ CREATE TABLE IF NOT EXISTS prepared_operations (
1643
+ operation_id TEXT PRIMARY KEY,
1644
+ command TEXT NOT NULL,
1645
+ idempotency_key TEXT NOT NULL,
1646
+ scope_digest TEXT NOT NULL,
1647
+ request_digest TEXT NOT NULL,
1648
+ authority_request_hash TEXT NOT NULL,
1649
+ result_expectation TEXT NOT NULL,
1650
+ result_expectation_digest TEXT NOT NULL,
1651
+ state TEXT NOT NULL CHECK (state IN ('prepared','responded')),
1652
+ response_digest TEXT,
1653
+ response_consequence TEXT,
1654
+ created_at TEXT NOT NULL,
1655
+ updated_at TEXT NOT NULL,
1656
+ UNIQUE (command, idempotency_key, scope_digest),
1657
+ CHECK ((state = 'prepared' AND response_digest IS NULL AND response_consequence IS NULL)
1658
+ OR (state = 'responded' AND response_digest IS NOT NULL AND response_consequence IS NOT NULL))
1659
+ );
1660
+ `);
1661
+ const columns = database.query("PRAGMA table_info(prepared_operations)").all();
1662
+ if (!columns.some((column) => column.name === "authority_request_hash")) {
1663
+ database.exec("ALTER TABLE prepared_operations ADD COLUMN authority_request_hash TEXT");
1664
+ }
1665
+ if (!columns.some((column) => column.name === "result_expectation")) {
1666
+ database.exec("ALTER TABLE prepared_operations ADD COLUMN result_expectation TEXT");
1667
+ }
1668
+ if (!columns.some((column) => column.name === "result_expectation_digest")) {
1669
+ database.exec("ALTER TABLE prepared_operations ADD COLUMN result_expectation_digest TEXT");
1670
+ }
1671
+ if (!columns.some((column) => column.name === "response_consequence")) {
1672
+ database.exec("ALTER TABLE prepared_operations ADD COLUMN response_consequence TEXT");
1673
+ }
1674
+ if (this.path !== ":memory:") {
1675
+ chmodSync(this.path, 384);
1676
+ if (created)
1677
+ fsyncDirectory(dirname(this.path));
1678
+ }
1679
+ this.database = database;
1680
+ return database;
1681
+ }
1682
+ }
1683
+ function fsyncDirectory(path) {
1684
+ const descriptor = openSync(path, "r");
1685
+ try {
1686
+ fsyncSync(descriptor);
1687
+ } finally {
1688
+ closeSync(descriptor);
1689
+ }
1690
+ }
1691
+ function successfulMutationConsequenceDigest(command, operationId, value, expectation) {
1692
+ return digestCanonical(canonicalMutationConsequence(command, operationId, value, expectation));
1693
+ }
1694
+ function legacySuccessfulResponseDigest(envelope) {
1695
+ const data = isPlainObject(envelope.data) ? Object.fromEntries(Object.entries(envelope.data).filter(([field]) => field !== "idempotency")) : envelope.data ?? null;
1696
+ return digestCanonical({
1697
+ schema_version: envelope.schema_version,
1698
+ ok: envelope.ok,
1699
+ command: envelope.command,
1700
+ operation_id: envelope.operation_id ?? null,
1701
+ data
1702
+ });
1703
+ }
1704
+ function canonicalMutationConsequence(command, operationIdInput, value, expectationInput) {
1705
+ if (!isPublicMutationCommand(command)) {
1706
+ throw new InfinityError("integrity_failure", "CLI consequence command is not a public mutation command");
1707
+ }
1708
+ const operationId = identifier(operationIdInput, "operation_id");
1709
+ const expectation = parsePublicMutationResultExpectation(expectationInput);
1710
+ if (expectation.command !== command) {
1711
+ throw new InfinityError("integrity_failure", "CLI consequence expectation command differs");
1712
+ }
1713
+ const parsed = parsePublicMutationResult(command, value, operationId, expectation);
1714
+ return {
1715
+ schema_version: CLI_MUTATION_CONSEQUENCE_SCHEMA_VERSION,
1716
+ command,
1717
+ operation_id: operationId,
1718
+ result_expectation_digest: digestCanonical(expectation),
1719
+ result: {
1720
+ ...parsed,
1721
+ idempotency: { replayed: false }
1722
+ }
1723
+ };
1724
+ }
1725
+ function parseStoredResultExpectation(command, expectationText, expectationDigestText) {
1726
+ if (expectationText === null || expectationDigestText === null) {
1727
+ throw new InfinityError("state_conflict", "legacy CLI operation requires an exact command replay", { status: 409 });
1728
+ }
1729
+ const expectationDigest = digest(expectationDigestText, "CLI result expectation digest");
1730
+ let expectation;
1731
+ try {
1732
+ expectation = parsePublicMutationResultExpectation(parseStrictJson(expectationText));
1733
+ } catch (error) {
1734
+ throw new InfinityError("integrity_failure", "CLI result expectation bytes are corrupt", { cause: error });
1735
+ }
1736
+ if (expectation.command !== command || digestCanonical(expectation) !== expectationDigest || canonicalJson(expectation) !== expectationText) {
1737
+ throw new InfinityError("integrity_failure", "CLI result expectation differs from its protected digest or command");
1738
+ }
1739
+ return expectation;
1740
+ }
1741
+ function parseStoredMutationConsequence(consequenceText, expectedCommand, expectedOperationId, expectation) {
1742
+ let stored;
1743
+ try {
1744
+ stored = closedObject(parseStrictJson(consequenceText), "CLI mutation consequence", [
1745
+ "schema_version",
1746
+ "command",
1747
+ "operation_id",
1748
+ "result_expectation_digest",
1749
+ "result"
1750
+ ]);
1751
+ } catch (error) {
1752
+ throw new InfinityError("integrity_failure", "CLI stored mutation consequence bytes are corrupt", { cause: error });
1753
+ }
1754
+ if (stored.schema_version !== CLI_MUTATION_CONSEQUENCE_SCHEMA_VERSION || stored.command !== expectedCommand || stored.operation_id !== expectedOperationId || stored.result_expectation_digest !== digestCanonical(expectation)) {
1755
+ throw new InfinityError("integrity_failure", "CLI stored mutation consequence binding differs");
1756
+ }
1757
+ const canonical = canonicalMutationConsequence(expectedCommand, expectedOperationId, stored.result, expectation);
1758
+ if (canonicalJson(canonical) !== consequenceText) {
1759
+ throw new InfinityError("integrity_failure", "CLI stored mutation consequence is not canonical or complete");
1760
+ }
1761
+ return canonical;
1762
+ }
1763
+ function prepareOwnerOnlyPath(path) {
1764
+ const directory = dirname(path);
1765
+ mkdirSync(directory, { recursive: true, mode: 448 });
1766
+ const directoryStat = lstatSync(directory);
1767
+ if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink()) {
1768
+ throw new InfinityError("integrity_failure", "CLI journal directory is not a real directory");
1769
+ }
1770
+ if (typeof process.getuid === "function" && directoryStat.uid !== process.getuid()) {
1771
+ throw new InfinityError("capability_denied", "CLI journal directory is not owned by the current user", { status: 403 });
1772
+ }
1773
+ chmodSync(directory, 448);
1774
+ try {
1775
+ const fileStat = lstatSync(path);
1776
+ if (!fileStat.isFile() || fileStat.isSymbolicLink()) {
1777
+ throw new InfinityError("integrity_failure", "CLI journal path is not a regular file");
1778
+ }
1779
+ if (typeof process.getuid === "function" && fileStat.uid !== process.getuid()) {
1780
+ throw new InfinityError("capability_denied", "CLI journal is not owned by the current user", { status: 403 });
1781
+ }
1782
+ chmodSync(path, 384);
1783
+ } catch (error) {
1784
+ if (error instanceof InfinityError)
1785
+ throw error;
1786
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT")
1787
+ throw error;
1788
+ }
1789
+ }
1790
+
1791
+ // src/authcapsules/codewith-local.ts
1792
+ import { createHash as createHash2 } from "crypto";
1793
+ import { lstat, readdir, readFile, realpath } from "fs/promises";
1794
+ import { isAbsolute, join as join2, relative, sep } from "path";
1795
+
1796
+ // src/authcapsules/infinity-agent-policy.ts
1797
+ import { posix } from "path";
1798
+ var INFINITY_AGENT_POLICY_SCHEMA_VERSION = "infinity.codewith-agent-policy.v1";
1799
+ var CAPSULE_REMOTE_CAPABILITIES = [
1800
+ "sandbox.checkpoint.request",
1801
+ "sandbox.exec",
1802
+ "sandbox.file.read",
1803
+ "sandbox.file.write"
1804
+ ];
1805
+ var POLICY_FIELDS = [
1806
+ "schema_version",
1807
+ "profile",
1808
+ "enforcement",
1809
+ "environment_inherit",
1810
+ "history_persistence",
1811
+ "ephemeral",
1812
+ "host_filesystem_access",
1813
+ "host_shell_access",
1814
+ "direct_network_access",
1815
+ "auth_profile_control",
1816
+ "allowed_capabilities"
1817
+ ];
1818
+ function parseInfinityAgentPolicy(value) {
1819
+ const input = closedObject(value, "infinity-agent policy", POLICY_FIELDS);
1820
+ const requireBoolean = (field, expected) => {
1821
+ if (input[field] !== expected) {
1822
+ const words = field.replaceAll("_", " ");
1823
+ throw new InfinityError("capability_denied", `infinity-agent policy ${words} must be ${String(expected)}`, { status: 403 });
1824
+ }
1825
+ return expected;
1826
+ };
1827
+ const allowed = stringArray(input.allowed_capabilities, "policy.allowed_capabilities", {
1828
+ maxItems: CAPSULE_REMOTE_CAPABILITIES.length,
1829
+ item: (entry, label) => enumValue(entry, label, CAPSULE_REMOTE_CAPABILITIES)
1830
+ });
1831
+ const sorted = [...allowed].sort();
1832
+ if (allowed.some((entry, index) => entry !== sorted[index])) {
1833
+ throw new InfinityError("invalid_input", "policy allowed capabilities must use canonical sorted order");
1834
+ }
1835
+ return deepFreeze({
1836
+ schema_version: enumValue(input.schema_version, "policy.schema_version", [INFINITY_AGENT_POLICY_SCHEMA_VERSION]),
1837
+ profile: enumValue(input.profile, "policy.profile", ["infinity-agent"]),
1838
+ enforcement: enumValue(input.enforcement, "policy.enforcement", ["codewith-native-v1"]),
1839
+ environment_inherit: enumValue(input.environment_inherit, "policy.environment_inherit", ["none"]),
1840
+ history_persistence: enumValue(input.history_persistence, "policy.history_persistence", ["none"]),
1841
+ ephemeral: requireBoolean("ephemeral", true),
1842
+ host_filesystem_access: requireBoolean("host_filesystem_access", false),
1843
+ host_shell_access: requireBoolean("host_shell_access", false),
1844
+ direct_network_access: requireBoolean("direct_network_access", false),
1845
+ auth_profile_control: requireBoolean("auth_profile_control", false),
1846
+ allowed_capabilities: allowed
1847
+ });
1848
+ }
1849
+ function infinityAgentPolicyDigest(value) {
1850
+ return digestCanonical(parseInfinityAgentPolicy(value));
1851
+ }
1852
+
1853
+ class ProtectedCapsuleRemoteToolBridge {
1854
+ #authority;
1855
+ #backend;
1856
+ constructor(dependencies) {
1857
+ this.#authority = dependencies.authority;
1858
+ this.#backend = dependencies.backend;
1859
+ }
1860
+ async open(input) {
1861
+ const policy = parseInfinityAgentPolicy(input.policy);
1862
+ if (input.descriptor.infinity_agent_policy_sha256 !== infinityAgentPolicyDigest(policy)) {
1863
+ throw new InfinityError("capability_denied", "infinity-agent policy measurement does not match the AuthCapsule descriptor", { status: 403 });
1864
+ }
1865
+ if (input.descriptor.owner_ref !== input.binding.fence.actor_principal) {
1866
+ throw new InfinityError("capability_denied", "AuthCapsule owner does not match the remote-tool actor", { status: 403 });
1867
+ }
1868
+ await this.#authority.assertCurrent({ ...input, policy });
1869
+ let closed = false;
1870
+ const invokedIds = new Set;
1871
+ return {
1872
+ invoke: async (call) => {
1873
+ if (closed)
1874
+ throw new InfinityError("state_conflict", "capsule remote-tool bridge session is closed", { status: 409 });
1875
+ const parsed = parseRemoteToolCall(call, policy);
1876
+ if (invokedIds.has(parsed.request_id)) {
1877
+ throw new InfinityError("state_conflict", "capsule remote-tool request id was already used", { status: 409 });
1878
+ }
1879
+ invokedIds.add(parsed.request_id);
1880
+ await this.#authority.assertCurrent({
1881
+ descriptor: input.descriptor,
1882
+ binding: input.binding,
1883
+ policy,
1884
+ capability: parsed.capability
1885
+ });
1886
+ return this.#backend.invoke({
1887
+ descriptor: input.descriptor,
1888
+ binding: input.binding,
1889
+ capability: parsed.capability,
1890
+ request_id: parsed.request_id,
1891
+ input: parsed.input
1892
+ });
1893
+ },
1894
+ close: async () => {
1895
+ closed = true;
1896
+ }
1897
+ };
1898
+ }
1899
+ }
1900
+ function parseRemoteToolCall(value, policy) {
1901
+ const call = closedObject(value, "capsule remote-tool call", ["request_id", "capability", "input"]);
1902
+ const capability = enumValue(call.capability, "call.capability", CAPSULE_REMOTE_CAPABILITIES);
1903
+ if (!policy.allowed_capabilities.includes(capability)) {
1904
+ throw new InfinityError("capability_denied", "capsule remote-tool capability is not present in the measured allowlist", { status: 403 });
1905
+ }
1906
+ const requestId = identifier(call.request_id, "call.request_id");
1907
+ return deepFreeze({
1908
+ request_id: requestId,
1909
+ capability,
1910
+ input: parseCapabilityInput(capability, call.input)
1911
+ });
1912
+ }
1913
+ function parseCapabilityInput(capability, value) {
1914
+ if (capability === "sandbox.file.read") {
1915
+ const input2 = closedObject(value, capability, ["path", "max_bytes"]);
1916
+ return deepFreeze({
1917
+ path: relativeSandboxPath(input2.path, "read path"),
1918
+ max_bytes: positiveInteger(input2.max_bytes, "read max_bytes", 16 * 1024 * 1024)
1919
+ });
1920
+ }
1921
+ if (capability === "sandbox.file.write") {
1922
+ const input2 = closedObject(value, capability, ["path", "content_utf8"]);
1923
+ const content = stringValue(input2.content_utf8, "write content_utf8", { max: 16 * 1024 * 1024 });
1924
+ if (new TextEncoder().encode(content).byteLength > 16 * 1024 * 1024) {
1925
+ throw new InfinityError("invalid_input", "write content exceeds the bridge byte limit");
1926
+ }
1927
+ return deepFreeze({ path: relativeSandboxPath(input2.path, "write path"), content_utf8: content });
1928
+ }
1929
+ if (capability === "sandbox.exec") {
1930
+ const input2 = closedObject(value, capability, ["argv", "cwd", "timeout_ms"]);
1931
+ const argv = stringArray(input2.argv, "exec argv", {
1932
+ maxItems: 128,
1933
+ item: (entry, label) => stringValue(entry, label, { max: 4096 })
1934
+ });
1935
+ return deepFreeze({
1936
+ argv,
1937
+ cwd: relativeSandboxPath(input2.cwd, "exec cwd", true),
1938
+ timeout_ms: positiveInteger(input2.timeout_ms, "exec timeout_ms", 300000)
1939
+ });
1940
+ }
1941
+ const input = closedObject(value, capability, ["reason"]);
1942
+ return deepFreeze({ reason: stringValue(input.reason, "checkpoint reason", { max: 512 }) });
1943
+ }
1944
+ function relativeSandboxPath(value, label, allowDot = false) {
1945
+ const parsed = stringValue(value, label, { max: 4096 });
1946
+ if (parsed.includes("\\") || parsed.startsWith("/") || parsed.includes("\x00")) {
1947
+ throw new InfinityError("capability_denied", `${label} must be a portable relative sandbox path`, { status: 403 });
1948
+ }
1949
+ const normalized = posix.normalize(parsed);
1950
+ if (normalized === ".." || normalized.startsWith("../") || normalized.startsWith("/")) {
1951
+ throw new InfinityError("capability_denied", `${label} escapes the sandbox workspace`, { status: 403 });
1952
+ }
1953
+ if (!allowDot && normalized === "." || normalized.length === 0) {
1954
+ throw new InfinityError("invalid_input", `${label} must identify a sandbox path`);
1955
+ }
1956
+ return normalized;
1957
+ }
1958
+
1959
+ // src/contracts/fence.ts
1960
+ var BROKER_FENCE_FIELDS = [
1961
+ "authority_epoch",
1962
+ "route_lineage_id",
1963
+ "route_id",
1964
+ "route_epoch",
1965
+ "run_id",
1966
+ "attempt_id",
1967
+ "attempt_lease_id",
1968
+ "lease_epoch",
1969
+ "lease_holder_principal",
1970
+ "resource_lease_id",
1971
+ "resource_id",
1972
+ "resource_lifecycle_generation",
1973
+ "operation_id",
1974
+ "operation_digest",
1975
+ "operation_execution_epoch",
1976
+ "actor_principal",
1977
+ "operation_executor_principal",
1978
+ "audience",
1979
+ "issued_at",
1980
+ "lease_expires_at",
1981
+ "operation_execution_expires_at"
1982
+ ];
1983
+ var BROKER_FENCE_SCHEMA_VERSION = "infinity.broker-fence.v1";
1984
+ var BROKER_FENCE_WIRE_FIELDS = ["schema_version", ...BROKER_FENCE_FIELDS];
1985
+ var REJECTED_FENCE_ALIASES = [
1986
+ "authority_generation",
1987
+ "authority_incarnation",
1988
+ "route_authority_epoch",
1989
+ "producer_epoch",
1990
+ "attempt_lease_epoch",
1991
+ "cancellation_generation",
1992
+ "allocation_generation",
1993
+ "lifecycle_revision"
1994
+ ];
1995
+ function parseBrokerFence(value) {
1996
+ if (value && typeof value === "object") {
1997
+ for (const alias of REJECTED_FENCE_ALIASES) {
1998
+ if (Object.hasOwn(value, alias))
1999
+ throw new InfinityError("invalid_input", `broker fence alias ${alias} is rejected`);
2000
+ }
2001
+ }
2002
+ const input = closedObject(value, "broker_fence", BROKER_FENCE_WIRE_FIELDS);
2003
+ const parsed = {
2004
+ schema_version: enumValue(input.schema_version, "schema_version", [BROKER_FENCE_SCHEMA_VERSION]),
2005
+ authority_epoch: positiveInt64(input.authority_epoch, "authority_epoch"),
2006
+ route_lineage_id: identifier(input.route_lineage_id, "route_lineage_id"),
2007
+ route_id: identifier(input.route_id, "route_id"),
2008
+ route_epoch: positiveInt64(input.route_epoch, "route_epoch"),
2009
+ run_id: identifier(input.run_id, "run_id"),
2010
+ attempt_id: identifier(input.attempt_id, "attempt_id"),
2011
+ attempt_lease_id: identifier(input.attempt_lease_id, "attempt_lease_id"),
2012
+ lease_epoch: positiveInt64(input.lease_epoch, "lease_epoch"),
2013
+ lease_holder_principal: identifier(input.lease_holder_principal, "lease_holder_principal"),
2014
+ resource_lease_id: identifier(input.resource_lease_id, "resource_lease_id"),
2015
+ resource_id: identifier(input.resource_id, "resource_id"),
2016
+ resource_lifecycle_generation: positiveInt64(input.resource_lifecycle_generation, "resource_lifecycle_generation"),
2017
+ operation_id: identifier(input.operation_id, "operation_id"),
2018
+ operation_digest: digest(input.operation_digest, "operation_digest"),
2019
+ operation_execution_epoch: positiveInt64(input.operation_execution_epoch, "operation_execution_epoch"),
2020
+ actor_principal: identifier(input.actor_principal, "actor_principal"),
2021
+ operation_executor_principal: identifier(input.operation_executor_principal, "operation_executor_principal"),
2022
+ audience: identifier(input.audience, "audience"),
2023
+ issued_at: timestamp(input.issued_at, "issued_at"),
2024
+ lease_expires_at: timestamp(input.lease_expires_at, "lease_expires_at"),
2025
+ operation_execution_expires_at: timestamp(input.operation_execution_expires_at, "operation_execution_expires_at")
2026
+ };
2027
+ const issued = Date.parse(parsed.issued_at);
2028
+ const leaseExpiry = Date.parse(parsed.lease_expires_at);
2029
+ const executionExpiry = Date.parse(parsed.operation_execution_expires_at);
2030
+ if (!(issued < executionExpiry && executionExpiry <= leaseExpiry)) {
2031
+ throw new InfinityError("invalid_input", "broker fence expiry window is invalid");
2032
+ }
2033
+ return Object.freeze(parsed);
2034
+ }
2035
+
2036
+ // src/authcapsules/codewith-local.ts
2037
+ var AUTH_CAPSULE_DESCRIPTOR_SCHEMA_VERSION = "infinity.auth-capsule-descriptor.v2";
2038
+ var CAPSULE_REMOTE_TOOL_BINDING_SCHEMA_VERSION = "infinity.capsule-remote-tool-binding.v1";
2039
+ var DESCRIPTOR_FIELDS = [
2040
+ "schema_version",
2041
+ "auth_capsule_id",
2042
+ "owner_ref",
2043
+ "provider_key",
2044
+ "provider_subject_ref",
2045
+ "capacity_domain_ref",
2046
+ "account_lane_id",
2047
+ "canonical_node_id",
2048
+ "node_key_thumbprint",
2049
+ "node_generation",
2050
+ "placement_generation",
2051
+ "auth_generation",
2052
+ "auth_state_revision",
2053
+ "accounts_revision_set_digest",
2054
+ "capsule_attestation_digest",
2055
+ "local_profile_ref",
2056
+ "codewith_binary_sha256",
2057
+ "runtime_policy_sha256",
2058
+ "infinity_agent_policy_sha256"
2059
+ ];
2060
+ var BINDING_FIELDS = [
2061
+ "schema_version",
2062
+ "dispatch_id",
2063
+ "canonical_intent_sha256",
2064
+ "sandbox_prepare_anchor_sha256",
2065
+ "authority_envelope_sha256",
2066
+ "effect_claim_sha256",
2067
+ "operation_digest",
2068
+ "provider",
2069
+ "source_manifest_sha256",
2070
+ "input_manifest_sha256",
2071
+ "checkpoint_policy_sha256",
2072
+ "fence"
2073
+ ];
2074
+ var FORBIDDEN_CREDENTIAL_FIELD = /(?:^|_)(?:access|refresh|session)?_?(?:token|secret|password|cookie|api_key|credential|auth_json)(?:$|_)/i;
2075
+ var MAX_PROMPT_BYTES = 256 * 1024;
2076
+ var MAX_PROCESS_OUTPUT_BYTES = 16 * 1024 * 1024;
2077
+ function parseAuthCapsuleDescriptor(value) {
2078
+ rejectCredentialFields(value, "auth capsule descriptor");
2079
+ const input = closedObject(value, "auth capsule descriptor", DESCRIPTOR_FIELDS);
2080
+ return deepFreeze({
2081
+ schema_version: enumValue(input.schema_version, "descriptor.schema_version", [AUTH_CAPSULE_DESCRIPTOR_SCHEMA_VERSION]),
2082
+ auth_capsule_id: identifier(input.auth_capsule_id, "descriptor.auth_capsule_id"),
2083
+ owner_ref: identifier(input.owner_ref, "descriptor.owner_ref"),
2084
+ provider_key: identifier(input.provider_key, "descriptor.provider_key"),
2085
+ provider_subject_ref: identifier(input.provider_subject_ref, "descriptor.provider_subject_ref"),
2086
+ capacity_domain_ref: identifier(input.capacity_domain_ref, "descriptor.capacity_domain_ref"),
2087
+ account_lane_id: identifier(input.account_lane_id, "descriptor.account_lane_id"),
2088
+ canonical_node_id: identifier(input.canonical_node_id, "descriptor.canonical_node_id"),
2089
+ node_key_thumbprint: digest(input.node_key_thumbprint, "descriptor.node_key_thumbprint"),
2090
+ node_generation: positiveCounter(input.node_generation, "descriptor.node_generation"),
2091
+ placement_generation: positiveCounter(input.placement_generation, "descriptor.placement_generation"),
2092
+ auth_generation: positiveCounter(input.auth_generation, "descriptor.auth_generation"),
2093
+ auth_state_revision: positiveCounter(input.auth_state_revision, "descriptor.auth_state_revision"),
2094
+ accounts_revision_set_digest: digest(input.accounts_revision_set_digest, "descriptor.accounts_revision_set_digest"),
2095
+ capsule_attestation_digest: digest(input.capsule_attestation_digest, "descriptor.capsule_attestation_digest"),
2096
+ local_profile_ref: identifier(input.local_profile_ref, "descriptor.local_profile_ref"),
2097
+ codewith_binary_sha256: digest(input.codewith_binary_sha256, "descriptor.codewith_binary_sha256"),
2098
+ runtime_policy_sha256: digest(input.runtime_policy_sha256, "descriptor.runtime_policy_sha256"),
2099
+ infinity_agent_policy_sha256: digest(input.infinity_agent_policy_sha256, "descriptor.infinity_agent_policy_sha256")
2100
+ });
2101
+ }
2102
+ function parseCapsuleRemoteToolBinding(value) {
2103
+ rejectCredentialFields(value, "capsule remote-tool binding");
2104
+ const input = closedObject(value, "capsule remote-tool binding", BINDING_FIELDS);
2105
+ const fence = parseBrokerFence(input.fence);
2106
+ const parsed = deepFreeze({
2107
+ schema_version: enumValue(input.schema_version, "binding.schema_version", [CAPSULE_REMOTE_TOOL_BINDING_SCHEMA_VERSION]),
2108
+ dispatch_id: identifier(input.dispatch_id, "binding.dispatch_id"),
2109
+ canonical_intent_sha256: digest(input.canonical_intent_sha256, "binding.canonical_intent_sha256"),
2110
+ sandbox_prepare_anchor_sha256: digest(input.sandbox_prepare_anchor_sha256, "binding.sandbox_prepare_anchor_sha256"),
2111
+ authority_envelope_sha256: digest(input.authority_envelope_sha256, "binding.authority_envelope_sha256"),
2112
+ effect_claim_sha256: digest(input.effect_claim_sha256, "binding.effect_claim_sha256"),
2113
+ operation_digest: digest(input.operation_digest, "binding.operation_digest"),
2114
+ provider: enumValue(input.provider, "binding.provider", ["e2b", "daytona"]),
2115
+ source_manifest_sha256: digest(input.source_manifest_sha256, "binding.source_manifest_sha256"),
2116
+ input_manifest_sha256: digest(input.input_manifest_sha256, "binding.input_manifest_sha256"),
2117
+ checkpoint_policy_sha256: digest(input.checkpoint_policy_sha256, "binding.checkpoint_policy_sha256"),
2118
+ fence
2119
+ });
2120
+ if (parsed.operation_digest !== parsed.fence.operation_digest) {
2121
+ throw new InfinityError("capability_denied", "remote-tool operation digest does not match the full broker fence", { status: 403 });
2122
+ }
2123
+ if (parsed.fence.audience !== "capsule-remote-tool") {
2124
+ throw new InfinityError("capability_denied", "remote-tool fence has the wrong audience", { status: 403 });
2125
+ }
2126
+ return parsed;
2127
+ }
2128
+
2129
+ class LocalCodewithAuthCapsuleLauncher {
2130
+ #registry;
2131
+ #authority;
2132
+ #bridge;
2133
+ constructor(dependencies) {
2134
+ this.#registry = dependencies.registry;
2135
+ this.#authority = dependencies.authority;
2136
+ this.#bridge = dependencies.bridge;
2137
+ }
2138
+ async launch(request) {
2139
+ const descriptor = parseAuthCapsuleDescriptor(request.descriptor);
2140
+ const binding = parseCapsuleRemoteToolBinding(request.binding);
2141
+ const prompt = parsePrompt(request.prompt);
2142
+ if (descriptor.owner_ref !== binding.fence.actor_principal) {
2143
+ throw new InfinityError("capability_denied", "AuthCapsule owner does not match the run actor", { status: 403 });
2144
+ }
2145
+ if (binding.fence.lease_holder_principal !== binding.fence.operation_executor_principal) {
2146
+ throw new InfinityError("capability_denied", "capsule host must hold both the attempt lease and operation execution fence", { status: 403 });
2147
+ }
2148
+ const profile = await this.#registry.resolve(descriptor);
2149
+ let policy;
2150
+ try {
2151
+ policy = await assertTrustedLocalProfile(profile, descriptor);
2152
+ } catch (error) {
2153
+ if (error instanceof InfinityError)
2154
+ throw error;
2155
+ throw untrustedProfile("local profile path or attested artifact is unavailable");
2156
+ }
2157
+ await probeNativeInfinityAgentPolicy(profile);
2158
+ await this.#authority.assertCurrent({ descriptor, binding });
2159
+ const bridgeSession = await this.#bridge.open({ descriptor, binding, policy });
2160
+ try {
2161
+ const argv = [
2162
+ profile.executable_path,
2163
+ "exec",
2164
+ "--auth-profile",
2165
+ profile.auth_profile_name,
2166
+ "--profile",
2167
+ profile.runtime_profile_name,
2168
+ "--strict-config",
2169
+ "-a",
2170
+ "never",
2171
+ "-c",
2172
+ 'tools.policy="infinity-agent"',
2173
+ "--sandbox",
2174
+ "read-only",
2175
+ "--ignore-user-config",
2176
+ "--ignore-rules",
2177
+ "--disable",
2178
+ "hooks",
2179
+ "--disable",
2180
+ "multi_agent",
2181
+ "--disable",
2182
+ "scheduled_tasks",
2183
+ "--disable",
2184
+ "apps",
2185
+ "--disable",
2186
+ "browser_use",
2187
+ "--disable",
2188
+ "browser_use_external",
2189
+ "--disable",
2190
+ "computer_use",
2191
+ "--disable",
2192
+ "image_generation",
2193
+ "--disable",
2194
+ "memories",
2195
+ "--disable",
2196
+ "mailbox_dispatcher",
2197
+ "--disable",
2198
+ "workflows",
2199
+ "--disable",
2200
+ "shell_snapshot",
2201
+ "--ephemeral",
2202
+ "--json",
2203
+ "--skip-git-repo-check",
2204
+ "-C",
2205
+ profile.empty_workspace_path,
2206
+ "-"
2207
+ ];
2208
+ const subprocess = Bun.spawn(argv, {
2209
+ cwd: profile.empty_workspace_path,
2210
+ env: closedCodewithEnvironment(profile.codewith_home),
2211
+ stdin: "pipe",
2212
+ stdout: "pipe",
2213
+ stderr: "pipe"
2214
+ });
2215
+ subprocess.stdin.write(`${prompt}
2216
+ `);
2217
+ subprocess.stdin.end();
2218
+ const [exitCode, stdout, stderr] = await Promise.all([
2219
+ subprocess.exited,
2220
+ readBoundedText(subprocess.stdout, "Codewith stdout"),
2221
+ readBoundedText(subprocess.stderr, "Codewith stderr")
2222
+ ]);
2223
+ return deepFreeze({
2224
+ schema_version: "infinity.codewith-auth-capsule-result.v1",
2225
+ exit_code: exitCode,
2226
+ stdout,
2227
+ stderr,
2228
+ descriptor_sha256: digestCanonical(descriptor),
2229
+ binding_sha256: digestCanonical(binding)
2230
+ });
2231
+ } finally {
2232
+ await bridgeSession.close();
2233
+ }
2234
+ }
2235
+ }
2236
+ function rejectCredentialFields(value, label) {
2237
+ if (!value || typeof value !== "object" || Array.isArray(value))
2238
+ return;
2239
+ for (const key of Object.keys(value)) {
2240
+ if (FORBIDDEN_CREDENTIAL_FIELD.test(key)) {
2241
+ throw new InfinityError("invalid_input", `${label} contains credential material or a credential carrier field`);
2242
+ }
2243
+ }
2244
+ }
2245
+ function positiveCounter(value, label) {
2246
+ const parsed = stringValue(value, label, { max: 20, pattern: /^[1-9][0-9]*$/ });
2247
+ if (BigInt(parsed) > 9223372036854775807n) {
2248
+ throw new InfinityError("invalid_input", `${label} exceeds signed int64`);
2249
+ }
2250
+ return parsed;
2251
+ }
2252
+ function parsePrompt(value) {
2253
+ const parsed = stringValue(value, "Codewith prompt", { max: MAX_PROMPT_BYTES });
2254
+ if (parsed.includes("\x00"))
2255
+ throw new InfinityError("invalid_input", "Codewith prompt must not contain NUL");
2256
+ if (new TextEncoder().encode(parsed).byteLength > MAX_PROMPT_BYTES) {
2257
+ throw new InfinityError("invalid_input", "Codewith prompt is too large");
2258
+ }
2259
+ return parsed;
2260
+ }
2261
+ async function assertTrustedLocalProfile(profile, descriptor) {
2262
+ const paths = [profile.executable_path, profile.codewith_home, profile.empty_workspace_path, profile.infinity_agent_policy_path];
2263
+ if (!paths.every(isAbsolute))
2264
+ throw new InfinityError("capability_denied", "trusted local profile paths must be absolute", { status: 403 });
2265
+ identifier(profile.auth_profile_name, "Codewith auth profile name");
2266
+ if (profile.runtime_profile_name !== "infinity-agent") {
2267
+ throw new InfinityError("capability_denied", "Codewith runtime profile must be infinity-agent", { status: 403 });
2268
+ }
2269
+ const executableStat = await lstat(profile.executable_path);
2270
+ const homeStat = await lstat(profile.codewith_home);
2271
+ const workspaceStat = await lstat(profile.empty_workspace_path);
2272
+ const agentPolicyStat = await lstat(profile.infinity_agent_policy_path);
2273
+ if (!executableStat.isFile() || executableStat.isSymbolicLink())
2274
+ throw untrustedProfile("Codewith executable");
2275
+ if (!homeStat.isDirectory() || homeStat.isSymbolicLink())
2276
+ throw untrustedProfile("Codewith home");
2277
+ if (!workspaceStat.isDirectory() || workspaceStat.isSymbolicLink())
2278
+ throw untrustedProfile("empty workspace");
2279
+ if (!agentPolicyStat.isFile() || agentPolicyStat.isSymbolicLink() || agentPolicyStat.size > 64 * 1024) {
2280
+ throw untrustedProfile("infinity-agent policy");
2281
+ }
2282
+ if ((await readdir(profile.empty_workspace_path)).length !== 0) {
2283
+ throw untrustedProfile("local Codewith workspace is not empty");
2284
+ }
2285
+ const [realHome, realWorkspace, realAgentPolicy] = await Promise.all([
2286
+ realpath(profile.codewith_home),
2287
+ realpath(profile.empty_workspace_path),
2288
+ realpath(profile.infinity_agent_policy_path)
2289
+ ]);
2290
+ if (containsPath(realHome, realWorkspace) || containsPath(realWorkspace, realHome)) {
2291
+ throw untrustedProfile("Codewith credential home and empty workspace overlap");
2292
+ }
2293
+ if (!containsPath(realHome, realAgentPolicy))
2294
+ throw untrustedProfile("infinity-agent policy escapes Codewith home");
2295
+ const policyPath = join2(realHome, `${profile.runtime_profile_name}.config.toml`);
2296
+ const authProfilePath = join2(realHome, "auth_profiles", profile.auth_profile_name);
2297
+ const [policyStat, authProfileStat] = await Promise.all([lstat(policyPath), lstat(authProfilePath)]);
2298
+ if (!policyStat.isFile() || policyStat.isSymbolicLink())
2299
+ throw untrustedProfile("runtime policy");
2300
+ if (!authProfileStat.isDirectory() || authProfileStat.isSymbolicLink())
2301
+ throw untrustedProfile("auth profile");
2302
+ const realAuthProfile = await realpath(authProfilePath);
2303
+ if (!containsPath(realHome, realAuthProfile))
2304
+ throw untrustedProfile("auth profile escapes Codewith home");
2305
+ const [binaryDigest, policyDigest] = await Promise.all([fileDigest(profile.executable_path), fileDigest(policyPath)]);
2306
+ if (binaryDigest !== descriptor.codewith_binary_sha256 || policyDigest !== descriptor.runtime_policy_sha256) {
2307
+ throw untrustedProfile("Codewith binary or infinity-agent policy attestation digest mismatch");
2308
+ }
2309
+ if (profile.codewith_binary_sha256 !== undefined && profile.codewith_binary_sha256 !== binaryDigest) {
2310
+ throw untrustedProfile("registry Codewith binary attestation digest mismatch");
2311
+ }
2312
+ if (profile.runtime_policy_sha256 !== undefined && profile.runtime_policy_sha256 !== policyDigest) {
2313
+ throw untrustedProfile("registry runtime policy attestation digest mismatch");
2314
+ }
2315
+ const policyText = await readFile(realAgentPolicy, "utf8");
2316
+ const agentPolicy = parseInfinityAgentPolicy(parseStrictJson(policyText));
2317
+ if (canonicalJson(agentPolicy) !== policyText)
2318
+ throw untrustedProfile("infinity-agent policy is not canonical JSON");
2319
+ const agentPolicyDigest = infinityAgentPolicyDigest(agentPolicy);
2320
+ if (agentPolicyDigest !== descriptor.infinity_agent_policy_sha256) {
2321
+ throw untrustedProfile("infinity-agent policy attestation digest mismatch");
2322
+ }
2323
+ if (profile.infinity_agent_policy_sha256 !== undefined && profile.infinity_agent_policy_sha256 !== agentPolicyDigest) {
2324
+ throw untrustedProfile("registry infinity-agent policy attestation digest mismatch");
2325
+ }
2326
+ return agentPolicy;
2327
+ }
2328
+ async function probeNativeInfinityAgentPolicy(profile) {
2329
+ const subprocess = Bun.spawn([
2330
+ profile.executable_path,
2331
+ "debug",
2332
+ "auth-capsule-policy",
2333
+ "--format",
2334
+ "json"
2335
+ ], {
2336
+ cwd: profile.empty_workspace_path,
2337
+ env: closedCodewithEnvironment(profile.codewith_home),
2338
+ stdin: "ignore",
2339
+ stdout: "pipe",
2340
+ stderr: "pipe"
2341
+ });
2342
+ const [exitCode, stdout] = await Promise.all([
2343
+ subprocess.exited,
2344
+ readBoundedText(subprocess.stdout, "Codewith capability probe stdout"),
2345
+ readBoundedText(subprocess.stderr, "Codewith capability probe stderr")
2346
+ ]);
2347
+ if (exitCode !== 0)
2348
+ throw unsupportedNativePolicy();
2349
+ let document;
2350
+ try {
2351
+ document = parseStrictJson(stdout.trim());
2352
+ const input = closedObject(document, "Codewith AuthCapsule capability probe", [
2353
+ "schema_version",
2354
+ "native_policy_enforcement",
2355
+ "host_filesystem_tools",
2356
+ "host_shell_tools",
2357
+ "auth_profile_control",
2358
+ "protected_remote_tool_bridge"
2359
+ ]);
2360
+ if (input.schema_version !== "codewith.auth-capsule-policy-capabilities/v1" || input.native_policy_enforcement !== true || input.host_filesystem_tools !== false || input.host_shell_tools !== false || input.auth_profile_control !== false || input.protected_remote_tool_bridge !== true) {
2361
+ throw unsupportedNativePolicy();
2362
+ }
2363
+ } catch (error) {
2364
+ if (error instanceof InfinityError && error.message.includes("native infinity-agent"))
2365
+ throw error;
2366
+ throw unsupportedNativePolicy();
2367
+ }
2368
+ }
2369
+ function unsupportedNativePolicy() {
2370
+ return new InfinityError("capability_denied", "Codewith capability probe did not prove native infinity-agent enforcement; subscription launch refused", { status: 403 });
2371
+ }
2372
+ function containsPath(parent, candidate) {
2373
+ const path = relative(parent, candidate);
2374
+ return path === "" || !path.startsWith(`..${sep}`) && path !== ".." && !isAbsolute(path);
2375
+ }
2376
+ async function fileDigest(path) {
2377
+ return `sha256:${createHash2("sha256").update(await readFile(path)).digest("hex")}`;
2378
+ }
2379
+ function untrustedProfile(reason) {
2380
+ return new InfinityError("capability_denied", `trusted local profile attestation failed: ${reason}`, { status: 403 });
2381
+ }
2382
+ function closedCodewithEnvironment(codewithHome) {
2383
+ return {
2384
+ CODEWITH_HOME: codewithHome,
2385
+ HOME: codewithHome,
2386
+ LANG: "C.UTF-8",
2387
+ LC_ALL: "C.UTF-8",
2388
+ NO_COLOR: "1",
2389
+ PATH: "/usr/bin:/bin"
2390
+ };
2391
+ }
2392
+ async function readBoundedText(stream, label) {
2393
+ const reader = stream.getReader();
2394
+ const chunks = [];
2395
+ let size = 0;
2396
+ while (true) {
2397
+ const next = await reader.read();
2398
+ if (next.done)
2399
+ break;
2400
+ size += next.value.byteLength;
2401
+ if (size > MAX_PROCESS_OUTPUT_BYTES) {
2402
+ await reader.cancel();
2403
+ throw new InfinityError("state_conflict", `${label} exceeded the bounded capture limit`, { status: 502 });
2404
+ }
2405
+ chunks.push(next.value);
2406
+ }
2407
+ const bytes = new Uint8Array(size);
2408
+ let offset = 0;
2409
+ for (const chunk of chunks) {
2410
+ bytes.set(chunk, offset);
2411
+ offset += chunk.byteLength;
2412
+ }
2413
+ try {
2414
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
2415
+ } catch {
2416
+ throw new InfinityError("state_conflict", `${label} was not valid UTF-8`, { status: 502 });
2417
+ }
2418
+ }
2419
+
2420
+ // src/cli/run.ts
2421
+ async function runCli(argv, runtime) {
2422
+ try {
2423
+ const args = [...argv];
2424
+ consumeGlobalOutput(args);
2425
+ const group = args.shift();
2426
+ if (!group)
2427
+ throw new CliUsageError("a command is required");
2428
+ let envelope;
2429
+ if (group === "version") {
2430
+ requireNoArguments(args, "version");
2431
+ envelope = await runtime.client.version();
2432
+ if (envelope.ok && isRecord(envelope.data)) {
2433
+ envelope = inheritOperatorEnvelopeHttpStatus(envelope, {
2434
+ ...envelope,
2435
+ data: { ...envelope.data, client_version: "0.1.0" }
2436
+ });
2437
+ } else if (envelope.ok) {
2438
+ throw new InfinityError("protocol_incompatible", "Infinity version success data must be an object", { status: 502 });
2439
+ }
2440
+ } else if (group === "doctor") {
2441
+ requireNoArguments(args, "doctor");
2442
+ envelope = await runtime.client.doctor();
2443
+ } else if (group === "capability") {
2444
+ const verb = args.shift();
2445
+ if (verb !== "list")
2446
+ throw new CliUsageError("capability supports only list");
2447
+ requireNoArguments(args, "capability list");
2448
+ envelope = await runtime.client.listCapabilities();
2449
+ } else if (group === "run") {
2450
+ envelope = await runCommand(args, runtime);
2451
+ } else if (group === "operation") {
2452
+ envelope = await operationCommand(args, runtime);
2453
+ } else if (group === "auth-capsule") {
2454
+ envelope = await authCapsuleCommand(args, runtime);
2455
+ } else if (group === "sandbox") {
2456
+ envelope = await sandboxCommand(args, runtime);
2457
+ } else {
2458
+ throw new CliUsageError("unknown command");
2459
+ }
2460
+ runtime.writeStdout(`${canonicalJson(envelope)}
2461
+ `);
2462
+ return envelope.ok ? 0 : exitCodeFor(envelope.error?.code ?? "internal_error", envelope.error?.retryable ?? false, operatorEnvelopeHttpStatus(envelope));
2463
+ } catch (error) {
2464
+ const envelope = localFailure(error, runtime.now());
2465
+ runtime.writeStdout(`${canonicalJson(envelope)}
2466
+ `);
2467
+ const status = error instanceof InfinityError ? error.status : undefined;
2468
+ return exitCodeFor(envelope.error?.code ?? "internal_error", envelope.error?.retryable ?? false, status);
2469
+ }
2470
+ }
2471
+ async function sandboxCommand(args, runtime) {
2472
+ if (args.shift() !== "dispatch") {
2473
+ throw new CliUsageError("sandbox supports only dispatch authorize or dispatch production");
2474
+ }
2475
+ const verb = args.shift();
2476
+ if (verb !== "authorize" && verb !== "production") {
2477
+ throw new CliUsageError("sandbox supports only dispatch authorize or dispatch production");
2478
+ }
2479
+ const parsed = parseFlags(args, new Set(["--spec"]), 0);
2480
+ const document = parseStrictJson(await runtime.readInput(requiredFlag(parsed, "--spec")));
2481
+ if (verb === "authorize")
2482
+ return runtime.client.authorizeSandboxDispatch(document);
2483
+ return runtime.client.dispatchProductionSandbox(document);
2484
+ }
2485
+ async function authCapsuleCommand(args, runtime) {
2486
+ const noun = args.shift();
2487
+ if (noun !== "descriptor" && noun !== "binding") {
2488
+ throw new CliUsageError("auth-capsule supports only descriptor or binding validation");
2489
+ }
2490
+ const parsed = parseFlags(args, new Set(["--spec"]), 0);
2491
+ const document = parseStrictJson(await runtime.readInput(requiredFlag(parsed, "--spec")));
2492
+ const data = noun === "descriptor" ? parseAuthCapsuleDescriptor(document) : parseCapsuleRemoteToolBinding(document);
2493
+ return {
2494
+ schema_version: "infinity.operator/v1",
2495
+ ok: true,
2496
+ request_id: "request-local",
2497
+ command: `auth-capsule.${noun}.validate`,
2498
+ server_time: runtime.now().toISOString(),
2499
+ data,
2500
+ warnings: [],
2501
+ next_actions: []
2502
+ };
2503
+ }
2504
+ async function runCommand(args, runtime) {
2505
+ const verb = args.shift();
2506
+ if (!verb)
2507
+ throw new CliUsageError("run command requires a verb");
2508
+ if (verb === "validate" || verb === "plan") {
2509
+ const parsed = parseFlags(args, new Set(["--spec"]), 0);
2510
+ const selector = requiredFlag(parsed, "--spec");
2511
+ const spec = parseStrictJson(await runtime.readInput(selector));
2512
+ return verb === "validate" ? runtime.client.validateRun(spec) : runtime.client.planRun(spec);
2513
+ }
2514
+ if (verb === "submit") {
2515
+ const parsed = parseFlags(args, new Set([
2516
+ "--spec",
2517
+ "--idempotency-key",
2518
+ "--authority-epoch",
2519
+ "--route-lineage-id",
2520
+ "--route-id",
2521
+ "--route-epoch"
2522
+ ]), 0);
2523
+ const spec = parseRunSpec(parseStrictJson(await runtime.readInput(requiredFlag(parsed, "--spec"))));
2524
+ const request = {
2525
+ spec,
2526
+ idempotencyKey: requiredFlag(parsed, "--idempotency-key"),
2527
+ authorityEpoch: int64Flag(parsed, "--authority-epoch"),
2528
+ routeLineageId: requiredFlag(parsed, "--route-lineage-id"),
2529
+ routeId: requiredFlag(parsed, "--route-id"),
2530
+ routeEpoch: int64Flag(parsed, "--route-epoch")
2531
+ };
2532
+ const tuple = submitRunMutationTuple({
2533
+ spec,
2534
+ routeLineageId: request.routeLineageId,
2535
+ routeId: request.routeId,
2536
+ routeEpoch: request.routeEpoch
2537
+ });
2538
+ const authorityRequestHash = mutationRequestHash({
2539
+ command: "run.submit",
2540
+ scope: tuple.scope,
2541
+ request: tuple.request,
2542
+ authorityEpoch: request.authorityEpoch,
2543
+ idempotencyKey: request.idempotencyKey
2544
+ });
2545
+ return dispatchMutation(runtime, {
2546
+ command: "run.submit",
2547
+ idempotencyKey: request.idempotencyKey,
2548
+ scope: tuple.scope,
2549
+ request: {
2550
+ authority_epoch: request.authorityEpoch,
2551
+ route_lineage_id: request.routeLineageId,
2552
+ route_id: request.routeId,
2553
+ route_epoch: request.routeEpoch,
2554
+ spec
2555
+ },
2556
+ authorityRequestHash,
2557
+ resultExpectation: {
2558
+ command: "run.submit",
2559
+ run_spec_digest: runSpecDigest(spec),
2560
+ authority_epoch: request.authorityEpoch,
2561
+ route_epoch: request.routeEpoch
2562
+ }
2563
+ }, (operationId) => runtime.client.submitRun({ ...request, operationId }));
2564
+ }
2565
+ if (verb === "get") {
2566
+ const parsed = parseFlags(args, new Set, 1);
2567
+ return runtime.client.getRun(parsed.positional[0]);
2568
+ }
2569
+ if (verb === "list") {
2570
+ const parsed = parseFlags(args, new Set(["--limit", "--cursor"]), 0);
2571
+ const limit = parsed.flags.has("--limit") ? integerFlag(parsed, "--limit", false, 100) : undefined;
2572
+ const cursor = parsed.flags.get("--cursor");
2573
+ return runtime.client.listRuns({ ...limit === undefined ? {} : { limit }, ...cursor === undefined ? {} : { cursor } });
2574
+ }
2575
+ if (verb === "wait") {
2576
+ const parsed = parseFlags(args, new Set(["--timeout-ms"]), 1);
2577
+ return runtime.client.waitRun(parsed.positional[0], integerFlag(parsed, "--timeout-ms", true, 30000));
2578
+ }
2579
+ if (verb === "attach") {
2580
+ const parsed = parseFlags(args, new Set(["--cursor", "--limit", "--wait-ms"]), 1);
2581
+ const cursor = String(integerFlag(parsed, "--cursor", true));
2582
+ const limit = integerFlag(parsed, "--limit", false, 100);
2583
+ const waitMs = integerFlag(parsed, "--wait-ms", true, 30000);
2584
+ return runtime.client.readRunEvents(parsed.positional[0], { cursor, limit, waitMs });
2585
+ }
2586
+ if (verb === "cancel") {
2587
+ const parsed = parseFlags(args, new Set([
2588
+ "--idempotency-key",
2589
+ "--authority-epoch",
2590
+ "--if-revision",
2591
+ "--attempt-id",
2592
+ "--if-attempt-number",
2593
+ "--if-attempt-revision",
2594
+ "--attempt-lease-id",
2595
+ "--lease-epoch",
2596
+ "--reason-code"
2597
+ ]), 1);
2598
+ const leaseSelector = optionalLeaseSelectorFlags(parsed);
2599
+ const request = {
2600
+ runId: parsed.positional[0],
2601
+ idempotencyKey: requiredFlag(parsed, "--idempotency-key"),
2602
+ authorityEpoch: int64Flag(parsed, "--authority-epoch"),
2603
+ ifRevision: integerFlag(parsed, "--if-revision", false, MAX_MUTABLE_IF_REVISION),
2604
+ attemptId: requiredFlag(parsed, "--attempt-id"),
2605
+ expectedAttemptNumber: integerFlag(parsed, "--if-attempt-number", false, MAX_POSTGRES_INTEGER),
2606
+ expectedAttemptRevision: integerFlag(parsed, "--if-attempt-revision", false, MAX_MUTABLE_IF_REVISION),
2607
+ ...leaseSelector,
2608
+ reasonCode: requiredFlag(parsed, "--reason-code")
2609
+ };
2610
+ return dispatchMutation(runtime, mutationIntent("run.cancel", request), (operationId) => runtime.client.cancelRun({ ...request, operationId }));
2611
+ }
2612
+ if (verb === "retry") {
2613
+ const parsed = parseFlags(args, new Set([
2614
+ "--idempotency-key",
2615
+ "--authority-epoch",
2616
+ "--if-revision",
2617
+ "--attempt-id",
2618
+ "--if-attempt-number",
2619
+ "--if-attempt-revision",
2620
+ "--attempt-lease-id",
2621
+ "--lease-epoch"
2622
+ ]), 1);
2623
+ const leaseSelector = optionalLeaseSelectorFlags(parsed);
2624
+ const request = {
2625
+ runId: parsed.positional[0],
2626
+ idempotencyKey: requiredFlag(parsed, "--idempotency-key"),
2627
+ authorityEpoch: int64Flag(parsed, "--authority-epoch"),
2628
+ ifRevision: integerFlag(parsed, "--if-revision", false, MAX_MUTABLE_IF_REVISION),
2629
+ attemptId: requiredFlag(parsed, "--attempt-id"),
2630
+ expectedAttemptNumber: integerFlag(parsed, "--if-attempt-number", false, MAX_MUTABLE_IF_REVISION),
2631
+ expectedAttemptRevision: integerFlag(parsed, "--if-attempt-revision", false, MAX_POSTGRES_INTEGER),
2632
+ ...leaseSelector
2633
+ };
2634
+ return dispatchMutation(runtime, mutationIntent("run.retry", request), (operationId) => runtime.client.retryRun({ ...request, operationId }));
2635
+ }
2636
+ throw new CliUsageError("unknown run verb");
2637
+ }
2638
+ async function dispatchMutation(runtime, intent, dispatch) {
2639
+ const prepared = await runtime.operationJournal.prepare(intent);
2640
+ let correlated;
2641
+ try {
2642
+ const envelope = await dispatch(prepared.operationId);
2643
+ correlated = envelope;
2644
+ if (envelope.operation_id === undefined) {
2645
+ if (!isOperatorPreReservationFailure(envelope)) {
2646
+ throw new InfinityError("integrity_failure", "Infinity mutation response omitted its protected operation ID", { status: 502 });
2647
+ }
2648
+ correlated = inheritOperatorEnvelopeHttpStatus(envelope, { ...envelope, operation_id: prepared.operationId });
2649
+ }
2650
+ if (correlated.command !== prepared.command || correlated.operation_id !== prepared.operationId) {
2651
+ throw new InfinityError("integrity_failure", "Infinity mutation response correlation does not match the protected operation", { status: 502 });
2652
+ }
2653
+ if (correlated.ok) {
2654
+ if (!isPublicMutationCommand(prepared.command)) {
2655
+ throw new InfinityError("protocol_incompatible", "CLI prepared an unsupported public mutation command", { status: 502 });
2656
+ }
2657
+ parsePublicMutationResult(prepared.command, correlated.data, prepared.operationId, prepared.resultExpectation);
2658
+ }
2659
+ } catch (error) {
2660
+ throw new AmbiguousMutationDispatchError(prepared.command, prepared.operationId, error);
2661
+ }
2662
+ await recordProtectedMutationResponse(runtime, prepared.command, prepared.operationId, correlated);
2663
+ return correlated;
2664
+ }
2665
+ async function recordProtectedMutationResponse(runtime, command, operationId, envelope) {
2666
+ try {
2667
+ await runtime.operationJournal.recordResponse(operationId, envelope);
2668
+ } catch (error) {
2669
+ if (error instanceof InfinityError && error.code === "integrity_failure")
2670
+ throw error;
2671
+ throw new AmbiguousMutationDispatchError(command, operationId, error);
2672
+ }
2673
+ }
2674
+ function mutationIntent(command, request) {
2675
+ const scope = { run_id: request.runId, attempt_id: request.attemptId };
2676
+ const authorityRequest = {
2677
+ expected_run_revision: request.ifRevision,
2678
+ expected_attempt_number: request.expectedAttemptNumber,
2679
+ expected_attempt_revision: request.expectedAttemptRevision,
2680
+ ...request.attemptLeaseId === undefined ? {} : {
2681
+ attempt_lease_id: request.attemptLeaseId,
2682
+ lease_epoch: request.leaseEpoch
2683
+ },
2684
+ ...request.reasonCode === undefined ? {} : { reason_code: request.reasonCode }
2685
+ };
2686
+ return {
2687
+ command,
2688
+ idempotencyKey: request.idempotencyKey,
2689
+ scope,
2690
+ request: {
2691
+ authority_epoch: request.authorityEpoch,
2692
+ if_revision: request.ifRevision,
2693
+ attempt_id: request.attemptId,
2694
+ if_attempt_number: request.expectedAttemptNumber,
2695
+ if_attempt_revision: request.expectedAttemptRevision,
2696
+ ...request.attemptLeaseId === undefined ? {} : {
2697
+ attempt_lease_id: request.attemptLeaseId,
2698
+ lease_epoch: request.leaseEpoch
2699
+ },
2700
+ ...request.reasonCode === undefined ? {} : { reason_code: request.reasonCode }
2701
+ },
2702
+ authorityRequestHash: mutationRequestHash({
2703
+ command,
2704
+ scope,
2705
+ request: authorityRequest,
2706
+ authorityEpoch: request.authorityEpoch,
2707
+ idempotencyKey: request.idempotencyKey
2708
+ }),
2709
+ resultExpectation: command === "run.cancel" ? {
2710
+ command,
2711
+ run_id: request.runId,
2712
+ attempt_id: request.attemptId,
2713
+ attempt_number: request.expectedAttemptNumber,
2714
+ expected_run_revision: nextExpectedRunRevision2(request.ifRevision),
2715
+ expected_attempt_revision: nextExpectedAttemptRevision2(request.expectedAttemptRevision),
2716
+ recovery_lease_duration_ms: CANCEL_RECOVERY_LEASE_DURATION_MS,
2717
+ prior_lease: request.attemptLeaseId === undefined ? { state: "none" } : {
2718
+ state: "selected",
2719
+ attempt_lease_id: request.attemptLeaseId,
2720
+ lease_epoch: request.leaseEpoch
2721
+ }
2722
+ } : {
2723
+ command,
2724
+ run_id: request.runId,
2725
+ predecessor_attempt_id: request.attemptId,
2726
+ expected_attempt_number: nextExpectedAttemptNumber2(request.expectedAttemptNumber),
2727
+ expected_run_revision: nextExpectedRunRevision2(request.ifRevision)
2728
+ }
2729
+ };
2730
+ }
2731
+ function nextExpectedRunRevision2(value) {
2732
+ if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_MUTABLE_IF_REVISION) {
2733
+ throw new CliUsageError("--if-revision cannot be incremented within the safe revision range");
2734
+ }
2735
+ return value + 1;
2736
+ }
2737
+ function nextExpectedAttemptRevision2(value) {
2738
+ if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_MUTABLE_IF_REVISION) {
2739
+ throw new CliUsageError("--if-attempt-revision cannot be incremented within the PostgreSQL integer range");
2740
+ }
2741
+ return value + 1;
2742
+ }
2743
+ function nextExpectedAttemptNumber2(value) {
2744
+ if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_MUTABLE_IF_REVISION) {
2745
+ throw new CliUsageError("--if-attempt-number cannot be incremented within the PostgreSQL integer range");
2746
+ }
2747
+ return value + 1;
2748
+ }
2749
+ async function operationCommand(args, runtime) {
2750
+ const verb = args.shift();
2751
+ if (verb !== "resolve")
2752
+ throw new CliUsageError("operation supports only resolve");
2753
+ const parsed = parseFlags(args, new Set, 1);
2754
+ const prepared = runtime.operationJournal.read(parsed.positional[0]);
2755
+ const envelope = await runtime.client.resolveOperation(prepared.operationId);
2756
+ if (envelope.ok) {
2757
+ const resolution = parsePublicOperationResolution(envelope.data, prepared.operationId, prepared.resultExpectation);
2758
+ if (resolution.status !== "unknown") {
2759
+ const binding = resolution.operation_binding;
2760
+ if (binding.command !== prepared.command || binding.idempotency_key !== prepared.idempotencyKey || binding.scope_digest !== prepared.scopeDigest || binding.request_hash !== prepared.authorityRequestHash) {
2761
+ throw new InfinityError("integrity_failure", "Infinity resolution tuple does not match the protected local operation", { status: 502 });
2762
+ }
2763
+ }
2764
+ if (resolution.status === "committed") {
2765
+ if (prepared.state === "responded") {
2766
+ const resolvedDigest = successfulMutationConsequenceDigest(prepared.command, prepared.operationId, resolution.result, prepared.resultExpectation);
2767
+ if (resolvedDigest !== prepared.responseDigest) {
2768
+ throw new InfinityError("integrity_failure", "Infinity committed resolution conflicts with the locally observed success", { status: 502 });
2769
+ }
2770
+ }
2771
+ const mutationEnvelope = inheritOperatorEnvelopeHttpStatus(envelope, {
2772
+ ...envelope,
2773
+ command: prepared.command,
2774
+ operation_id: prepared.operationId,
2775
+ data: resolution.result
2776
+ });
2777
+ await recordProtectedMutationResponse(runtime, prepared.command, prepared.operationId, mutationEnvelope);
2778
+ }
2779
+ }
2780
+ return envelope;
2781
+ }
2782
+ function consumeGlobalOutput(args) {
2783
+ if (args[0] !== "--output")
2784
+ return "json";
2785
+ args.shift();
2786
+ const value = args.shift();
2787
+ if (value !== "json" && value !== "jsonl")
2788
+ throw new CliUsageError("--output must be json or jsonl");
2789
+ return value;
2790
+ }
2791
+ function parseFlags(args, allowed, positionalCount) {
2792
+ const positional = [];
2793
+ const flags = new Map;
2794
+ for (let index = 0;index < args.length; index += 1) {
2795
+ const token = args[index];
2796
+ if (!token.startsWith("--")) {
2797
+ positional.push(token);
2798
+ continue;
2799
+ }
2800
+ if (!allowed.has(token))
2801
+ throw new CliUsageError("unsupported option");
2802
+ if (flags.has(token))
2803
+ throw new CliUsageError(`duplicate option ${token}`);
2804
+ const value = args[index + 1];
2805
+ if (value === undefined || value.startsWith("--"))
2806
+ throw new CliUsageError(`${token} requires a value`);
2807
+ flags.set(token, value);
2808
+ index += 1;
2809
+ }
2810
+ if (positional.length !== positionalCount)
2811
+ throw new CliUsageError(`expected ${positionalCount} positional argument(s)`);
2812
+ return { positional, flags };
2813
+ }
2814
+ function requiredFlag(parsed, name) {
2815
+ const value = parsed.flags.get(name);
2816
+ if (value === undefined)
2817
+ throw new CliUsageError(`${name} is required`);
2818
+ return value;
2819
+ }
2820
+ function integerFlag(parsed, name, allowZero, maximum = Number.MAX_SAFE_INTEGER) {
2821
+ const value = requiredFlag(parsed, name);
2822
+ const pattern = allowZero ? /^(?:0|[1-9]\d*)$/ : /^[1-9]\d*$/;
2823
+ if (!pattern.test(value))
2824
+ throw new CliUsageError(`${name} must be ${allowZero ? "a nonnegative" : "a positive"} integer`);
2825
+ const number = Number(value);
2826
+ if (!Number.isSafeInteger(number) || number > maximum)
2827
+ throw new CliUsageError(`${name} is outside the allowed integer range`);
2828
+ return number;
2829
+ }
2830
+ function int64Flag(parsed, name) {
2831
+ const value = requiredFlag(parsed, name);
2832
+ if (!/^[1-9]\d*$/.test(value))
2833
+ throw new CliUsageError(`${name} must be a positive integer`);
2834
+ try {
2835
+ const parsedValue = BigInt(value);
2836
+ return positiveInt64(parsedValue, name);
2837
+ } catch {
2838
+ throw new CliUsageError(`${name} is outside the signed 64-bit range`);
2839
+ }
2840
+ }
2841
+ function optionalLeaseSelectorFlags(parsed) {
2842
+ const hasAttemptLeaseId = parsed.flags.has("--attempt-lease-id");
2843
+ const hasLeaseEpoch = parsed.flags.has("--lease-epoch");
2844
+ if (hasAttemptLeaseId !== hasLeaseEpoch) {
2845
+ throw new CliUsageError("--attempt-lease-id and --lease-epoch must be supplied together");
2846
+ }
2847
+ if (!hasAttemptLeaseId)
2848
+ return {};
2849
+ return {
2850
+ attemptLeaseId: requiredFlag(parsed, "--attempt-lease-id"),
2851
+ leaseEpoch: int64Flag(parsed, "--lease-epoch")
2852
+ };
2853
+ }
2854
+ function requireNoArguments(args, command) {
2855
+ if (args.length !== 0)
2856
+ throw new CliUsageError(`${command} accepts no arguments`);
2857
+ }
2858
+ function isRecord(value) {
2859
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2860
+ }
2861
+ function exitCodeFor(code, retryable, httpStatus) {
2862
+ if (code === "operation_outcome_unknown")
2863
+ return 10;
2864
+ if (httpStatus === 503)
2865
+ return 9;
2866
+ if (code === "invalid_input")
2867
+ return 2;
2868
+ if (code === "not_found")
2869
+ return 5;
2870
+ if (["capability_denied", "policy_denied"].includes(code))
2871
+ return 4;
2872
+ if (["idempotency_key_reused", "operation_id_conflict", "logical_work_conflict", "authority_epoch_mismatch", "stale_revision", "stale_lease_epoch"].includes(code))
2873
+ return 6;
2874
+ if (code === "state_conflict" && httpStatus === 409)
2875
+ return 6;
2876
+ if (code === "state_conflict" && retryable)
2877
+ return 9;
2878
+ if (["state_conflict", "approval_required", "approval_digest_mismatch"].includes(code))
2879
+ return 7;
2880
+ if (code === "capacity_unavailable")
2881
+ return 8;
2882
+ if (code === "protocol_incompatible")
2883
+ return 12;
2884
+ if (code === "integrity_failure")
2885
+ return 13;
2886
+ return 14;
2887
+ }
2888
+
2889
+ class AmbiguousMutationDispatchError extends Error {
2890
+ command;
2891
+ operationId;
2892
+ original;
2893
+ constructor(command, operationId, original) {
2894
+ super(original instanceof Error ? original.message : "mutation dispatch failed after the operation was prepared", { cause: original });
2895
+ this.command = command;
2896
+ this.operationId = operationId;
2897
+ this.original = original;
2898
+ this.name = "AmbiguousMutationDispatchError";
2899
+ }
2900
+ }
2901
+
2902
+ class CliUsageError extends Error {
2903
+ constructor(message) {
2904
+ super(message);
2905
+ this.name = "CliUsageError";
2906
+ }
2907
+ }
2908
+ function localFailure(error, now) {
2909
+ const dispatch = error instanceof AmbiguousMutationDispatchError ? error : undefined;
2910
+ const original = dispatch?.original ?? error;
2911
+ const usage = original instanceof CliUsageError;
2912
+ const known = original instanceof InfinityError;
2913
+ const unknownOutcome = dispatch !== undefined;
2914
+ const code = unknownOutcome ? "operation_outcome_unknown" : usage ? "invalid_input" : known ? original.code : "internal_error";
2915
+ return {
2916
+ schema_version: "infinity.operator/v1",
2917
+ ok: false,
2918
+ request_id: "request-local",
2919
+ command: dispatch?.command ?? "local",
2920
+ server_time: now.toISOString(),
2921
+ ...dispatch === undefined ? {} : { operation_id: dispatch.operationId },
2922
+ error: {
2923
+ code,
2924
+ message: unknownOutcome ? "Mutation dispatch outcome is unknown; resolve the protected operation ID before retrying." : original instanceof Error ? original.message : "Internal client error.",
2925
+ retryable: unknownOutcome ? false : known ? original.retryable : false,
2926
+ retry_after_ms: null,
2927
+ details: known ? { ...original.details } : {},
2928
+ remediation: unknownOutcome ? "Resolve the emitted protected operation ID before retrying." : usage || code === "invalid_input" ? "Correct the explicit command arguments." : code === "protocol_incompatible" || code === "integrity_failure" ? "Stop and verify the configured Infinity endpoint and schema." : "Contact the Infinity operator."
2929
+ },
2930
+ warnings: [],
2931
+ next_actions: []
2932
+ };
2933
+ }
2934
+
2935
+ // src/cli/main.ts
2936
+ var LOCAL_OPERATOR_ENDPOINT = "http://127.0.0.1:18787";
2937
+ try {
2938
+ const ids = new RandomIdFactory;
2939
+ const clock = new SystemClock;
2940
+ const operationJournal = new DurableCliOperationJournal(defaultCliOperationJournalPath(), ids, clock);
2941
+ try {
2942
+ process.exitCode = await runCli(Bun.argv.slice(2), {
2943
+ client: new OperatorHttpClient(LOCAL_OPERATOR_ENDPOINT),
2944
+ readInput: async (selector) => {
2945
+ if (selector !== "-")
2946
+ throw new CliUsageError("--spec accepts stdin ('-') only");
2947
+ return Bun.stdin.text();
2948
+ },
2949
+ writeStdout: (value) => process.stdout.write(value),
2950
+ writeStderr: (value) => process.stderr.write(value),
2951
+ operationJournal,
2952
+ now: () => clock.now()
2953
+ });
2954
+ } finally {
2955
+ operationJournal.close();
2956
+ }
2957
+ } catch (error) {
2958
+ const usage = new CliUsageError(error instanceof Error ? error.message : "invalid CLI startup configuration");
2959
+ process.stdout.write(`${canonicalJson(localFailure(usage, new Date))}
2960
+ `);
2961
+ process.exitCode = 2;
2962
+ }
2963
+ export {
2964
+ LOCAL_OPERATOR_ENDPOINT
2965
+ };