toolroll 0.9.109 → 0.9.110

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 (135) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/agent-detect.js +244 -0
  3. package/dist/agent-fence.js +12 -1
  4. package/dist/agentconfig.js +2 -2
  5. package/dist/approval-summary.js +344 -0
  6. package/dist/attest.js +2 -2
  7. package/dist/browser/workspace.css +2 -2
  8. package/dist/browser/workspace.js +27 -27
  9. package/dist/builder.js +36 -2
  10. package/dist/chat-actions.js +24 -17
  11. package/dist/chat-core.js +3 -1
  12. package/dist/chat-decide.js +101 -46
  13. package/dist/chat-delivery-state.js +2 -0
  14. package/dist/chat-delivery.js +3 -2
  15. package/dist/chat-live.js +2 -1
  16. package/dist/chat-task-actions.js +6 -0
  17. package/dist/check-report.js +1 -1
  18. package/dist/cli.js +2 -0
  19. package/dist/console-instance.js +10 -1
  20. package/dist/contracts/console-api.js +10 -5
  21. package/dist/contracts/engine-api.js +271 -0
  22. package/dist/coordinator.js +2 -2
  23. package/dist/discord-api.js +4 -3
  24. package/dist/discord-chat.js +3 -1
  25. package/dist/easy-start-args.js +7 -3
  26. package/dist/easy-start.js +25 -0
  27. package/dist/egress.js +72 -10
  28. package/dist/engine-handoff.js +34 -0
  29. package/dist/engine-reads.js +261 -0
  30. package/dist/eval-world.js +3 -2
  31. package/dist/evidence.js +2 -0
  32. package/dist/fast-start.js +55 -14
  33. package/dist/fast-terms.js +2 -2
  34. package/dist/first-run.js +10 -2
  35. package/dist/flexible-agents.js +234 -0
  36. package/dist/flexible-answers-schema.js +61 -0
  37. package/dist/flexible-answers.js +889 -0
  38. package/dist/flexible-custody.js +494 -0
  39. package/dist/flexible-import.js +782 -0
  40. package/dist/flexible-launch-schema.js +72 -0
  41. package/dist/flexible-launch.js +331 -0
  42. package/dist/flexible-launcher.js +88 -0
  43. package/dist/flexible-levels.js +34 -0
  44. package/dist/flexible-merge-guard.js +47 -0
  45. package/dist/flexible-refs.js +47 -0
  46. package/dist/flexible-relay-cancel.js +19 -0
  47. package/dist/flexible-relay-schema.js +55 -0
  48. package/dist/flexible-relay-upstreams.js +36 -0
  49. package/dist/flexible-relay.js +1032 -0
  50. package/dist/flexible-session.js +732 -0
  51. package/dist/flexible-ship-schema.js +81 -0
  52. package/dist/flexible-ship.js +694 -0
  53. package/dist/flexible-start.js +80 -0
  54. package/dist/flexible-thread.js +175 -25
  55. package/dist/flexible-turns-schema.js +69 -0
  56. package/dist/flexible-turns.js +490 -0
  57. package/dist/flexible.js +10 -1
  58. package/dist/flow-actions.js +6 -4
  59. package/dist/flow-steps.js +1 -1
  60. package/dist/flows-cli.js +2 -1
  61. package/dist/git-views.js +6 -3
  62. package/dist/install-mode.js +225 -0
  63. package/dist/lead-doors.js +7 -1
  64. package/dist/limits-ui.js +7 -0
  65. package/dist/live-reply.js +6 -0
  66. package/dist/live-terminal.js +425 -29
  67. package/dist/local-owner.js +6 -0
  68. package/dist/model-choices.js +12 -6
  69. package/dist/notification-delivery.js +11 -0
  70. package/dist/operate.js +74 -30
  71. package/dist/outbound-privacy.js +204 -0
  72. package/dist/passwordless.js +2 -1
  73. package/dist/project-delete.js +14 -0
  74. package/dist/provider-connection.js +5 -3
  75. package/dist/publish.js +5 -0
  76. package/dist/pull-request-flow.js +26 -7
  77. package/dist/push.js +5 -1
  78. package/dist/release-card.js +11 -3
  79. package/dist/release.js +10 -1
  80. package/dist/route-store.js +2 -2
  81. package/dist/sandbox-launch.js +32 -8
  82. package/dist/sandbox-runtime.js +16 -7
  83. package/dist/sandbox-tools.js +176 -0
  84. package/dist/scope.js +12 -36
  85. package/dist/scout-net.js +7 -2
  86. package/dist/serve.js +58 -11
  87. package/dist/server/chrome.js +3 -1
  88. package/dist/server/console.css +33 -6
  89. package/dist/server/engine-api.js +378 -0
  90. package/dist/server/flows.js +2 -2
  91. package/dist/server/http.js +7 -0
  92. package/dist/server/link-redemption.js +52 -0
  93. package/dist/server/mutation-key.js +21 -7
  94. package/dist/server/pages.js +69 -40
  95. package/dist/server/people-tokens.js +17 -41
  96. package/dist/server/render-chat.js +1 -0
  97. package/dist/server/render-new-task.js +3 -3
  98. package/dist/server/render-results.js +4 -4
  99. package/dist/server/render-tasks.js +129 -138
  100. package/dist/server/route-table.js +30 -1
  101. package/dist/server/settings-section-table.js +3 -0
  102. package/dist/server/settings-sections.js +33 -0
  103. package/dist/server/settings.js +84 -10
  104. package/dist/server/task-views.js +8 -2
  105. package/dist/server/tasks.js +25 -8
  106. package/dist/server/terminals.js +181 -28
  107. package/dist/server/welcome.js +35 -10
  108. package/dist/settings-groups-ui.js +2 -2
  109. package/dist/settings-proofs.js +13 -9
  110. package/dist/slack-api.js +4 -3
  111. package/dist/slack-chat.js +5 -3
  112. package/dist/spend.js +46 -12
  113. package/dist/status-probe.js +343 -0
  114. package/dist/store.js +102 -5
  115. package/dist/teams-api.js +4 -3
  116. package/dist/teams-chat.js +4 -2
  117. package/dist/telegram-lead.js +2 -1
  118. package/dist/telegram-live.js +2 -1
  119. package/dist/telegram-team.js +2 -1
  120. package/dist/telegram.js +17 -5
  121. package/dist/trusted-path.js +162 -0
  122. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  123. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  124. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  125. package/dist/tui/linux-x64/toolroll-tui +0 -0
  126. package/dist/tui-launch.js +282 -0
  127. package/dist/tui-source.js +5 -3
  128. package/dist/tui.js +1 -1
  129. package/dist/webhooks.js +8 -4
  130. package/dist/welcome-facts.js +22 -15
  131. package/dist/workspace-ui.js +5 -0
  132. package/package.json +1 -1
  133. package/scripts/crash-canary.mjs +1 -1
  134. package/scripts/pilot.mjs +1 -1
  135. package/scripts/provider-canary.mjs +5 -3
