@intentic/sandbox-contract 1.421.0 → 1.423.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 (251) hide show
  1. package/dist/chores/chores.d.ts.map +1 -1
  2. package/dist/chores/chores.js +1 -48
  3. package/dist/chores/chores.js.map +1 -1
  4. package/dist/chores/index.d.ts +1 -1
  5. package/dist/chores/index.d.ts.map +1 -1
  6. package/dist/chores/index.js +1 -1
  7. package/dist/chores/index.js.map +1 -1
  8. package/dist/chores/prompt.d.ts +0 -1
  9. package/dist/chores/prompt.d.ts.map +1 -1
  10. package/dist/chores/prompt.js +0 -2
  11. package/dist/chores/prompt.js.map +1 -1
  12. package/dist/contracts/capabilities.contract.d.ts +0 -28
  13. package/dist/contracts/capabilities.contract.d.ts.map +1 -1
  14. package/dist/contracts/ci.contract.d.ts +30 -0
  15. package/dist/contracts/ci.contract.d.ts.map +1 -1
  16. package/dist/contracts/ci.contract.js +10 -1
  17. package/dist/contracts/ci.contract.js.map +1 -1
  18. package/dist/contracts/device.contract.d.ts +46 -0
  19. package/dist/contracts/device.contract.d.ts.map +1 -1
  20. package/dist/contracts/device.contract.js +2 -0
  21. package/dist/contracts/device.contract.js.map +1 -1
  22. package/dist/contracts/issues.contract.d.ts +6 -0
  23. package/dist/contracts/issues.contract.d.ts.map +1 -1
  24. package/dist/contracts/offload.contract.d.ts +51 -0
  25. package/dist/contracts/offload.contract.d.ts.map +1 -1
  26. package/dist/contracts/offload.contract.js +3 -3
  27. package/dist/contracts/offload.contract.js.map +1 -1
  28. package/dist/contracts/panels.contract.d.ts +0 -7
  29. package/dist/contracts/panels.contract.d.ts.map +1 -1
  30. package/dist/contracts/runner.contract.d.ts +48 -0
  31. package/dist/contracts/runner.contract.d.ts.map +1 -1
  32. package/dist/contracts/secrets.contract.d.ts +2 -17
  33. package/dist/contracts/secrets.contract.d.ts.map +1 -1
  34. package/dist/contracts/secrets.contract.js +2 -2
  35. package/dist/contracts/secrets.contract.js.map +1 -1
  36. package/dist/contracts/settings.contract.d.ts +0 -135
  37. package/dist/contracts/settings.contract.d.ts.map +1 -1
  38. package/dist/contracts/system.contract.d.ts +18 -18
  39. package/dist/contracts/workspace.contract.d.ts +0 -60
  40. package/dist/contracts/workspace.contract.d.ts.map +1 -1
  41. package/dist/contracts/workspace.contract.js +1 -11
  42. package/dist/contracts/workspace.contract.js.map +1 -1
  43. package/dist/events/requests.js +1 -1
  44. package/dist/events/requests.js.map +1 -1
  45. package/dist/ids/project-id.d.ts +3 -0
  46. package/dist/ids/project-id.d.ts.map +1 -0
  47. package/dist/ids/project-id.js +25 -0
  48. package/dist/ids/project-id.js.map +1 -0
  49. package/dist/ids/tunnel-ids.d.ts +0 -1
  50. package/dist/ids/tunnel-ids.d.ts.map +1 -1
  51. package/dist/ids/tunnel-ids.js +0 -1
  52. package/dist/ids/tunnel-ids.js.map +1 -1
  53. package/dist/index.d.ts +0 -4
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +0 -4
  56. package/dist/index.js.map +1 -1
  57. package/dist/models/account-moves.js +4 -4
  58. package/dist/models/account-moves.js.map +1 -1
  59. package/dist/models/model-roles.d.ts +1 -1
  60. package/dist/models/model-roles.d.ts.map +1 -1
  61. package/dist/models/model-roles.js +1 -1
  62. package/dist/models/model-roles.js.map +1 -1
  63. package/dist/models/plan-pools.d.ts +3 -1
  64. package/dist/models/plan-pools.d.ts.map +1 -1
  65. package/dist/models/plan-pools.js +26 -3
  66. package/dist/models/plan-pools.js.map +1 -1
  67. package/dist/protocol/doors/runner-protocol.d.ts +42 -0
  68. package/dist/protocol/doors/runner-protocol.d.ts.map +1 -1
  69. package/dist/protocol/doors/runner-protocol.js +23 -0
  70. package/dist/protocol/doors/runner-protocol.js.map +1 -1
  71. package/dist/protocol/doors/sandbox-pass.d.ts +22 -0
  72. package/dist/protocol/doors/sandbox-pass.d.ts.map +1 -0
  73. package/dist/protocol/doors/sandbox-pass.js +72 -0
  74. package/dist/protocol/doors/sandbox-pass.js.map +1 -0
  75. package/dist/protocol/raw/raw-json-routes.d.ts +96 -9
  76. package/dist/protocol/raw/raw-json-routes.d.ts.map +1 -1
  77. package/dist/protocol/raw/raw-json-routes.js +6 -2
  78. package/dist/protocol/raw/raw-json-routes.js.map +1 -1
  79. package/dist/protocol/raw/raw-routes.d.ts +24 -7
  80. package/dist/protocol/raw/raw-routes.d.ts.map +1 -1
  81. package/dist/protocol/raw/raw-routes.js +6 -2
  82. package/dist/protocol/raw/raw-routes.js.map +1 -1
  83. package/dist/schemas/capabilities.d.ts +0 -14
  84. package/dist/schemas/capabilities.d.ts.map +1 -1
  85. package/dist/schemas/capabilities.js +0 -4
  86. package/dist/schemas/capabilities.js.map +1 -1
  87. package/dist/schemas/certificate-request.d.ts +0 -2
  88. package/dist/schemas/certificate-request.d.ts.map +1 -1
  89. package/dist/schemas/ci.d.ts +69 -0
  90. package/dist/schemas/ci.d.ts.map +1 -1
  91. package/dist/schemas/ci.js +30 -0
  92. package/dist/schemas/ci.js.map +1 -1
  93. package/dist/schemas/device-files.d.ts +71 -0
  94. package/dist/schemas/device-files.d.ts.map +1 -0
  95. package/dist/schemas/device-files.js +53 -0
  96. package/dist/schemas/device-files.js.map +1 -0
  97. package/dist/schemas/devices.d.ts.map +1 -1
  98. package/dist/schemas/devices.js.map +1 -1
  99. package/dist/schemas/hosts.d.ts +3 -0
  100. package/dist/schemas/hosts.d.ts.map +1 -1
  101. package/dist/schemas/hosts.js +3 -0
  102. package/dist/schemas/hosts.js.map +1 -1
  103. package/dist/schemas/issues.d.ts +133 -0
  104. package/dist/schemas/issues.d.ts.map +1 -1
  105. package/dist/schemas/issues.js +34 -0
  106. package/dist/schemas/issues.js.map +1 -1
  107. package/dist/schemas/maintenance.d.ts.map +1 -1
  108. package/dist/schemas/maintenance.js +16 -10
  109. package/dist/schemas/maintenance.js.map +1 -1
  110. package/dist/schemas/metrics.d.ts.map +1 -1
  111. package/dist/schemas/metrics.js.map +1 -1
  112. package/dist/schemas/offload.d.ts +40 -0
  113. package/dist/schemas/offload.d.ts.map +1 -1
  114. package/dist/schemas/offload.js +21 -0
  115. package/dist/schemas/offload.js.map +1 -1
  116. package/dist/schemas/panels.d.ts +0 -14
  117. package/dist/schemas/panels.d.ts.map +1 -1
  118. package/dist/schemas/panels.js +0 -6
  119. package/dist/schemas/panels.js.map +1 -1
  120. package/dist/schemas/personas.d.ts.map +1 -1
  121. package/dist/schemas/personas.js +0 -6
  122. package/dist/schemas/personas.js.map +1 -1
  123. package/dist/schemas/providers/plan-limits.d.ts +1 -0
  124. package/dist/schemas/providers/plan-limits.d.ts.map +1 -1
  125. package/dist/schemas/providers/plan-limits.js +5 -1
  126. package/dist/schemas/providers/plan-limits.js.map +1 -1
  127. package/dist/schemas/providers/usage.d.ts +0 -12
  128. package/dist/schemas/providers/usage.d.ts.map +1 -1
  129. package/dist/schemas/providers/usage.js +0 -5
  130. package/dist/schemas/providers/usage.js.map +1 -1
  131. package/dist/schemas/secrets.d.ts +1 -22
  132. package/dist/schemas/secrets.d.ts.map +1 -1
  133. package/dist/schemas/secrets.js +3 -13
  134. package/dist/schemas/secrets.js.map +1 -1
  135. package/dist/schemas/settings-experiments.d.ts +0 -4
  136. package/dist/schemas/settings-experiments.d.ts.map +1 -1
  137. package/dist/schemas/settings-experiments.js +0 -12
  138. package/dist/schemas/settings-experiments.js.map +1 -1
  139. package/dist/schemas/settings-history.d.ts +1 -1
  140. package/dist/schemas/settings-history.d.ts.map +1 -1
  141. package/dist/schemas/settings-history.js +1 -0
  142. package/dist/schemas/settings-history.js.map +1 -1
  143. package/dist/schemas/settings-savings.d.ts +0 -144
  144. package/dist/schemas/settings-savings.d.ts.map +1 -1
  145. package/dist/schemas/settings-savings.js +1 -3
  146. package/dist/schemas/settings-savings.js.map +1 -1
  147. package/dist/schemas/settings.d.ts +0 -4
  148. package/dist/schemas/settings.d.ts.map +1 -1
  149. package/dist/schemas/settings.js +3 -4
  150. package/dist/schemas/settings.js.map +1 -1
  151. package/dist/schemas/short-codes.d.ts +0 -10
  152. package/dist/schemas/short-codes.d.ts.map +1 -1
  153. package/dist/schemas/short-codes.js +1 -9
  154. package/dist/schemas/short-codes.js.map +1 -1
  155. package/dist/schemas/workspace/workspace-search.d.ts +0 -12
  156. package/dist/schemas/workspace/workspace-search.d.ts.map +1 -1
  157. package/dist/schemas/workspace/workspace-search.js +5 -12
  158. package/dist/schemas/workspace/workspace-search.js.map +1 -1
  159. package/dist/state/definition.d.ts +0 -24
  160. package/dist/state/definition.d.ts.map +1 -1
  161. package/dist/state/update-probation.d.ts +1 -1
  162. package/dist/state/update-probation.d.ts.map +1 -1
  163. package/dist/state/update-probation.js +1 -1
  164. package/dist/state/update-probation.js.map +1 -1
  165. package/dist/state/workspace-state.d.ts +6 -1
  166. package/dist/state/workspace-state.d.ts.map +1 -1
  167. package/dist/state/workspace-state.js +7 -1
  168. package/dist/state/workspace-state.js.map +1 -1
  169. package/package.json +27 -5
  170. package/src/chores/chores.test.ts +1 -2
  171. package/src/chores/chores.ts +2 -62
  172. package/src/chores/index.ts +1 -1
  173. package/src/chores/prompt.ts +1 -6
  174. package/src/chores/verdict.test.ts +3 -44
  175. package/src/contracts/ci.contract.ts +13 -0
  176. package/src/contracts/device.contract.ts +5 -0
  177. package/src/contracts/offload.contract.ts +3 -2
  178. package/src/contracts/secrets.contract.ts +4 -5
  179. package/src/contracts/workspace.contract.ts +2 -14
  180. package/src/events/requests.ts +1 -1
  181. package/src/events/system-events.ts +2 -2
  182. package/src/ids/project-id.test.ts +26 -0
  183. package/src/ids/project-id.ts +34 -0
  184. package/src/ids/tunnel-ids.test.ts +2 -23
  185. package/src/ids/tunnel-ids.ts +0 -4
  186. package/src/index.ts +0 -6
  187. package/src/models/account-moves.ts +6 -6
  188. package/src/models/model-roles.ts +3 -1
  189. package/src/models/plan-pools.test.ts +57 -20
  190. package/src/models/plan-pools.ts +48 -8
  191. package/src/policy/persona-capability.ts +1 -1
  192. package/src/protocol/doors/runner-protocol.ts +42 -2
  193. package/src/protocol/doors/sandbox-pass.test.ts +51 -0
  194. package/src/protocol/doors/sandbox-pass.ts +119 -0
  195. package/src/protocol/headers.ts +2 -2
  196. package/src/protocol/member-reach.test.ts +0 -1
  197. package/src/protocol/raw/raw-json-routes.ts +14 -2
  198. package/src/protocol/raw/raw-routes.ts +14 -5
  199. package/src/protocol/routes.test.ts +0 -4
  200. package/src/schemas/automations.ts +3 -3
  201. package/src/schemas/capabilities.ts +0 -6
  202. package/src/schemas/ci.ts +42 -0
  203. package/src/schemas/device-files.ts +90 -0
  204. package/src/schemas/devices.ts +5 -4
  205. package/src/schemas/hosts.ts +15 -3
  206. package/src/schemas/issues.ts +54 -0
  207. package/src/schemas/maintenance.ts +20 -12
  208. package/src/schemas/metrics.ts +2 -0
  209. package/src/schemas/offload.ts +39 -2
  210. package/src/schemas/panels.ts +0 -8
  211. package/src/schemas/personas.ts +2 -6
  212. package/src/schemas/providers/plan-limits.ts +7 -1
  213. package/src/schemas/providers/usage.ts +5 -14
  214. package/src/schemas/secrets.ts +8 -20
  215. package/src/schemas/settings-experiments.ts +0 -17
  216. package/src/schemas/settings-history.ts +3 -0
  217. package/src/schemas/settings-savings.ts +2 -9
  218. package/src/schemas/settings.test.ts +16 -9
  219. package/src/schemas/settings.ts +5 -5
  220. package/src/schemas/short-codes.ts +2 -14
  221. package/src/schemas/version-seam.test.ts +2 -2
  222. package/src/schemas/workspace/workspace-search.ts +12 -25
  223. package/src/state/update-probation.ts +4 -3
  224. package/src/state/workspace-state.test.ts +2 -2
  225. package/src/state/workspace-state.ts +10 -1
  226. package/src/text/path-refs.test.ts +1 -1
  227. package/dist/contracts/intentic.contract.d.ts +0 -30
  228. package/dist/contracts/intentic.contract.d.ts.map +0 -1
  229. package/dist/contracts/intentic.contract.js +0 -34
  230. package/dist/contracts/intentic.contract.js.map +0 -1
  231. package/dist/contracts/inventory.contract.d.ts +0 -138
  232. package/dist/contracts/inventory.contract.d.ts.map +0 -1
  233. package/dist/contracts/inventory.contract.js +0 -31
  234. package/dist/contracts/inventory.contract.js.map +0 -1
  235. package/dist/schemas/codebase-health.d.ts +0 -56
  236. package/dist/schemas/codebase-health.d.ts.map +0 -1
  237. package/dist/schemas/codebase-health.js +0 -43
  238. package/dist/schemas/codebase-health.js.map +0 -1
  239. package/dist/schemas/intentic.d.ts +0 -5
  240. package/dist/schemas/intentic.d.ts.map +0 -1
  241. package/dist/schemas/intentic.js +0 -3
  242. package/dist/schemas/intentic.js.map +0 -1
  243. package/dist/schemas/inventory.d.ts +0 -175
  244. package/dist/schemas/inventory.d.ts.map +0 -1
  245. package/dist/schemas/inventory.js +0 -62
  246. package/dist/schemas/inventory.js.map +0 -1
  247. package/src/contracts/intentic.contract.ts +0 -45
  248. package/src/contracts/inventory.contract.ts +0 -35
  249. package/src/schemas/codebase-health.ts +0 -60
  250. package/src/schemas/intentic.ts +0 -2
  251. package/src/schemas/inventory.ts +0 -83
@@ -13,7 +13,9 @@ import {
13
13
  refusalVerdict,
14
14
  refusedInstant,
15
15
  refusedPoolReset,
16
- roomiestAccount,
16
+ bestWithRoom,
17
+ NEARLY_OUT_ROOM,
18
+ renewalOf,
17
19
  scopedWindow,
18
20
  uncoveredModels,
19
21
  serviceState,
@@ -179,8 +181,8 @@ test("spent is the contract's one line: 99.5% still has room, 100% is spent unti
179
181
  test("a pool read at 100 in whole percents is at the line with no room, until a refusal proves it empty", () => {
180
182
  const week = window({ kind: "seven_day", utilization: 100, resetsAt: 900, rounded: true });
181
183
  const atLine = usage(window({ kind: "five_hour", utilization: 75, rounded: true }), week);
182
- expect(readingHeadroom(atLine)).toEqual({ kind: "ready", room: 0 });
183
- expect(readingHeadroom(atLine, { id: "claude-opus-5-5" })).toEqual({ kind: "ready", room: 0 });
184
+ expect(readingHeadroom(atLine)).toEqual({ kind: "ready", room: 0, renewsAt: 900 });
185
+ expect(readingHeadroom(atLine, { id: "claude-opus-5-5" })).toEqual({ kind: "ready", room: 0, renewsAt: 900 });
184
186
  // A precise 100 is still spent.
185
187
  expect(readingHeadroom(usage(window({ kind: "seven_day", utilization: 100, resetsAt: 900 })))).toEqual({ kind: "spent", reopensAt: 900 });
186
188
  // The provider refused it: spent until the pool reopens, and a reading still at the line does not answer that.
@@ -349,7 +351,7 @@ test("a spent allowance with no instant named is stamped with its pool's reset,
349
351
  const lapsed = at(500, window({ kind: "five_hour", utilization: 0, lapsedAt: reset }), window({ kind: "seven_day", utilization: 40, resetsAt: 900 }));
350
352
  expect(refusedPoolReset(spent, [{ account: "a", usage: lapsed }])).toBe(900);
351
353
  expect(refusalVerdict(filed, [{ account: "a", usage: lapsed }], reset * 1000)).toBe("answered");
352
- expect(serviceStates([{ account: "a", usage: lapsed }], [filed], undefined, reset * 1000).get("a")).toEqual({ kind: "ready", room: 60 });
354
+ expect(serviceStates([{ account: "a", usage: lapsed }], [filed], undefined, reset * 1000).get("a")).toEqual({ kind: "ready", room: 60, renewsAt: 900 });
353
355
  });
354
356
 
355
357
  // 2026-10-21: Claude refused at 5h 98% and weekly 97% (rounded) with no time named, so the refusal was stamped with the
@@ -378,7 +380,7 @@ test("a stamped reset ends a refusal only where no reading since it says the poo
378
380
  expect(serviceStates([{ account: "a", usage: weeklyFull }], [stamped], undefined, now).get("a")).toEqual(unstampedVerdict);
379
381
  expect(fleetCapacity([{ account: "a", usage: weeklyFull }], [stamped], undefined, now)).toMatchObject({ kind: "spent", reopensAt: weeklyReset });
380
382
  // Nothing read since the stamp: it ends there. Read with room since: over.
381
- expect(serviceStates([{ account: "a", usage: refusedIn }], [stamped], undefined, now).get("a")).toEqual({ kind: "ready", room: 2 });
383
+ expect(serviceStates([{ account: "a", usage: refusedIn }], [stamped], undefined, now).get("a")).toEqual({ kind: "ready", room: 2, renewsAt: weeklyReset });
382
384
  const roomSince = at((fiveHourReset + 600) * 1000, window({ kind: "five_hour", utilization: 4, resetsAt: fiveHourReset + 18_000 }), window({ kind: "seven_day", utilization: 60, resetsAt: weeklyReset }));
383
385
  expect(refusalVerdict(stamped, [{ account: "a", usage: roomSince }], now)).toBe("answered");
384
386
  });
@@ -436,9 +438,9 @@ test("each account answers to the newest refusal on file that still stands over
436
438
  b: { kind: "blocked", fix: "reconnect", reason: "no." },
437
439
  });
438
440
  // Only the provider's last one: the first account is back at the line, no room but not proven spent.
439
- expect(serviceStates(accounts, [elsewhere], undefined, 9_999).get("a")).toEqual({ kind: "ready", room: 0 });
441
+ expect(serviceStates(accounts, [elsewhere], undefined, 9_999).get("a")).toEqual({ kind: "ready", room: 0, renewsAt: 20 });
440
442
  // Past the instant the provider named, its refusal is over and the reading speaks alone.
441
- expect(serviceStates(accounts, [elsewhere, own], undefined, 20_000).get("a")).toEqual({ kind: "ready", room: 0 });
443
+ expect(serviceStates(accounts, [elsewhere, own], undefined, 20_000).get("a")).toEqual({ kind: "ready", room: 0, renewsAt: 20 });
442
444
  // A newer refusal on the same account outranks the older one.
443
445
  const revoked = refusal({ kind: "auth", account: "a", at: 6_000 });
444
446
  expect(serviceStates(accounts, [own, revoked], undefined, 9_999).get("a")).toEqual({ kind: "blocked", fix: "reconnect", reason: "no." });
@@ -491,14 +493,14 @@ test("refusals naming their accounts hold a 31-account Google fleet steady acros
491
493
  expect(fleetCapacity(accounts, refused, flash, reread)).toMatchObject({ kind: "serving", serving: 2, accounts: 31 });
492
494
  const states = serviceStates(accounts, refused, opus, reread);
493
495
  expect(states.get("tried-0")).toEqual({ kind: "spent", reopensAt: opusBack, pool: "Claude and GPT models" });
494
- expect(states.get("svichita09")).toEqual({ kind: "ready", room: 100 });
496
+ expect(states.get("svichita09")).toEqual({ kind: "ready", room: 100, renewsAt: opusBack });
495
497
  }
496
498
  // The same refusal filed under no account is answered on each account by its own reading alone: the account with
497
499
  // room frees itself, never one whose reading since says nothing.
498
500
  const nameless = refusal({ kind: "limit", at: refusedAt, model: "claude-opus-4-6-thinking", resetsAt: opusBack });
499
501
  const onlyOneRead = fleet(refusedAt - 30_000).map((facts) => (facts.account === "svichita09" ? { ...facts, usage: pools(reread, 0, 19.42) } : facts));
500
502
  const states = serviceStates([...onlyOneRead, { account: "unread" }], [nameless], opus, reread);
501
- expect(states.get("svichita09")).toEqual({ kind: "ready", room: 100 });
503
+ expect(states.get("svichita09")).toEqual({ kind: "ready", room: 100, renewsAt: opusBack });
502
504
  expect(states.get("unread")).toMatchObject({ kind: "spent", reopensAt: opusBack });
503
505
  });