@@ -0,0 +1,80 @@
1
+ import { createHash } from "node:crypto";
2
+ import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
3
+ import { FLEXIBLE_LAPSE_WORDS, FLEXIBLE_LEVEL_WORDS, FLEXIBLE_UNAVAILABLE, flexibleStanding, FULL_ACCESS_WORDS, OPEN_NETWORK_WORDS } from "./flexible.js";
4
+ import { flexibleNetworkDigest, flexibleThreadNetwork } from "./flexible-launcher.js";
5
+ import { flexibleRelayBilling } from "./flexible-relay.js";
6
+ import { networkWords } from "./egress.js";
7
+ import { agentModelName } from "./model-names.js";
8
+ import { CLAUDE_EXACT } from "./model-catalog.js";
9
+ export const FLEXIBLE_DEFAULT_MODEL = CLAUDE_EXACT.find(one => one.value.startsWith("claude-sonnet-"))?.value ?? "claude-sonnet-5-5";
10
+ const RELAY_MODEL = /^claude-(?:opus|sonnet|haiku|fable)-\d{1,2}(?:-\d{1,2})?(?:-\d{8})?$/;
11
+ const WORDS = Object.freeze({
12
+ "not-available": FLEXIBLE_UNAVAILABLE,
13
+ "invalid-request": "That isn't a thread Toolroll can start: name a project and a Claude model. Nothing was started.",
14
+ "not-flexible": "This project isn't Flexible, so threads can't start in it. Nothing was started.",
15
+ "terms-unreadable": "This project's Flexible terms can't be read, so they allow nothing. Nothing was started.",
16
+ "not-a-starter": "These terms don't let you start threads in this project. Nothing was started.",
17
+ "no-sign-in": "Toolroll holds no Claude sign-in for Flexible threads yet, so no thread can start. Nothing was started.",
18
+ });
19
+ const refuse = (reason) => ({ ok: false, reason, message: WORDS[reason] });
20
+ const money = (micro) => `$${(micro / 1_000_000).toFixed(2)}`;
21
+ const plural = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
22
+ const lowerFirst = (text) => text.charAt(0).toLowerCase() + text.slice(1);
23
+ export const FLEXIBLE_SHIP_WORDS = "One press. Toolroll merges only when the project's required check passes on that exact commit. A failed or missing check never merges, there is no merge anyway, and any change to the commit cancels it.";
24
+ export const FLEXIBLE_UNKNOWN_COST_WORDS = "If Toolroll can't measure what a turn on an API key cost, that turn holds the monthly budgets it counts toward until the month ends, and a daily dollar limit until the next day (UTC).";
25
+ export function flexibleStartCard(store, input) {
26
+ if (!FLEXIBLE_AVAILABLE)
27
+ return refuse("not-available");
28
+ const model = input.model === null || input.model === "" ? FLEXIBLE_DEFAULT_MODEL : input.model;
29
+ if (typeof input.repo !== "string" || input.repo === "" || typeof model !== "string" || !RELAY_MODEL.test(model) || typeof input.message !== "string"
30
+ || typeof input.by?.name !== "string" || !Number.isSafeInteger(input.by.generation))
31
+ return refuse("invalid-request");
32
+ const standing = flexibleStanding(store, input.repo);
33
+ if (standing.state === "secure")
34
+ return refuse("not-flexible");
35
+ if (standing.state === "unreadable")
36
+ return refuse("terms-unreadable");
37
+ if (standing.state === "lapsed")
38
+ return { ok: false, reason: "terms-lapsed", message: `This project's Flexible terms no longer count. ${FLEXIBLE_LAPSE_WORDS[standing.reason]} Nothing was started.` };
39
+ const terms = standing.terms;
40
+ if (terms.starters === "signer" && input.by.name !== terms.signer)
41
+ return refuse("not-a-starter");
42
+ const network = flexibleThreadNetwork(store, input.repo);
43
+ if ("ok" in network)
44
+ return refuse("not-available");
45
+ const credential = flexibleRelayBilling(store);
46
+ if (!credential.ok)
47
+ return refuse("no-sign-in");
48
+ const billing = credential.billing;
49
+ const open = network.mode === "open";
50
+ const project = store.handle.prepare("SELECT name FROM project WHERE path = ?").get(input.repo)?.["name"];
51
+ const caps = terms.caps;
52
+ const decisions = [
53
+ { label: "Project", words: typeof project === "string" ? project : input.repo, lines: typeof project === "string" ? [input.repo] : [], fields: ["flexible.repo"] },
54
+ { label: "Level", words: `${FLEXIBLE_LEVEL_WORDS.full}: no permission prompts inside the sandbox`, lines: [FULL_ACCESS_WORDS], fields: ["flexible.level"], risky: true },
55
+ { label: "Agent", words: `${agentModelName("claude", model)}, signed in through Toolroll's relay`, lines: ["Your Claude login stays with Toolroll and never enters the agent; each call is checked and counted.",
56
+ billing === "subscription" ? "Billed to your Claude plan (Toolroll's setup-token sign-in)." : "Billed per call to Toolroll's Claude API key."], fields: ["flexible.agent", "flexible.billing"] },
57
+ { label: "Works in", words: "its own copy of this repository, on its own branch", lines: ["Your repository changes only when you Ship."], fields: ["flexible.repository"] },
58
+ { label: "Network", words: open ? "open: any website, through the thread's own proxy" : lowerFirst(networkWords(network, "claude").replace(/^Network: /, "")),
59
+ lines: ["Nothing on this computer is reachable (no local services, keychain, SSH agent or saved sign-ins)."], fields: ["flexible.network"], ...(open ? { risky: true } : {}) },
60
+ { label: "Limits", words: `${plural(caps.turnsPerDayPerson, "turn")} a day for you, ${plural(caps.turnsPerDayProject, "turn")} a day in this project, ${plural(caps.liveThreads, "thread")} at once`,
61
+ lines: [
62
+ "Turn limits are hard. A limit on turns doesn't limit what one turn costs.",
63
+ caps.measuredMicrousdPerDay === null ? "No dollar limit: a turn runs until it finishes." : `New turns stop once today's measured spend reaches ${money(caps.measuredMicrousdPerDay)}; a turn already running may go past it.`,
64
+ FLEXIBLE_UNKNOWN_COST_WORDS,
65
+ ], fields: ["flexible.caps"], ...(caps.measuredMicrousdPerDay === null ? { risky: true } : {}) },
66
+ { label: "Ship", words: FLEXIBLE_SHIP_WORDS, fields: ["flexible.ship"] },
67
+ { label: "Terms", words: `this project's Flexible terms, turned on by ${terms.signer}`, lines: [`They last until someone turns them off or lowers them, or ${terms.signer}'s account or access changes.`], fields: ["flexible.terms"] },
68
+ ];
69
+ const warnings = [
70
+ { words: "The agent can read this repository's whole history, not just the commit it starts from.", fields: ["flexible.repository"] },
71
+ { words: "Anything it reads can end up in what it writes: its messages and its commits. Toolroll checks for secrets before Ship, but that isn't a guarantee.", fields: ["flexible.network"] },
72
+ ...(open ? OPEN_NETWORK_WORDS.map(words => ({ words, fields: ["flexible.network"] })) : []),
73
+ ];
74
+ const digestOfMessage = createHash("sha256").update(input.message, "utf8").digest("hex");
75
+ const networkDigest = flexibleNetworkDigest(network);
76
+ const key = createHash("sha256").update(JSON.stringify({ v: 1, kind: "standing-orders:flexible-start", digest: standing.digest, repo: input.repo, by: input.by, model, level: "full", billing,
77
+ network: networkDigest, message: digestOfMessage, decisions, warnings }), "utf8").digest("hex").slice(0, 32);
78
+ const summary = { revision: null, revisionNotes: [], revisionChanges: [], decisions, why: null, differs: [], warnings, usual: [], usualLabel: "Other settings", key };
79
+ return { ok: true, card: { summary, digest: standing.digest, network: networkDigest, model, level: "full", billing, terms } };
80
+ }
@@ -1,5 +1,5 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
- import { randomBytes } from "node:crypto";
2
+ import { createHash, randomBytes } from "node:crypto";
3
3
  import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