504
506
 
@@ -528,8 +530,43 @@ test("an unnamed turn takes the most room, then an unmeasured account, then a sp
528
530
  expect(preferredAccount([entry("seatless", blocked), entry("spent", { kind: "spent" })])?.id).toBe("spent");
529
531
  expect(preferredAccount([entry("seatless", blocked), entry("other", blocked)])?.id).toBe("seatless");
530
532
  expect(preferredAccount([entry("first", { kind: "ready", room: 60 }), entry("second", { kind: "ready", room: 60 })])?.id).toBe("first");
531
- expect(roomiestAccount([entry("seatless", blocked), entry("unread", { kind: "unknown" })])).toBeUndefined();
532
- expect(roomiestAccount([entry("low", { kind: "ready", room: 5 }), entry("high", { kind: "ready", room: 60 })])?.id).toBe("high");
533
+ expect(bestWithRoom([entry("seatless", blocked), entry("unread", { kind: "unknown" })])).toBeUndefined();
534
+ expect(bestWithRoom([entry("low", { kind: "ready", room: 5 }), entry("high", { kind: "ready", room: 60 })])?.id).toBe("high");
535
+ });
536
+
537
+ /* 2026-11-17: Claude's Ultra plan meters no five-hour window. One account had 70 weekly points left renewing in six days,
538
+ the other 40 renewing in ten hours, and the most-room pick spent the first while the second's reset unspent. */
539
+ test("between accounts with room, the one whose allowance renews first wins, unless it is nearly out", () => {
540
+ const entry = (id: string, state: AccountState) => ({ id, state });
541
+ const now = 1_800_000_000;
542
+ const later = entry("later", { kind: "ready", room: 70, renewsAt: now + 144 * 3_600 });
543
+ const sooner = entry("sooner", { kind: "ready", room: 40, renewsAt: now + 10 * 3_600 });
544
+ expect(preferredAccount([later, sooner])?.id).toBe("sooner");
545
+ expect(bestWithRoom([later, sooner])?.id).toBe("sooner");
546
+ // Nearly out, it ranks after every account with more, however soon it renews; among those, room decides.
547
+ const nearlyOut = entry("nearly-out", { kind: "ready", room: NEARLY_OUT_ROOM, renewsAt: now + 3_600 });
548
+ expect(preferredAccount([nearlyOut, later])?.id).toBe("later");
549
+ expect(preferredAccount([nearlyOut, entry("lower", { kind: "ready", room: 4, renewsAt: now })])?.id).toBe("nearly-out");
550
+ // A reset nobody published never outranks a known one; between two unknown, room decides as before.
551
+ expect(preferredAccount([entry("unknown", { kind: "ready", room: 90 }), sooner])?.id).toBe("sooner");
552
+ expect(preferredAccount([entry("a", { kind: "ready", room: 50 }), entry("b", { kind: "ready", room: 60 })])?.id).toBe("b");
553
+ // The same moment: room decides.
554
+ expect(preferredAccount([sooner, entry("roomier", { kind: "ready", room: 80, renewsAt: now + 10 * 3_600 })])?.id).toBe("roomier");
555
+ });
556
+
557
+ test("an allowance renews when the longest pool the turn spends resets, never when a five-hour one does", () => {
558
+ const now = 1_800_000_000;
559
+ const weekly = (utilization: number, resetsAt: number): UsageWindow => ({ kind: "seven_day", utilization, resetsAt, gates: "all" });
560
+ const fiveHour: UsageWindow = { kind: "five_hour", utilization: 90, resetsAt: now + 3_600, gates: "all" };
561
+ expect(renewalOf([fiveHour, weekly(40, now + 20 * 3_600)])).toBe(now + 20 * 3_600);
562
+ // Two weekly pools (the whole plan's and Opus's slice): the first of them to reset.
563
+ expect(renewalOf([weekly(40, now + 50 * 3_600), { ...weekly(10, now + 30 * 3_600), kind: "seven_day_opus", gates: { models: ["opus"] } }])).toBe(now + 30 * 3_600);
564
+ // The weekly pool has lapsed (its reset passed, nothing re-read it): what renews is unknown, not the five-hour reset.
565
+ expect(renewalOf([fiveHour, { kind: "seven_day", utilization: 0, gates: "all", lapsedAt: now }])).toBeUndefined();
566
+ // No pool names its length: the first to reset decides.
567
+ expect(renewalOf([{ kind: "pool:a", utilization: 10, resetsAt: now + 7_200, gates: "all" }, { kind: "pool:b", utilization: 10, resetsAt: now + 3_600, gates: "all" }])).toBe(now + 3_600);
568
+ // The verdict carries it, read off the pools still open.
569
+ expect(readingHeadroom({ windows: [fiveHour, weekly(40, now + 20 * 3_600)], measuredAt: now * 1000 })).toEqual({ kind: "ready", room: 10, renewsAt: now + 20 * 3_600 });
533
570
  });
534
571
 
535
572
  test("an account at the line is tried after an unmeasured one and before a spent one, and never a move's destination", () => {
@@ -539,8 +576,8 @@ test("an account at the line is tried after an unmeasured one and before a spent
539
576
  expect(preferredAccount([entry("line", atLine), entry("unread", { kind: "unknown" })])?.id).toBe("unread");
540
577
  expect(preferredAccount([entry("spent", { kind: "spent" }), entry("line", atLine)])?.id).toBe("line");
541
578
  // A move lands only on proven room: two accounts at the line would otherwise hand a refused turn back and forth.
542
- expect(roomiestAccount([entry("line", atLine), entry("spent", { kind: "spent" })])).toBeUndefined();
543
- expect(roomiestAccount([entry("line", atLine), entry("low", { kind: "ready", room: 2 })])?.id).toBe("low");
579
+ expect(bestWithRoom([entry("line", atLine), entry("spent", { kind: "spent" })])).toBeUndefined();
580
+ expect(bestWithRoom([entry("line", atLine), entry("low", { kind: "ready", room: 2 })])?.id).toBe("low");
544
581
  });
545
582
 
546
583
  // The 2026-10-27/28 account: switched off, served for an evening (most room on its reading), switched off again.
@@ -548,9 +585,9 @@ test("an account its organisation keeps switching off goes behind every steady o
548
585
  const entry = (id: string, state: AccountState, flapping?: boolean) => ({ id, state, flapping });
549
586
  const flapping = entry("flapping", { kind: "ready", room: 90 }, true);
550
587
  expect(preferredAccount([flapping, entry("steady", { kind: "ready", room: 5 })])?.id).toBe("steady");
551
- expect(roomiestAccount([flapping, entry("steady", { kind: "ready", room: 5 }, false)])?.id).toBe("steady");
588
+ expect(bestWithRoom([flapping, entry("steady", { kind: "ready", room: 5 }, false)])?.id).toBe("steady");
552
589
  expect(preferredAccount([flapping, entry("unread", { kind: "unknown" }), entry("line", { kind: "ready", room: 0 })])?.id).toBe("flapping");
553
- expect(roomiestAccount([flapping, entry("line", { kind: "ready", room: 0 })])?.id).toBe("flapping");
590
+ expect(bestWithRoom([flapping, entry("line", { kind: "ready", room: 0 })])?.id).toBe("flapping");
554
591
  // Among flapping accounts, room decides again.
555
592
  expect(preferredAccount([flapping, entry("roomier", { kind: "ready", room: 95 }, true)])?.id).toBe("roomier");
556
593
  expect(preferredAccount([entry("off", { kind: "unknown" }, true), entry("on", { kind: "unknown" })])?.id).toBe("on");
@@ -588,8 +625,8 @@ test("an account whose only named pools are full, with models no pool covers, is
588
625
  test("a reading contradicted by an answered turn holds that model's full pools at the line, not spent", () => {
589
626
  const full = usage(window({ kind: "google:gemini-weekly", utilization: 100, resetsAt: 9_000, gates: { models: ["gemini"] } }));
590
627
  const contradicted: AccountUsage = { ...full, contradicted: { at: 1, model: "gemini-3.8-flash-high" } };
591
- expect(readingHeadroom(contradicted, { id: "gemini-3.8-flash-high" })).toEqual({ kind: "ready", room: 0 });
592
- expect(readingHeadroom(contradicted)).toEqual({ kind: "ready", room: 0 });
628
+ expect(readingHeadroom(contradicted, { id: "gemini-3.8-flash-high" })).toEqual({ kind: "ready", room: 0, renewsAt: 9_000 });
629
+ expect(readingHeadroom(contradicted)).toEqual({ kind: "ready", room: 0, renewsAt: 9_000 });
593
630
  // Another family's pool is not what the turn proved anything about.
594
631
  const other: AccountUsage = { ...full, contradicted: { at: 1, model: "claude-opus-4-6-thinking" } };
595
632
  expect(readingHeadroom(other, { id: "gemini-3.8-flash-high" })).toEqual({ kind: "spent", reopensAt: 9_000 });
@@ -645,7 +682,7 @@ test("a refusal's instant is judged against the pools a reading since publishes:
645
682
  const renewed = codex(Math.floor(now / 1000) + 6 * DAY);
646
683
  expect(refusedInstant(sol, renewed)).toBe("renewed");
647
684
  expect(refusalVerdict(sol, [{ account: "a", usage: renewed }], now)).toBe("answered");
648
- expect(serviceStates([{ account: "a", usage: renewed }], [sol], { id: "gpt-6.1-sol" }, now).get("a")).toEqual({ kind: "ready", room: 64 });
685
+ expect(serviceStates([{ account: "a", usage: renewed }], [sol], { id: "gpt-6.1-sol" }, now).get("a")).toEqual({ kind: "ready", room: 64, renewsAt: Math.floor(now / 1000) + 6 * DAY });
649
686
  // Renewed but already spent again: still held, by the window itself.
650
687
  expect(refusedInstant(sol, codex(Math.floor(now / 1000) + 6 * DAY, 100))).toBe("unpublished");
651
688
 
@@ -655,8 +692,8 @@ test("a refusal's instant is judged against the pools a reading since publishes:
655
692
  expect(refusedInstant(sol, unnamed)).toBe("unpublished");
656
693
  expect(refusalVerdict(sol, [{ account: "a", usage: unnamed }], now)).toBe("standing");
657
694
  expect(serviceState({ account: "a", usage: unnamed }, [sol], { id: "gpt-6.1-sol" }, now)).toEqual({ kind: "spent", reopensAt: instant, pool: "GPT 6.1 Sol" });
658
- expect(serviceState({ account: "a", usage: unnamed }, [sol], { id: "gpt-6-luna" }, now)).toEqual({ kind: "ready", room: 64 });
659
- expect(serviceState({ account: "a", usage: unnamed }, [sol], undefined, now)).toEqual({ kind: "ready", room: 64 });
695
+ expect(serviceState({ account: "a", usage: unnamed }, [sol], { id: "gpt-6-luna" }, now)).toEqual({ kind: "ready", room: 64, renewsAt: Math.floor(filed / 1000) + 5 * DAY });
696
+ expect(serviceState({ account: "a", usage: unnamed }, [sol], undefined, now)).toEqual({ kind: "ready", room: 64, renewsAt: Math.floor(filed / 1000) + 5 * DAY });
660
697
 
661
698
  // Nothing read since the refusal, or a pool with no reset to judge by: the instant outranks, on the pool the model spends.
662
699
  expect(refusedInstant(sol, { ...unnamed, measuredAt: filed - 1 })).toBe("unjudged");
@@ -109,6 +109,21 @@ const holdingPools = (full: readonly UsageWindow[], open: readonly UsageWindow[]
109
109
  return open.length === 0 ? full : [];
110
110
  };
111
111
 
112
+ /* WHEN AN ACCOUNT'S ALLOWANCE RENEWS, which is what a pick between accounts with room weighs first (preferredAccount).
113
+ What is left of a pool when it resets is gone: on 2026-11-17, with Claude's Ultra plan metering no five-hour window,
114
+ the pick kept every turn on the account with the most weekly room, resetting six days out, while another account's
115
+ 40% reset unspent ten hours later. The pool that decides is the longest the turn spends, since a shorter one refills
116
+ within the day whichever account is picked; among several of that length (Claude's weekly pool beside its weekly Opus
117
+ slice), the first to reset. Undefined where those publish no reset, or no pool names its length and none resets. */
118
+ export const renewalOf = (windows: readonly UsageWindow[]): number | undefined => {
119
+ const periods = windows.map((window) => windowPeriod(window)?.seconds);
120
+ const known = periods.filter((seconds) => seconds !== undefined);
121
+ const longest = known.length === 0 ? undefined : Math.max(...known);
122
+ const deciding = longest === undefined ? windows : windows.filter((_, index) => periods[index] === longest);
123
+ const resets = deciding.flatMap((window) => (window.resetsAt === undefined ? [] : [window.resetsAt]));
124
+ return resets.length === 0 ? undefined : Math.min(...resets);
125
+ };
126
+
112
127
  /**
113
128
  * What a reading says, at the contract's one spent line, never whether the account can serve: that is `serviceStates`,
114
129
  * which first lays every standing refusal on the reading (judgedReading). A provider that rounds its percentages (Claude
@@ -129,7 +144,9 @@ export const readingHeadroom = (usage: AccountUsage | undefined, model?: ModelRe
129
144
  const open = windows.filter((window) => !provenFull(window));
130
145
  const holding = holdingPools(full, open, model);
131
146
  if (holding.length === 0) {
132
- return { kind: "ready", room: Math.max(0, SPENT_UTILIZATION - Math.max(...open.map((window) => window.utilization))) };
147
+ const room = Math.max(0, SPENT_UTILIZATION - Math.max(...open.map((window) => window.utilization)));
148
+ const renewsAt = renewalOf(open);
149
+ return renewsAt === undefined ? { kind: "ready", room } : { kind: "ready", room, renewsAt };
133
150
  }
134
151
  const sliced = model === undefined && !holding.some((window) => window.gates === "all");
135
152
  // Every per-model slice this reading names is full, but it names none for some models the account serves: whether
@@ -361,20 +378,43 @@ const ranksAbove = (next: RankedAccount, best: RankedAccount): boolean => {
361
378
  if ((next.flapping === true) !== (best.flapping === true)) {
362
379
  return best.flapping === true;
363
380
  }
364
- return next.state.kind === "ready" && best.state.kind === "ready" && next.state.room > best.state.room;
381
+ return next.state.kind === "ready" && best.state.kind === "ready" && readyAbove(next.state, best.state);
382
+ };
383
+
384
+ /** Room at or below this, in points of the fullest pool, is an account nearly out: it ranks after every one with more. */
385
+ export const NEARLY_OUT_ROOM = 10;
386
+
387
+ /* BETWEEN TWO ACCOUNTS WITH ROOM, THE ONE WHOSE ALLOWANCE RENEWS FIRST (renewalOf), unless it is nearly out. Points left
388
+ in a pool at its reset are lost, so spending the pool that resets first wastes the least of what the plans pay for,
389
+ and the later one is still there when the first has renewed. Most room decides only between accounts renewing at the
390
+ same moment, between accounts no reset is known for, and among accounts nearly out, where room is what keeps the next
391
+ turn from being refused. This reads no load: the daemon's own Claude pick (budget-planner.ts pickAccount) orders the
392
+ same way among the accounts its projection says carry the turn with what already runs on them. */
393
+ const readyAbove = (next: AccountState & { kind: "ready" }, best: AccountState & { kind: "ready" }): boolean => {
394
+ const nextOpen = next.room > NEARLY_OUT_ROOM;
395
+ if (nextOpen !== best.room > NEARLY_OUT_ROOM) {
396
+ return nextOpen;
397
+ }
398
+ const nextRenews = next.renewsAt ?? Number.POSITIVE_INFINITY;
399
+ const bestRenews = best.renewsAt ?? Number.POSITIVE_INFINITY;
400
+ if (nextOpen && nextRenews !== bestRenews) {
401
+ return nextRenews < bestRenews;
402
+ }
403
+ return next.room > best.room;
365
404
  };
366
405
 
367
406
  /**
368
- * The account an unnamed turn runs on: ready by most room, then unmeasured, then at the line, then spent, blocked only
369
- * when that is all there is; within each, a flapping account after the steady ones. Ties keep the caller's order.
407
+ * The account an unnamed turn runs on: ready, then unmeasured, then at the line, then spent, blocked only when that is
408
+ * all there is; within each, a flapping account after the steady ones; among ready ones, the first to renew of those not
409
+ * nearly out, then the most room (readyAbove). Ties keep the caller's order.
370
410
  */
371
411
  export const preferredAccount = <T extends RankedAccount>(entries: readonly T[]): T | undefined =>
372
412
  entries.reduce<T | undefined>((best, next) => (best === undefined || ranksAbove(next, best) ? next : best), undefined);
373
413
 
374
414
  /**
375
- * The roomiest account with proven room, or none: what a move off a refused account may land on. Ties keep the caller's
376
- * order. An account at the line is left out: a move there could be refused in turn, and two such accounts would hand the
377
- * turn back and forth.
415
+ * The best account with proven room, by the same order, or none: what a move off a refused account may land on. Ties keep
416
+ * the caller's order. An account at the line is left out: a move there could be refused in turn, and two such accounts
417
+ * would hand the turn back and forth.
378
418
  */
379
- export const roomiestAccount = <T extends RankedAccount>(entries: readonly T[]): T | undefined =>
419
+ export const bestWithRoom = <T extends RankedAccount>(entries: readonly T[]): T | undefined =>
380
420
  preferredAccount(entries.filter((entry) => entry.state.kind === "ready" && entry.state.room > 0));
@@ -30,7 +30,7 @@ const listed = (list: readonly string[] | undefined, id: string): boolean => lis
30
30
 
31
31
  /**
32
32
  * Whether a persona carrying these accounts (its `capabilities`) and these shelves may act through a capability. A kind
33
- * absent from the switch (an agent runtime, a devops entry, a VPN) passes untouched, so a new kind is never silently
33
+ * absent from the switch (an agent runtime, a VPN) passes untouched, so a new kind is never silently
34
34
  * denied.
35
35
  */
36
36
  export const personaAllowsCapability = (capability: CapabilityRef, accounts: readonly string[], shelves: PersonaShelves): boolean => {
@@ -173,6 +173,9 @@ export const RunnerFactsSchema = z.object({
173
173
  // Absent where the kernel does not report it.
174
174
  cpuPressure: z.number().nonnegative().optional(),
175
175
  memoryStall: z.number().nonnegative().optional(),
176
+ // The GPUs a program there can use (passed through to the container), by name and memory; empty where there is none,
177
+ // absent from a runner that predates the question. What a heavy command that needs one is placed by.
178
+ gpus: z.array(z.object({ name: z.string(), memoryMb: z.number().int().nonnegative() })).optional(),
176
179
  });
177
180
  export type RunnerFacts = z.infer<typeof RunnerFactsSchema>;
178
181
 
@@ -291,6 +294,18 @@ export const OFFLOAD_REF_PREFIX = "refs/intentic-offload/";
291
294
  export const offloadRef = (runId: string): string => `${OFFLOAD_REF_PREFIX}${runId}`;
292
295
  const OffloadRunIdSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{7,63}$/u);
293
296
  const EnvNameSchema = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u);
297
+ const Sha256Schema = z.string().regex(/^[0-9a-f]{64}$/u);
298
+
299
+ // A path an offloaded line makes that its caller needs back besides edits: a binary it built, a picture it rendered.
300
+ // Repo-relative, ignored paths included (`target/debug/integra`), or absolute under /tmp; a directory brings back every
301
+ // file under it. Never anywhere else on the runner, and never out of the repo by `..`.
302
+ export const OffloadOutputPathSchema = z
303
+ .string()
304
+ .min(1)
305
+ .max(1024)
306
+ .refine((path) => !path.split("/").includes(".."), "must not climb out by ..")
307
+ .refine((path) => !path.startsWith("/") || path.startsWith("/tmp/"), "an absolute output must be under /tmp/");
308
+ export const isTmpOutput = (path: string): boolean => path.startsWith("/tmp/");
294
309
 
295
310
  export const RunnerCommandSchema = z.object({
296
311
  runId: OffloadRunIdSchema,
@@ -306,6 +321,11 @@ export const RunnerCommandSchema = z.object({
306
321
  // Variables the line writes a file to (a report path): the runner points each at a scratch file and hands the file
307
322
  // back with the exit.
308
323
  exports: z.array(EnvNameSchema).max(8).default([]),
324
+ // Paths the line makes that come back whole, as `file` frames before the exit (OffloadOutputPathSchema).
325
+ outputs: z.array(OffloadOutputPathSchema).max(16).default([]),
326
+ // What the caller already holds at an output path (a directory's files by their own paths), by sha256: a file the
327
+ // same byte for byte is said, not sent.
328
+ have: z.record(z.string(), Sha256Schema).default({}),
309
329
  // The heavy-command rule it matched here, named in the runner's own output and queue.
310
330
  label: z.string().min(1).max(80),
311
331
  timeoutMs: z
@@ -317,12 +337,25 @@ export const RunnerCommandSchema = z.object({
317
337
  });
318
338
  export type RunnerCommand = z.infer<typeof RunnerCommandSchema>;
319
339
 
340
+ // One output file coming back, in pieces sent in order: each `data` is one gzip member of the next bytes, base64, and
341
+ // the last piece carries `end` with the whole file's size, mode and sha256, which the caller checks before it puts the
342
+ // file in place. `same` instead of data says the caller already holds it byte for byte.
343
+ export const RunnerFileFrameSchema = z.object({
344
+ kind: z.literal("file"),
345
+ path: z.string().min(1),
346
+ data: z.string().optional(),
347
+ end: z.object({ size: z.number().int().nonnegative(), mode: z.number().int().nonnegative(), sha256: Sha256Schema }).optional(),
348
+ same: z.boolean().optional(),
349
+ });
350
+ export type RunnerFileFrame = z.infer<typeof RunnerFileFrameSchema>;
351
+
320
352
  // What a running command streams back: narration of the runner's own steps (fetch, install, queue), the line's output
321
- // as it comes, and last its end: the exit, every file it changed as a binary git patch against the snapshot, and the
322
- // exported files, base64.
353
+ // as it comes, the output files asked for, and last its end: the exit, every file it changed as a binary git patch
354
+ // against the snapshot, and the exported files, base64.
323
355
  export const RunnerCommandFrameSchema = z.union([
324
356
  z.object({ kind: z.literal("status"), text: z.string() }),
325
357
  z.object({ kind: z.literal("output"), stream: z.enum(["stdout", "stderr"]), text: z.string() }),
358
+ RunnerFileFrameSchema,
326
359
  z.object({
327
360
  kind: z.literal("exit"),
328
361
  code: z.number().int(),
@@ -333,6 +366,13 @@ export const RunnerCommandFrameSchema = z.union([
333
366
  ran: z.boolean().default(true),
334
367
  patchBase64: z.string().optional(),
335
368
  files: z.record(EnvNameSchema, z.string()).default({}),
369
+ // How heavy the line was there, for the parent's command profiles (offload/command-profiles.ts): the most
370
+ // memory everything it started held at once, and how long it ran. Absent where the runner could not measure.
371
+ peakMemoryMb: z.number().int().nonnegative().optional(),
372
+ durationMs: z.number().int().nonnegative().optional(),
373
+ // Outputs asked for that the line never made, and ones too big to bring back.
374
+ missing: z.array(z.string()).optional(),
375
+ tooBig: z.array(z.string()).optional(),
336
376
  }),
337
377
  ]);
338
378
  export type RunnerCommandFrame = z.infer<typeof RunnerCommandFrameSchema>;
@@ -0,0 +1,51 @@
1
+ import { generateKeyPairSync } from "node:crypto";
2
+ import { mintIdentityAssertion, verifyIdentityAssertion } from "../../policy/identity-assertion.js";
3
+ import { isSandboxPass, mintSandboxPass, SANDBOX_PASS_MAX_TTL_MS, SANDBOX_PASS_TTL_MS, verifySandboxPass } from "./sandbox-pass.js";
4
+
5
+ const pemPair = (): { privateKey: string; publicKey: string } =>
6
+ generateKeyPairSync("ed25519", { publicKeyEncoding: { type: "spki", format: "pem" }, privateKeyEncoding: { type: "pkcs8", format: "pem" } });
7
+ const { privateKey: privatePem, publicKey: publicPem } = pemPair();
8
+ const NOW = 1_800_000_000_000;
9
+ const A = "0123456789ab";
10
+ const B = "ba9876543210";
11
+
12
+ const mint = (overrides: Partial<Parameters<typeof mintSandboxPass>[1]> = {}): string =>
13
+ mintSandboxPass(privatePem, { from: A, fromName: "ops", to: B, project: "github.com/acme/app", issuedAtMs: NOW, ...overrides });
14
+
15
+ describe("sandbox pass", () => {
16
+ it("round-trips the claim and expires when it says", () => {
17
+ const pass = mint();
18
+ expect(isSandboxPass(pass)).toBe(true);
19
+ expect(verifySandboxPass(publicPem, pass, NOW + 1_000)).toEqual({
20
+ from: A,
21
+ fromName: "ops",
22
+ to: B,
23
+ project: "github.com/acme/app",
24
+ issuedAt: NOW / 1000,
25
+ expiresAt: (NOW + SANDBOX_PASS_TTL_MS) / 1000,
26
+ });
27
+ expect(verifySandboxPass(publicPem, pass, NOW + SANDBOX_PASS_TTL_MS)).toBeUndefined();
28
+ });
29
+
30
+ it("refuses another key, a tampered payload, and a claim from the future", () => {
31
+ expect(verifySandboxPass(pemPair().publicKey, mint(), NOW)).toBeUndefined();
32
+ const [prefix, payload, signature] = mint().split(".");
33
+ const forged = Buffer.from(Buffer.from(payload ?? "", "base64url").toString("utf8").replace(B, A.replace("0", "f")), "utf8").toString("base64url");
34
+ expect(verifySandboxPass(publicPem, `${prefix}.${forged}.${signature}`, NOW)).toBeUndefined();
35
+ expect(verifySandboxPass(publicPem, mint({ issuedAtMs: NOW + 120_000 }), NOW)).toBeUndefined();
36
+ });
37
+
38
+ it("is never an identity assertion, nor the reverse, under the same key", () => {
39
+ const pass = mint();
40
+ expect(verifyIdentityAssertion(publicPem, pass, NOW)).toBeUndefined();
41
+ const assertion = mintIdentityAssertion(privatePem, { sandboxId: B, email: "a@b.org", method: "email", issuedAtMs: NOW });
42
+ expect(verifySandboxPass(publicPem, assertion, NOW)).toBeUndefined();
43
+ expect(verifySandboxPass(publicPem, assertion.replace(/^pa1/, "sp1"), NOW)).toBeUndefined();
44
+ });
45
+
46
+ it("refuses to mint a pass to itself or one that lives too long", () => {
47
+ expect(() => mint({ to: A })).toThrow();
48
+ expect(() => mint({ ttlMs: SANDBOX_PASS_MAX_TTL_MS + 1 })).toThrow();
49
+ expect(() => mint({ project: " " })).toThrow();
50
+ });
51
+ });
@@ -0,0 +1,119 @@
1
+ import { createPrivateKey, createPublicKey, randomBytes, sign as edSign, verify as edVerify } from "node:crypto";
2
+ import { parseJsonWith } from "@intentic/base/json";
3
+ import { z } from "zod";
4
+ import { SANDBOX_ID } from "../../ids/tunnel-ids.js";
5
+
6
+ // The platform's signed word that one sandbox may report to another ON THE SAME ACCOUNT about one project: the
7
+ // credential behind account-level report routing. The sending daemon asks the platform who owns a project
8
+ // (`projectResolve`, authenticated by its connect token, so `from` is the platform's own reading, never the sender's
9
+ // claim); the platform answers with the owner's address and this pass; the receiving daemon checks it against the
10
+ // platform's identity key it already holds (the announce answer's `identityKey`). Signed with the same key as the
11
+ // identity assertion, under its own prefix, so neither can ever stand in for the other.
12
+
13
+ const PASS_PREFIX = "sp1";
14
+
15
+ // Long enough for an outbox to drain a few reports through one resolve; short enough that a lifted pass is soon dead.
16
+ export const SANDBOX_PASS_TTL_MS = 10 * 60_000;
17
+ // What a daemon accepts whatever the claim says, so a platform minting with a wrong ttl cannot hand out a long credential.
18
+ export const SANDBOX_PASS_MAX_TTL_MS = 15 * 60_000;
19
+
20
+ // The header a pass rides on the receiving daemon's `/account/` routes.
21
+ export const SANDBOX_PASS_HEADER = "x-intentic-sandbox-pass";
22
+
23
+ export interface SandboxPass {
24
+ // The sending sandbox's tunnel id, and the name its owner gave it (for the inbox; display only).
25
+ readonly from: string;
26
+ readonly fromName: string;
27
+ // The receiving sandbox's tunnel id: a daemon refuses a pass addressed to anyone else.
28
+ readonly to: string;
29
+ // The normalized project id the receiver claims (project-id.ts).
30
+ readonly project: string;
31
+ readonly issuedAt: number;
32
+ readonly expiresAt: number;
33
+ }
34
+
35
+ const base64url = (bytes: Buffer): string => bytes.toString("base64url");
36
+
37
+ // The prefix is part of what is signed: a pass is never a valid signature over an identity assertion, nor the reverse.
38
+ const signedBytes = (payload: Buffer): Buffer => Buffer.concat([Buffer.from(`${PASS_PREFIX}.`, "utf8"), payload]);
39
+
40
+ export const isSandboxPass = (token: string): boolean => token.startsWith(`${PASS_PREFIX}.`);
41
+
42
+ export const mintSandboxPass = (
43
+ privateKeyPem: string,
44
+ claim: {
45
+ readonly from: string;
46
+ readonly fromName: string;
47
+ readonly to: string;
48
+ readonly project: string;
49
+ readonly issuedAtMs: number;
50
+ readonly ttlMs?: number;
51
+ },
52
+ ): string => {
53
+ if (!SANDBOX_ID.test(claim.from) || !SANDBOX_ID.test(claim.to)) {
54
+ throw new Error("a sandbox pass names two 12-hex sandbox ids");
55
+ }
56
+ if (claim.from === claim.to) {
57
+ throw new Error("a sandbox pass is from one sandbox to another");
58
+ }
59
+ if (claim.project.trim() === "") {
60
+ throw new Error("a sandbox pass names a project");
61
+ }
62
+ const ttlMs = claim.ttlMs ?? SANDBOX_PASS_TTL_MS;
63
+ if (ttlMs <= 0 || ttlMs > SANDBOX_PASS_MAX_TTL_MS) {
64
+ throw new Error(`a sandbox pass lives at most ${SANDBOX_PASS_MAX_TTL_MS} ms`);
65
+ }
66
+ const payload = Buffer.from(
67
+ JSON.stringify({
68
+ v: 1,
69
+ iss: claim.from,
70
+ name: claim.fromName.slice(0, 120),
71
+ aud: claim.to,
72
+ prj: claim.project,
73
+ iat: Math.floor(claim.issuedAtMs / 1000),
74
+ exp: Math.floor((claim.issuedAtMs + ttlMs) / 1000),
75
+ jti: base64url(randomBytes(12)),
76
+ }),
77
+ "utf8",
78
+ );
79
+ const signature = edSign(null, signedBytes(payload), createPrivateKey(privateKeyPem));
80
+ return `${PASS_PREFIX}.${base64url(payload)}.${base64url(signature)}`;
81
+ };
82
+
83
+ const PassPayloadSchema = z.object({
84
+ v: z.literal(1),
85
+ iss: z.string().regex(SANDBOX_ID),
86
+ name: z.string(),
87
+ aud: z.string().regex(SANDBOX_ID),
88
+ prj: z.string().min(1),
89
+ iat: z.number(),
90
+ exp: z.number(),
91
+ jti: z.string().min(1),
92
+ });
93
+
94
+ // Verifies a pass against the platform's public key at nowMs; undefined for any way of being invalid (wrong prefix, bad
95
+ // signature, malformed claim, expired, issued in the future, living longer than allowed). The caller checks `to`
96
+ // against its own id and `project` against its own claims.
97
+ export const verifySandboxPass = (publicKeyPem: string, token: string, nowMs: number): SandboxPass | undefined => {
98
+ const [prefix, encodedPayload, encodedSignature, ...rest] = token.split(".");
99
+ if (prefix !== PASS_PREFIX || encodedPayload === undefined || encodedSignature === undefined || rest.length > 0) {
100
+ return undefined;
101
+ }
102
+ const payload = Buffer.from(encodedPayload, "base64url");
103
+ try {
104
+ if (!edVerify(null, signedBytes(payload), createPublicKey(publicKeyPem), Buffer.from(encodedSignature, "base64url"))) {
105
+ return undefined;
106
+ }
107
+ } catch {
108
+ // allow(silent-catch): a key or signature that does not parse verifies nothing: the pass is invalid, said as undefined.
109
+ return undefined;
110
+ }
111
+ const claim = parseJsonWith(payload.toString("utf8"), PassPayloadSchema);
112
+ if (claim === undefined || claim.iss === claim.aud) {
113
+ return undefined;
114
+ }
115
+ if (claim.exp * 1000 <= nowMs || claim.iat * 1000 > nowMs + 60_000 || (claim.exp - claim.iat) * 1000 > SANDBOX_PASS_MAX_TTL_MS) {
116
+ return undefined;
117
+ }
118
+ return { from: claim.iss, fromName: claim.name, to: claim.aud, project: claim.prj, issuedAt: claim.iat, expiresAt: claim.exp };
119
+ };
@@ -4,8 +4,8 @@
4
4
  export const REQUEST_ID_HEADER = "x-intentic-request-id";
5
5
 
6
6
  // The header a sandbox's connect token travels in: the platform's routes a sandbox calls as itself
7
- // (api-contract's PLATFORM_INGRESS), the daemon's own gate, which takes the token from `ic` and the owner's browser,
8
- // and its `/enroll`. `ic` spells it in Rust; api-contract's ingress test holds that spelling to this value.
7
+ // (api-contract's PLATFORM_INGRESS) and the daemon's own gate, which takes the token from `ic` and the owner's
8
+ // browser. `ic` spells it in Rust; api-contract's ingress test holds that spelling to this value.
9
9
  export const CONNECT_TOKEN_HEADER = "x-intentic-connect";
10
10
 
11
11
  // The header an extension's backend and its processes present their per-extension token in, checked against the
@@ -143,7 +143,6 @@ describe("memberRefusal for a person given part of the sandbox", () => {
143
143
  expect(memberRefusal(maintainer, "GET", "/members")).toBeUndefined();
144
144
  expect(memberRefusal(maintainer, "POST", "/privacy/reveal")).toBeUndefined();
145
145
  expect(memberRefusal(maintainer, "POST", "/settings/agent-domain")).toBeUndefined();
146
- expect(memberRefusal(maintainer, "POST", "/system/enroll/code")).toBeUndefined();
147
146
  expect(memberRefusal(maintainer, "POST", "/system/passkeys/policy")).toMatchObject({ floor: "owner" });
148
147
  expect(memberRefusal(maintainer, "POST", "/platform/relink")).toMatchObject({ floor: "owner" });
149
148
  });
@@ -37,7 +37,7 @@ import {
37
37
  PhonePasswordsPairSchema,
38
38
  } from "../../schemas/phone-passwords.js";
39
39
  import { OkSchema } from "../../schemas/shared.js";
40
- import { EnrollCodeAnswerSchema, EnrollCodeRequestSchema, PeerPairingAnswerSchema, SyncPairAnswerSchema, SyncPairRequestSchema } from "../../schemas/short-codes.js";
40
+ import { PeerPairingAnswerSchema, SyncPairAnswerSchema, SyncPairRequestSchema } from "../../schemas/short-codes.js";
41
41
  import { SpeechStatusSchema, SpeechTranscriptSchema, SpeechWakeClaimSchema, SpeechWakeGrantSchema } from "../../schemas/speech.js";
42
42
  import {
43
43
  AuthenticationOptionsSchema,
@@ -74,6 +74,14 @@ import {
74
74
  LinkWriteAnswerSchema,
75
75
  LinkWriteSchema,
76
76
  } from "../../schemas/links.js";
77
+ import {
78
+ AccountOutboxSchema,
79
+ AccountProjectsSchema,
80
+ AccountReportSchema,
81
+ AccountSendOutcomeSchema,
82
+ AccountSendSchema,
83
+ IssueAcceptedSchema,
84
+ } from "../../schemas/issues.js";
77
85
  import { UploadManifestSchema, UploadSkipSchema } from "../../schemas/workspace/workspace-upload.js";
78
86
  import {
79
87
  ArrivalAbandonedSchema,
@@ -111,7 +119,6 @@ export const RAW_JSON_ROUTES = {
111
119
  // The voices a sandbox speaks with, for the Voice settings (schemas/voice.ts).
112
120
  "GET /speech/voices": { output: VoicesViewSchema },
113
121
  // A server-connect code for the owner's command (short-codes.ts).
114
- "POST /system/enroll/code": { input: EnrollCodeRequestSchema, output: EnrollCodeAnswerSchema },
115
122
  // The roster is ownership's; every write answers the roster after it.
116
123
  "GET /members": { output: MembersRosterSchema },
117
124
  "POST /members": { input: MemberGrantSchema, output: MembersListSchema },
@@ -185,6 +192,11 @@ export const RAW_JSON_ROUTES = {
185
192
  "POST /system/links/{id}": { input: InboundLinkTermsUpdateSchema, output: InboundLinkSummarySchema },
186
193
  "DELETE /system/links/{id}": { output: OkSchema },
187
194
  "POST /system/links/{id}/requests/{request}": { input: LinkRequestDecisionSchema, output: InboundLinkSummarySchema },
195
+ // Another sandbox on the owner's account reporting a problem about a project this one claims (schemas/issues.ts).
196
+ "POST /account/report": { input: AccountReportSchema, output: IssueAcceptedSchema },
197
+ "POST /account/outbox": { input: AccountSendSchema, output: AccountSendOutcomeSchema },
198
+ "GET /account/outbox": { output: AccountOutboxSchema },
199
+ "GET /account/projects": { output: AccountProjectsSchema },
188
200
  // The link doors, as the asking sandbox's daemon reads them. A status takes `?after=<version>&wait=<seconds>` to
189
201
  // be held until it moves past that version.
190
202
  "GET /link": { output: LinkHelloSchema },
@@ -66,11 +66,6 @@ export const RAW_ROUTES = {
66
66
  "GET /system/browser-view": { auth: "door", beforeBoot: true, control: "never" },
67
67
  // The sandbox's own desktop, watched and driven by the owner (desktop/desktop-view.ts); the same query ticket.
68
68
  "GET /system/desktop-view": { auth: "door", beforeBoot: true, control: "never" },
69
- // Deploy-target enrollment, gated by the connect token.
70
- "POST /enroll": { auth: "door", control: "never" },
71
- // A server-connect code for the command that connects a server: its single-use enroll token stands in for the connect
72
- // token. Anybody who operates the sandbox may connect a server to it.
73
- "POST /system/enroll/code": { control: "never" },
74
69
  // An event automation's webhook, gated by the automation's own token.
75
70
  "POST /automations/{id}/fire": { auth: "door" },
76
71
  // The release gate a pipeline runner waits on, gated by the workflow's minted gate token.
@@ -180,6 +175,11 @@ export const RAW_ROUTES = {
180
175
  // The `devices push` CLI: a program the agent built, carried to one of the owner's computers in chunks; held to the
181
176
  // devices the calling conversation's turn mounts, and refused by the machine itself unless "Run programs" is on.
182
177
  "POST /devices/{name}/artifacts": { agent: true, control: "never" },
178
+ // The `devices copy` CLI: a file or a folder carried to a path on one of the owner's computers, or back off it, in
179
+ // chunks (hosts/device-files.routes.ts); held to the same rule, and the machine holds each chunk to its folders and,
180
+ // onto it, its "Create and change files" switch.
181
+ "POST /devices/{name}/files": { agent: true, control: "never" },
182
+ "GET /devices/{name}/files": { agent: true, control: "never" },
183
183
  // The rest of the `devices` command, held to the same rule (hosts/device-door.routes.ts): the device's app_start for a
184
184
  // shell, and its loopback ports reached from the sandbox (hosts/device-tunnels.ts).
185
185
  "POST /devices/{name}/apps": { agent: true, control: "never" },
@@ -299,6 +299,15 @@ export const RAW_ROUTES = {
299
299
  "POST /system/links/{id}": { control: "never" },
300
300
  "DELETE /system/links/{id}": { control: "never" },
301
301
  "POST /system/links/{id}/requests/{request}": { control: "never" },
302
+ // Account-level report routing: another sandbox on the owner's account reporting a problem about a project this one
303
+ // claims. Checked in the handler against a pass the platform signed (policy/sandbox-pass.ts); it only ever records
304
+ // into the issues inbox, and wakes an agent only as the inbox's own escalation rule says.
305
+ "POST /account/report": { auth: "door", control: "never" },
306
+ // The sending side, for the `projects` command on the agent's PATH: report a problem to whichever sandbox claims a
307
+ // project (delivered now or kept in the outbox), what is still waiting, and the projects this sandbox claims.
308
+ "POST /account/outbox": { agent: true, control: "never" },
309
+ "GET /account/outbox": { agent: true, control: "never" },
310
+ "GET /account/projects": { agent: true, control: "never" },
302
311
  // The link doors, called by the asking sandbox's daemon: each checks the link token itself (x-intentic-link) and
303
312
  // reaches only the conversations that link opened, which is the whole of a link's reach.
304
313
  "GET /link": { auth: "door", control: "never" },