@@ -12,6 +12,9 @@ import { SANDBOX_LAUNCH_SPEC, SEATBELT_NO_KEYCHAIN } from "./sandbox-runtime.js"
12
12
  import { hardenedGit, lazyFetchSetting, recordedCommonDir } from "./teardown-git.js";
13
13
  import { withCheckoutLock } from "./git-views.js";
14
14
  import { processMayBeAlive } from "./process-liveness.js";
15
+ import { startIdentityOf } from "./flexible-custody.js";
16
+ import { defaultCustodyIO, holdLaunch, recordGateShut, recordLaunchOpened, recordLive, recordNeverStarted, recordSpawning, settleLaunch, unsettledLaunch } from "./flexible-launch.js";
17
+ import { readProjectRefs, saveRefSnapshot } from "./flexible-refs.js";
15
18
  import { projectRowKnown } from "./store.js";
16
19
  import { poolRootOf } from "./worktree.js";
17
20
  export const FLEXIBLE_THREAD_ID = /^[0-9a-f]{32}$/;
@@ -47,6 +50,7 @@ const WORDS = Object.freeze({
47
50
  "network-required": "A thread can only run through its own network proxy, and it wasn't given one.",
48
51
  "containment": "The sandbox couldn't hold this thread, so it didn't run.",
49
52
  "thread-running": "This thread's agent may still be running, so its repository was left as it is.",
53
+ "thread-shipping": "This thread's work is being shipped. Let the Ship finish, or cancel it, before removing the thread. Nothing was removed.",
50
54
  "codex-unsupported": "Codex's own sandbox can't keep a Flexible thread away from threads and files made after it starts, so a Codex thread can't run in it.",
51
55
  });
52
56
  const refuse = (reason, detail) => ({ ok: false, reason, message: detail === undefined ? WORDS[reason] : `${WORDS[reason]} (${detail})` });
@@ -189,10 +193,16 @@ export async function prepareFlexibleThread(store, input) {
189
193
  const id = randomBytes(16).toString("hex");
190
194
  const paths = flexibleThreadPaths(state, id);
191
195
  const keepRef = flexibleKeepRef(id);
192
- store.transact(() => {
196
+ const reserved = store.transact(() => {
193
197
  store.handle.prepare(`INSERT INTO flexible_thread (id, repo, base_sha, keep_ref, folder, created_by, created_at, state) VALUES (?, ?, ?, ?, ?, ?, ?, 'preparing')`)
194
198
  .run(id, input.repo, baseSha, keepRef, paths.folder, input.by, input.now.toISOString());
199
+ const held = input.reserve?.(id) ?? { ok: true };
200
+ if (!held.ok)
201
+ store.handle.prepare("DELETE FROM flexible_thread WHERE id = ? AND state = 'preparing'").run(id);
202
+ return held;
195
203
  });
204
+ if (!reserved.ok)
205
+ return reserved;
196
206
  const zero = "0".repeat(baseSha.length);
197
207
  let madeFolder = false, madeRef = false;
198
208
  const build = gitIn(inner, "build");
@@ -218,10 +228,13 @@ export async function prepareFlexibleThread(store, input) {
218
228
  if (checkout.code !== 0)
219
229
  throw new Error("the thread's files couldn't be checked out");
220
230
  reserveProtectedNames(paths.repo);
231
+ const refs = await readProjectRefs(read, project);
221
232
  const ready = store.transact(() => {
222
233
  const moved = store.handle.prepare("UPDATE flexible_thread SET state = 'ready' WHERE id = ? AND state = 'preparing'").run(id);
223
234
  if (Number(moved.changes) !== 1)
224
235
  return false;
236
+ if (refs !== null)
237
+ saveRefSnapshot(store, id, refs, input.now);
225
238
  store.recordAction({ at: input.now.toISOString(), actor: input.by, repo: input.repo, taskId: null, runId: null, source: "policy", action: "flexible thread repository made", outcome: "ready",
226
239
  detail: `thread ${id} · base ${baseSha} · ${keepRef}` });
227
240
  return true;
@@ -232,6 +245,10 @@ export async function prepareFlexibleThread(store, input) {
232
245
  }
233
246
  catch (error) {
234
247
  const why = error instanceof Error ? error.message : String(error);
248
+ try {
249
+ input.release?.(id, why);
250
+ }
251
+ catch { }
235
252
  if (madeRef)
236
253
  await build(project, ["update-ref", "--no-deref", "-d", keepRef, baseSha]);
237
254
  if (madeFolder)
@@ -256,10 +273,23 @@ async function removeLocked(store, input) {
256
273
  const thread = flexibleThread(store, input.id);
257
274
  if (thread === null)
258
275
  return refuse("thread-unknown");
259
- if (thread.livePid !== null && processMayBeAlive(thread.livePid, true))
276
+ const paths = flexibleThreadPaths(state, thread.id);
277
+ const launch = unsettledLaunch(store, thread.id);
278
+ if (launch !== null) {
279
+ const leaderRuns = launch.leaderPid !== null && launch.state === "live" && processMayBeAlive(launch.leaderPid, true);
280
+ if (leaderRuns)
281
+ return refuse("thread-running");
282
+ const settled = await settleLaunch(store, { thread: thread.id, folder: paths.folder, reason: "the thread is being removed", stop: true, clock: () => input.now, ...(input.io === undefined ? {} : { io: input.io }) });
283
+ if (!settled.ok)
284
+ return refuse("thread-running", settled.why);
285
+ }
286
+ if (store.handle.prepare("SELECT 1 FROM flexible_ship WHERE thread = ? AND state IN ('approved', 'armed', 'completed')").get(thread.id) !== undefined)
287
+ return refuse("thread-shipping");
288
+ const after = flexibleThread(store, thread.id);
289
+ if (after.livePid !== null && processMayBeAlive(after.livePid, true))
260
290
  return refuse("thread-running");
261
- const claimed = store.transact(() => Number(store.handle.prepare("UPDATE flexible_thread SET state = 'removing', live_pid = NULL, live_since = NULL WHERE id = ? AND state IN ('ready', 'removing') AND live_pid IS ?")
262
- .run(thread.id, thread.livePid).changes) === 1);
291
+ const claimed = store.transact(() => Number(store.handle.prepare("UPDATE flexible_thread SET state = 'removing', live_pid = NULL, live_since = NULL WHERE id = ? AND state IN ('ready', 'removing') AND live_pid IS ? AND NOT EXISTS (SELECT 1 FROM flexible_thread_launch WHERE thread = ? AND state <> 'exited')")
292
+ .run(thread.id, after.livePid, thread.id).changes) === 1);
263
293
  if (!claimed)
264
294
  return refuse("thread-not-ready");
265
295
  const inner = input.runner ?? run;
@@ -273,21 +303,38 @@ async function removeLocked(store, input) {
273
303
  catch {
274
304
  project = null;
275
305
  }
306
+ let shipRefs = 0, shipRefsLeft = 0;
276
307
  if (project !== null) {
277
308
  const removed = await build(project, ["update-ref", "--no-deref", "-d", thread.keepRef, thread.baseSha]);
278
309
  if (removed.code === 0)
279
310
  keepRef = "removed";
280
311
  else
281
312
  keepRef = (await read(project, ["rev-parse", "--verify", "--quiet", "--end-of-options", thread.keepRef])).code === 0 ? "moved" : "already-gone";
313
+ const ships = store.handle.prepare("SELECT import_ref, candidate, state FROM flexible_ship WHERE thread = ? ORDER BY seq").all(thread.id);
314
+ for (const ship of ships.filter(one => ["imported", "merged", "cancelled", "sent-back"].includes(String(one["state"])))) {
315
+ const gone = await build(project, ["update-ref", "--no-deref", "-d", String(ship["import_ref"]), String(ship["candidate"])]);
316
+ if (gone.code === 0)
317
+ shipRefs++;
318
+ else if ((await read(project, ["rev-parse", "--verify", "--quiet", "--end-of-options", String(ship["import_ref"])])).code === 0)
319
+ shipRefsLeft++;
320
+ }
321
+ const standing = [...ships].reverse().find(one => ["imported", "merged", "cancelled", "sent-back"].includes(String(one["state"])));
322
+ if (standing !== undefined) {
323
+ const branch = `refs/heads/${flexibleThreadBranch(thread.id)}`;
324
+ const gone = await build(project, ["update-ref", "--no-deref", "-d", branch, String(standing["candidate"])]);
325
+ if (gone.code === 0)
326
+ shipRefs++;
327
+ else if ((await read(project, ["rev-parse", "--verify", "--quiet", "--end-of-options", branch])).code === 0)
328
+ shipRefsLeft++;
329
+ }
282
330
  }
283
- const paths = flexibleThreadPaths(state, thread.id);
284
331
  if (thread.folder === paths.folder && ownFolder(paths.root))
285
332
  rmSync(paths.folder, { recursive: true, force: true });
286
333
  store.transact(() => {
287
334
  store.handle.prepare("UPDATE flexible_thread SET state = 'removed', ended_at = ?, end_detail = ? WHERE id = ? AND state = 'removing'")
288
335
  .run(input.now.toISOString(), keepRef === "moved" ? "the keep-ref had been moved by someone else and was left as it was" : null, thread.id);
289
336
  store.recordAction({ at: input.now.toISOString(), actor: input.by, repo: thread.repo, taskId: null, runId: null, source: "policy", action: "flexible thread repository removed", outcome: "removed",
290
- detail: `thread ${thread.id} · keep-ref ${keepRef}` });
337
+ detail: `thread ${thread.id} · keep-ref ${keepRef}${shipRefs + shipRefsLeft > 0 ? ` · ship refs removed ${shipRefs}${shipRefsLeft > 0 ? `, ${shipRefsLeft} moved by someone else and left` : ""}` : ""}` });
291
338
  });
292
339
  return { ok: true, keepRef };
293
340
  }
@@ -341,6 +388,8 @@ export function flexibleThreadFence(store, input) {
341
388
  const network = input.network;
342
389
  if (!Number.isSafeInteger(network.proxyPort) || network.proxyPort < 1 || network.proxyPort > 65_535 || typeof network.token !== "string" || network.token === "")
343
390
  return refuse("network-required");
391
+ if (network.relayPort !== undefined && (!Number.isSafeInteger(network.relayPort) || network.relayPort < 1 || network.relayPort > 65_535 || network.relayPort === network.proxyPort))
392
+ return refuse("network-required");
344
393
  const databaseFile = store.databaseFile();
345
394
  const state = stateFolderOf(store);
346
395
  if (state === null || databaseFile === null)
@@ -379,7 +428,7 @@ export function flexibleThreadFence(store, input) {
379
428
  storage: input.storage, databaseFile, worktree: paths.folder, boundary, binding: null, runFolders: runFolders(null), poolRoots, home, policy: 2,
380
429
  extra: [project, ...others, ...stateDenies],
381
430
  writes: { writes: { subpaths: [paths.repo, paths.tmp, paths.cache], prefixes: [] }, readOnly: threadReadOnly(paths) },
382
- network: { mode: "allowlist", proxyPort: network.proxyPort, brokerPorts: [], loopback: "proxy-only", socketRoots: [], token: network.token },
431
+ network: { mode: "allowlist", proxyPort: network.proxyPort, brokerPorts: network.relayPort === undefined ? [] : [network.relayPort], loopback: "proxy-only", socketRoots: [], token: network.token },
383
432
  });
384
433
  const { keychain: _never, pool, ...rest } = made.fenceGrants;
385
434
  const unread = pool === undefined ? undefined : (({ readable: _read, ...held }) => held)(pool);
@@ -460,17 +509,42 @@ async function probeContainment(launch, paths, env, platform) {
460
509
  rmSync(writable, { force: true });
461
510
  }
462
511
  }
463
- function withThreadLock(id, work) {
464
- return withCheckoutLock(real(homedir()), `flexible-thread:${id}`, work);
512
+ function withThreadLock(id, work, timeoutMs) {
513
+ return withCheckoutLock(real(homedir()), `flexible-thread:${id}`, work, timeoutMs);
465
514
  }
466
- export async function flexibleThreadSpawn(store, input, file, args, start, platform = process.platform) {
515
+ export async function withFlexibleThreadLock(id, work, timeoutMs) {
516
+ if (!FLEXIBLE_AVAILABLE)
517
+ return refuse("not-available");
518
+ if (!FLEXIBLE_THREAD_ID.test(id))
519
+ return refuse("thread-unknown");
520
+ return withThreadLock(id, work, timeoutMs);
521
+ }
522
+ export const FLEXIBLE_START_GATE = 'IFS= read -r gate || exit 125; [ "$gate" = start ] || exit 125; exec "$@"';
523
+ export function flexibleFenceDigest(launch) {
524
+ return createHash("sha256").update(`standing-orders:flexible-fence:${JSON.stringify({ fence: launch.fence, grants: launch.fenceGrants })}`, "utf8").digest("hex").slice(0, 32);
525
+ }
526
+ function stopUnopenedLaunch(child) {
527
+ const pid = child.pid;
528
+ if (pid === undefined || !Number.isSafeInteger(pid) || pid <= 1 || child.exitCode !== null || child.signalCode !== null)
529
+ return;
530
+ try {
531
+ process.kill(-pid, "SIGKILL");
532
+ }
533
+ catch {
534
+ try {
535
+ child.kill("SIGKILL");
536
+ }
537
+ catch { }
538
+ }
539
+ }
540
+ export async function flexibleThreadSpawn(store, input, file, args, platform = process.platform, seams = {}) {
467
541
  if (!FLEXIBLE_AVAILABLE)
468
542
  return refuse("not-available");
469
543
  if (!FLEXIBLE_THREAD_ID.test(input.id))
470
544
  return refuse("thread-unknown");
471
- return withThreadLock(input.id, () => spawnLocked(store, input, file, args, start, platform));
545
+ return withThreadLock(input.id, () => spawnLocked(store, input, file, args, platform, seams));
472
546
  }
473
- async function spawnLocked(store, input, file, args, start, platform) {
547
+ async function spawnLocked(store, input, file, args, platform, seams) {
474
548
  const fenced = flexibleThreadFence(store, input);
475
549
  if (!fenced.ok)
476
550
  return fenced;
@@ -478,7 +552,8 @@ async function spawnLocked(store, input, file, args, start, platform) {
478
552
  const terms = termsProblem(launch);
479
553
  if (terms !== null)
480
554
  return refuse("containment", terms);
481
- const env = flexibleThreadEnv(paths, input.proxyEnv);
555
+ const base = flexibleThreadEnv(paths, input.proxyEnv);
556
+ const env = { ...Object.fromEntries(Object.entries(input.agentEnv ?? {}).filter(([name]) => !(name in base))), ...base };
482
557
  const probed = await probeContainment(launch, paths, env, platform);
483
558
  if (probed !== null)
484
559
  return refuse("containment", probed);
@@ -487,11 +562,13 @@ async function spawnLocked(store, input, file, args, start, platform) {
487
562
  return again;
488
563
  if (JSON.stringify(again.thread) !== JSON.stringify(fenced.thread))
489
564
  return refuse("thread-not-ready", "it changed while the sandbox was checked");
565
+ if (unsettledLaunch(store, input.id) !== null)
566
+ return refuse("thread-running");
490
567
  if (again.thread.livePid !== null && processMayBeAlive(again.thread.livePid, true))
491
568
  return refuse("thread-running");
492
569
  let spawned;
493
570
  try {
494
- spawned = confined(file, args, { fence: launch.fence, fenceGrants: launch.fenceGrants, confinement: "required", cwd: paths.repo, temp: paths.tmp });
571
+ spawned = confined("/bin/sh", ["-c", FLEXIBLE_START_GATE, "toolroll-start-gate", file, ...args], { fence: launch.fence, fenceGrants: launch.fenceGrants, confinement: "required", cwd: paths.repo, temp: paths.tmp });
495
572
  }
496
573
  catch (error) {
497
574
  return refuse("containment", error instanceof Error ? error.message : undefined);
@@ -499,23 +576,96 @@ async function spawnLocked(store, input, file, args, start, platform) {
499
576
  const problem = spawnProblem(spawned, platform);
500
577
  if (problem !== null)
501
578
  return refuse("containment", problem);
502
- const pid = start({ file: spawned.file, args: spawned.args, env: { ...outerEnv(env, platform), ...spawned.env }, cwd: paths.repo });
503
- let registered = false;
579
+ const io = seams.io ?? defaultCustodyIO();
580
+ const fenceDigest = flexibleFenceDigest(launch);
581
+ const record = recordSpawning(store, { thread: input.id, meta: input.launch, fenceDigest, bootId: io.bootId() });
582
+ let launchEnv;
504
583
  try {
505
- registered = Number.isSafeInteger(pid) && pid > 0 && store.transact(() => Number(store.handle.prepare("UPDATE flexible_thread SET live_pid = ?, live_since = ? WHERE id = ? AND state = 'ready'").run(pid, new Date().toISOString(), input.id).changes) === 1);
584
+ launchEnv = Object.fromEntries(Object.entries(input.agentEnvFor?.(record.id) ?? {}).filter(([name]) => !(name in env)));
506
585
  }
507
- catch {
508
- registered = false;
586
+ catch (error) {
587
+ recordNeverStarted(store, record.id, `the agent's launch couldn't be prepared: ${error instanceof Error ? error.message : String(error)}`);
588
+ return refuse("setup-failed", "the agent's launch couldn't be prepared");
589
+ }
590
+ let child;
591
+ try {
592
+ child = spawn(spawned.file, spawned.args, { cwd: paths.repo, env: { ...outerEnv({ ...launchEnv, ...env }, platform), ...spawned.env }, stdio: ["pipe", "pipe", "pipe"], detached: true });
509
593
  }
510
- if (!registered) {
594
+ catch (error) {
595
+ recordNeverStarted(store, record.id, `the agent couldn't be started: ${error instanceof Error ? error.message : String(error)}`);
596
+ return refuse("containment", "the agent couldn't be started");
597
+ }
598
+ child.on("error", () => { });
599
+ child.stdin?.on("error", () => { });
600
+ const pid = child.pid;
601
+ try {
602
+ if (pid === undefined || !Number.isSafeInteger(pid) || pid <= 1)
603
+ throw new Error("the agent's process didn't start");
604
+ seams.afterSpawn?.(pid);
605
+ const start = startIdentityOf(pid, io);
606
+ if (start === null)
607
+ throw new Error("the agent's process couldn't be identified");
608
+ recordLive(store, { launch: record.id, thread: input.id, pid, start });
609
+ holdLaunch(record.id, child);
610
+ }
611
+ catch (error) {
612
+ try {
613
+ child.stdin?.destroy();
614
+ }
615
+ catch { }
616
+ stopUnopenedLaunch(child);
511
617
  try {
512
- if (Number.isSafeInteger(pid) && pid > 0)
513
- process.kill(-pid, "SIGKILL");
618
+ recordNeverStarted(store, record.id, `stopped before it ran: ${error instanceof Error ? error.message : String(error)}`);
514
619
  }
515
620
  catch { }
516
- return refuse("containment", "the agent's process couldn't be registered, so it was stopped");
621
+ return refuse("containment", "the agent's process couldn't be registered, so it was stopped before it ran");
517
622
  }
518
- return { ok: true, pid, launch };
623
+ let shut;
624
+ try {
625
+ shut = input.beforeOpen?.() ?? null;
626
+ }
627
+ catch (error) {
628
+ shut = error instanceof Error ? error.message : "the start couldn't be re-checked";
629
+ }
630
+ if (shut !== null) {
631
+ try {
632
+ child.stdin?.destroy();
633
+ }
634
+ catch { }
635
+ stopUnopenedLaunch(child);
636
+ recordGateShut(store, { launch: record.id, thread: input.id, pid: pid, detail: `stopped before it ran: ${shut}` });
637
+ return refuse("thread-not-ready", shut);
638
+ }
639
+ try {
640
+ recordLaunchOpened(store, { launch: record.id, thread: input.id, turn: input.launch.turn });
641
+ }
642
+ catch {
643
+ try {
644
+ child.stdin?.destroy();
645
+ }
646
+ catch { }
647
+ stopUnopenedLaunch(child);
648
+ recordGateShut(store, { launch: record.id, thread: input.id, pid: pid, detail: "stopped before it ran: its launch couldn't be recorded" });
649
+ return refuse("thread-not-ready", "its launch couldn't be recorded");
650
+ }
651
+ child.stdin.write("start\n");
652
+ return { ok: true, pid: pid, launchId: record.id, launch, fenceDigest, child };
653
+ }
654
+ export async function stopFlexibleThreadAgent(store, input) {
655
+ if (!FLEXIBLE_AVAILABLE)
656
+ return refuse("not-available");
657
+ if (!FLEXIBLE_THREAD_ID.test(input.id))
658
+ return refuse("thread-unknown");
659
+ return withThreadLock(input.id, async () => {
660
+ const state = stateFolderOf(store);
661
+ if (state === null)
662
+ return refuse("no-state-folder");
663
+ const thread = flexibleThread(store, input.id);
664
+ if (thread === null)
665
+ return refuse("thread-unknown");
666
+ return settleLaunch(store, { thread: thread.id, folder: flexibleThreadPaths(state, thread.id).folder, reason: input.reason, stop: true, ...(input.clock === undefined ? {} : { clock: input.clock }), ...(input.io === undefined ? {} : { io: input.io }),
667
+ ...(input.keepTurn === undefined ? {} : { keepTurn: input.keepTurn }), ...(input.holderGone === true ? { holderGone: true } : {}), ...(input.expect === undefined ? {} : { expect: input.expect }) });
668
+ });
519
669
  }
520
670
  export function flexibleThreadCodexProfile(store, input) {
521
671
  if (!FLEXIBLE_AVAILABLE)
@@ -0,0 +1,69 @@
1
+ export const V164_SCHEMA = `
2
+ CREATE TABLE IF NOT EXISTS thread_turn (
3
+ id TEXT PRIMARY KEY CHECK (length(id) = 32 AND id NOT GLOB '*[^0-9a-f]*'),
4
+ thread TEXT NOT NULL CHECK (length(thread) = 32 AND thread NOT GLOB '*[^0-9a-f]*'),
5
+ seq INTEGER NOT NULL CHECK (seq >= 1),
6
+ repo TEXT NOT NULL,
7
+ owner TEXT NOT NULL,
8
+ owner_generation INTEGER NOT NULL,
9
+ terms_id INTEGER NOT NULL,
10
+ terms_digest TEXT NOT NULL,
11
+ level TEXT NOT NULL CHECK (level IN ('supervised', 'auto', 'full')),
12
+ provider TEXT NOT NULL CHECK (provider IN ('claude', 'codex')),
13
+ model TEXT NOT NULL CHECK (length(model) BETWEEN 1 AND 200),
14
+ billing TEXT NOT NULL CHECK (billing IN ('subscription', 'api-key')),
15
+ request_key TEXT NOT NULL CHECK (length(request_key) BETWEEN 1 AND 128),
16
+ holder TEXT NOT NULL CHECK (length(holder) BETWEEN 1 AND 128),
17
+ admitted_at TEXT NOT NULL,
18
+ utc_day TEXT NOT NULL CHECK (utc_day = substr(admitted_at, 1, 10)),
19
+ rail_reserved INTEGER NOT NULL DEFAULT 0 CHECK (rail_reserved IN (0, 1)),
20
+ status TEXT NOT NULL CHECK (status IN ('admitted', 'running', 'finished', 'interrupted', 'unknown', 'withdrawn')),
21
+ started_at TEXT,
22
+ ended_at TEXT,
23
+ end_detail TEXT CHECK (end_detail IS NULL OR length(end_detail) <= 2000),
24
+ tokens_in INTEGER NOT NULL DEFAULT 0 CHECK (tokens_in >= 0),
25
+ tokens_out INTEGER NOT NULL DEFAULT 0 CHECK (tokens_out >= 0),
26
+ cost_microusd INTEGER NOT NULL DEFAULT 0 CHECK (cost_microusd >= 0),
27
+ relay_calls INTEGER NOT NULL DEFAULT 0 CHECK (relay_calls >= 0),
28
+ cost_basis TEXT CHECK (cost_basis IS NULL OR cost_basis IN ('measured', 'estimated', 'unknown')),
29
+ CHECK ((status IN ('admitted', 'withdrawn')) = (started_at IS NULL)),
30
+ CHECK ((status IN ('admitted', 'running')) = (ended_at IS NULL)),
31
+ CHECK (status NOT IN ('admitted', 'withdrawn') OR (tokens_in = 0 AND tokens_out = 0 AND cost_microusd = 0 AND relay_calls = 0 AND cost_basis IS NULL)),
32
+ CHECK (status NOT IN ('finished', 'interrupted', 'unknown') OR cost_basis IS NOT NULL),
33
+ UNIQUE (thread, seq)
34
+ );
35
+ CREATE UNIQUE INDEX IF NOT EXISTS thread_turn_request ON thread_turn (thread, request_key) WHERE status <> 'withdrawn';
36
+ CREATE UNIQUE INDEX IF NOT EXISTS thread_turn_live ON thread_turn (thread) WHERE status IN ('admitted', 'running');
37
+ CREATE INDEX IF NOT EXISTS thread_turn_day ON thread_turn (utc_day, repo);
38
+ CREATE INDEX IF NOT EXISTS thread_turn_owner_day ON thread_turn (owner, utc_day);
39
+ CREATE TRIGGER IF NOT EXISTS thread_turn_written_once BEFORE UPDATE ON thread_turn
40
+ WHEN NEW.id IS NOT OLD.id OR NEW.thread IS NOT OLD.thread OR NEW.seq IS NOT OLD.seq OR NEW.repo IS NOT OLD.repo OR NEW.owner IS NOT OLD.owner
41
+ OR NEW.owner_generation IS NOT OLD.owner_generation OR NEW.terms_id IS NOT OLD.terms_id OR NEW.terms_digest IS NOT OLD.terms_digest
42
+ OR NEW.level IS NOT OLD.level OR NEW.provider IS NOT OLD.provider OR NEW.model IS NOT OLD.model OR NEW.billing IS NOT OLD.billing
43
+ OR NEW.request_key IS NOT OLD.request_key OR NEW.holder IS NOT OLD.holder OR NEW.admitted_at IS NOT OLD.admitted_at
44
+ OR NEW.utc_day IS NOT OLD.utc_day OR NEW.rail_reserved IS NOT OLD.rail_reserved
45
+ OR OLD.status = 'withdrawn'
46
+ OR (OLD.status = 'admitted' AND NEW.status NOT IN ('admitted', 'running', 'withdrawn'))
47
+ OR (OLD.status = 'running' AND NEW.status IN ('admitted', 'withdrawn'))
48
+ OR (OLD.status IN ('finished', 'interrupted', 'unknown') AND (NEW.status IS NOT OLD.status OR NEW.ended_at IS NOT OLD.ended_at OR NEW.end_detail IS NOT OLD.end_detail
49
+ OR (NEW.cost_basis IS NOT OLD.cost_basis AND NOT (NEW.cost_basis = 'unknown' OR (NEW.cost_basis = 'estimated' AND OLD.cost_basis = 'measured')))))
50
+ OR (OLD.started_at IS NOT NULL AND NEW.started_at IS NOT OLD.started_at)
51
+ OR NEW.tokens_in < OLD.tokens_in OR NEW.tokens_out < OLD.tokens_out OR NEW.cost_microusd < OLD.cost_microusd OR NEW.relay_calls < OLD.relay_calls
52
+ BEGIN
53
+ SELECT RAISE(ABORT, 'a flexible turn is written once, its status only moves forward and its usage only grows');
54
+ END;
55
+ CREATE TABLE IF NOT EXISTS flexible_installation_caps (
56
+ id INTEGER PRIMARY KEY CHECK (id = 1),
57
+ live_threads INTEGER CHECK (live_threads IS NULL OR live_threads BETWEEN 1 AND 1000),
58
+ turns_per_day INTEGER CHECK (turns_per_day IS NULL OR turns_per_day BETWEEN 1 AND 1000000),
59
+ measured_microusd_per_day INTEGER CHECK (measured_microusd_per_day IS NULL OR measured_microusd_per_day BETWEEN 1 AND 100000000000000),
60
+ updated_by TEXT NOT NULL,
61
+ updated_at TEXT NOT NULL
62
+ );
63
+ `;
64
+ export const V164_TABLES = Object.freeze(["thread_turn", "flexible_installation_caps"]);
65
+ export const V164_STEPS = Object.freeze(["thread-turn"]);
66
+ export const V164_OBJECTS = Object.freeze([
67
+ ["table", "thread_turn"], ["index", "thread_turn_request"], ["index", "thread_turn_live"], ["index", "thread_turn_day"], ["index", "thread_turn_owner_day"],
68
+ ["trigger", "thread_turn_written_once"], ["table", "flexible_installation_caps"],
69
+ ]);