toolroll 0.9.115 → 0.9.117

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 (145) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +43 -26
  3. package/dist/acp-agents.js +14 -1
  4. package/dist/acp-client.js +19 -1
  5. package/dist/agent-change-check.js +60 -0
  6. package/dist/agent-change-schema.js +19 -0
  7. package/dist/agent-detect.js +11 -1
  8. package/dist/agent-fence.js +39 -10
  9. package/dist/agent-network-request.js +108 -0
  10. package/dist/agent-requests.js +105 -0
  11. package/dist/approval-summary.js +3 -3
  12. package/dist/backup.js +17 -1
  13. package/dist/batch-checks.js +81 -18
  14. package/dist/browser/terminal.js +41 -41
  15. package/dist/browser/workspace.css +2 -2
  16. package/dist/browser/workspace.js +36 -36
  17. package/dist/builder.js +3 -1
  18. package/dist/candidate-materialize.js +119 -0
  19. package/dist/central-enrollment-contract.js +156 -0
  20. package/dist/central-recovery-stage.js +329 -0
  21. package/dist/chat-actions.js +101 -2
  22. package/dist/chat-channel.js +40 -0
  23. package/dist/check-only-standing.js +13 -0
  24. package/dist/check-only.js +25 -13
  25. package/dist/check-recovery-hold.js +199 -0
  26. package/dist/check-recovery-index-schema.js +3 -0
  27. package/dist/check-screenshots.js +83 -0
  28. package/dist/cli.js +125 -6
  29. package/dist/codex-limits.js +4 -0
  30. package/dist/connect-cli.js +257 -11
  31. package/dist/contracts/chat-actions.js +4 -0
  32. package/dist/contracts/console-api.js +15 -4
  33. package/dist/contracts/engine-api.js +344 -2
  34. package/dist/contracts/lead-tools.js +56 -2
  35. package/dist/contracts/provider.js +1 -1
  36. package/dist/contracts/route.js +1 -1
  37. package/dist/contracts/terminal-connection.js +50 -0
  38. package/dist/converse.js +80 -4
  39. package/dist/device-pair.js +280 -0
  40. package/dist/direct-chat-artifacts.js +347 -0
  41. package/dist/direct-chat-catalog.js +311 -0
  42. package/dist/direct-chat-fence.js +96 -0
  43. package/dist/direct-chat-git.js +343 -0
  44. package/dist/direct-chat-laptop.js +19 -0
  45. package/dist/direct-chat-schema.js +181 -0
  46. package/dist/direct-chat-ship.js +861 -0
  47. package/dist/direct-chat-workspace.js +389 -0
  48. package/dist/direct-chat.js +2107 -0
  49. package/dist/doctor.js +1 -1
  50. package/dist/easy-start.js +18 -0
  51. package/dist/egress.js +25 -4
  52. package/dist/engine-chat.js +454 -0
  53. package/dist/engine-reads.js +141 -13
  54. package/dist/exec.js +4 -3
  55. package/dist/flexible-agents.js +8 -16
  56. package/dist/flexible-authority-end.js +2 -0
  57. package/dist/flexible-interactive-schema.js +133 -0
  58. package/dist/flexible-interactive.js +94 -0
  59. package/dist/flexible-session.js +117 -49
  60. package/dist/flexible-ship.js +87 -7
  61. package/dist/flexible-sign-in.js +10 -0
  62. package/dist/flexible-start.js +21 -3
  63. package/dist/flexible-thread.js +2 -3
  64. package/dist/flexible-turns.js +26 -5
  65. package/dist/flexible.js +13 -0
  66. package/dist/flow-triggers.js +13 -4
  67. package/dist/flows-ui.js +54 -20
  68. package/dist/handoff-cli.js +630 -0
  69. package/dist/invoke.js +55 -13
  70. package/dist/lead-contract.js +5 -4
  71. package/dist/lead-doors.js +80 -1
  72. package/dist/lead-progress.js +9 -0
  73. package/dist/lead-tools.js +682 -10
  74. package/dist/lead.js +37 -9
  75. package/dist/live-bus.js +11 -0
  76. package/dist/live-terminal.js +132 -12
  77. package/dist/local-handoff.js +363 -0
  78. package/dist/local-owner-acts.js +264 -2
  79. package/dist/local-owner.js +16 -1
  80. package/dist/multiplayer-handoff.js +528 -0
  81. package/dist/multiplayer-presence.js +471 -0
  82. package/dist/names.js +17 -4
  83. package/dist/needs-you.js +10 -0
  84. package/dist/operate.js +280 -19
  85. package/dist/policy.js +2 -2
  86. package/dist/project-delete-ui.js +18 -11
  87. package/dist/project-delete.js +65 -4
  88. package/dist/project-tools.js +1 -1
  89. package/dist/prompt.js +1 -1
  90. package/dist/provider-connection.js +2 -0
  91. package/dist/provider-home.js +251 -8
  92. package/dist/provider.js +3 -2
  93. package/dist/publish.js +119 -64
  94. package/dist/pull-request-flow.js +35 -14
  95. package/dist/read-executor-worker.js +1 -1
  96. package/dist/read-executor.js +95 -1
  97. package/dist/restore-retirement.js +152 -0
  98. package/dist/result-follow-ups.js +116 -37
  99. package/dist/route-change.js +44 -4
  100. package/dist/scope.js +62 -5
  101. package/dist/serve.js +49 -5
  102. package/dist/server/chat.js +94 -13
  103. package/dist/server/console.css +9 -9
  104. package/dist/server/direct-chat.js +583 -0
  105. package/dist/server/engine-api.js +219 -21
  106. package/dist/server/flows.js +47 -13
  107. package/dist/server/found-repos.js +25 -0
  108. package/dist/server/guards.js +20 -6
  109. package/dist/server/live.js +81 -23
  110. package/dist/server/pages.js +67 -13
  111. package/dist/server/people-tokens.js +47 -6
  112. package/dist/server/remote.js +29 -0
  113. package/dist/server/render-results.js +6 -2
  114. package/dist/server/render-settings.js +4 -2
  115. package/dist/server/render-tasks.js +18 -17
  116. package/dist/server/route-table.js +69 -2
  117. package/dist/server/settings.js +22 -7
  118. package/dist/server/task-views.js +15 -3
  119. package/dist/server/tasks.js +39 -2
  120. package/dist/server/terminals.js +185 -11
  121. package/dist/settings-proofs.js +1 -1
  122. package/dist/spend-report.js +2 -2
  123. package/dist/spend.js +3 -3
  124. package/dist/store.js +600 -59
  125. package/dist/subagent-admin.js +23 -10
  126. package/dist/subagent-backup-schema.js +36 -0
  127. package/dist/subagent-backup.js +92 -0
  128. package/dist/subagent-week.js +2 -2
  129. package/dist/subagent-work.js +70 -47
  130. package/dist/subagents-ui.js +6 -2
  131. package/dist/subagents.js +5 -2
  132. package/dist/subscription-chat.js +36 -5
  133. package/dist/subscription-usage.js +233 -0
  134. package/dist/task-live.js +2 -1
  135. package/dist/teardown-git.js +34 -4
  136. package/dist/terminal-connection.js +159 -0
  137. package/dist/terminal-safety.js +114 -0
  138. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  139. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  140. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  141. package/dist/tui/linux-x64/toolroll-tui +0 -0
  142. package/dist/tui-contract.js +1 -1
  143. package/dist/tui-launch.js +32 -1
  144. package/dist/workspace-identity-schema.js +21 -0
  145. package/package.json +4 -2
@@ -6,8 +6,8 @@ import { FLEXIBLE_LEVEL_WORDS, FLEXIBLE_UNAVAILABLE, isFlexibleLevel } from "./f
6
6
  import { lowerFlexibleThreadLevel, recoverFlexibleLaunchesOf, startFlexibleTurn } from "./flexible-agents.js";
7
7
  import { decideFlexibleAnswer, expireFlexibleAnswers, flexibleRequestsOf, noteFlexibleToolActivity, openFlexibleAnswerCatalog, recordFlexibleRequest, recoverFlexibleAnswersOf, revokeFlexibleAnswers, sendFlexibleAnswer, streamAnswerSender, } from "./flexible-answers.js";
8
8
  import { startIdentityOf } from "./flexible-custody.js";
9
- import { defaultCustodyIO, flexibleTurnLaunched, unsettledLaunch } from "./flexible-launch.js";
10
- import { cancelFlexibleShip, flexibleShipsOf, flexibleShipTerms, sendBackFlexible, shipFlexible } from "./flexible-ship.js";
9
+ import { defaultCustodyIO, flexibleLaunch, flexibleTurnLaunched, unsettledLaunch } from "./flexible-launch.js";
10
+ import { cancelFlexibleShip, flexibleShipNeeds, flexibleShipsOf, flexibleShipTerms, sendBackFlexible, shipFlexible } from "./flexible-ship.js";
11
11
  import { startFlexibleRelay } from "./flexible-relay.js";
12
12
  import { flexibleSignInBilling } from "./flexible-sign-in.js";
13
13
  import { flexibleThread, prepareFlexibleThread, removeFlexibleThread, stopFlexibleThreadAgent, withFlexibleThreadLock } from "./flexible-thread.js";
@@ -118,10 +118,30 @@ export async function settleFlexibleStops(store, sessions, input = {}) {
118
118
  const clocked = input.clock === undefined ? {} : { clock: input.clock };
119
119
  let stopped = 0, pending = 0;
120
120
  if (!flexibleAvailable(store)) {
121
- const durable = store.handle.prepare("SELECT DISTINCT thread FROM flexible_thread_launch WHERE holder = ? AND state <> 'exited'").all(sessions.holder).map(row => String(row["thread"]));
122
- for (const thread of new Set([...sessions.threads.keys(), ...durable])) {
121
+ const reason = "interactive agent threads were turned off";
122
+ const launches = store.handle.prepare("SELECT thread, id FROM flexible_thread_launch WHERE holder = ? AND state <> 'exited' ORDER BY started_at, id").all(sessions.holder)
123
+ .map(row => ({ thread: String(row["thread"]), launch: String(row["id"]) }));
124
+ try {
125
+ store.transact(() => { const at = (input.clock ?? systemClock)().toISOString(); for (const one of launches)
126
+ requireFlexibleStop(store, { launch: one.launch, thread: one.thread, reason, at }); });
127
+ }
128
+ catch { }
129
+ for (const one of launches) {
130
+ try {
131
+ const done = await stopFlexibleThreadSession(store, sessions, { thread: one.thread, reason, ...clocked, expect: { launch: one.launch, holder: sessions.holder } });
132
+ if (done.ok && "stopped" in done && done.stopped)
133
+ stopped++;
134
+ else
135
+ pending++;
136
+ }
137
+ catch {
138
+ pending++;
139
+ }
140
+ }
141
+ const held = new Set(launches.map(one => one.thread));
142
+ for (const thread of [...sessions.threads.keys()].filter(one => !held.has(one))) {
123
143
  try {
124
- const done = await stopFlexibleThreadSession(store, sessions, { thread, reason: "interactive agent threads were turned off", ...clocked });
144
+ const done = await stopFlexibleThreadSession(store, sessions, { thread, reason, ...clocked, whileOff: true });
125
145
  if (done.ok && "stopped" in done && done.stopped)
126
146
  stopped++;
127
147
  else
@@ -250,7 +270,7 @@ async function settleStopRequirements(store, sessions, clocked) {
250
270
  if (launch === undefined || launch["state"] === "exited" || String(launch["holder"]) !== sessions.holder)
251
271
  continue;
252
272
  try {
253
- const done = await stopFlexibleThreadSession(store, sessions, { thread: one.thread, reason: one.reason, ...clocked });
273
+ const done = await stopFlexibleThreadSession(store, sessions, { thread: one.thread, reason: one.reason, ...clocked, expect: { launch: one.launch, holder: sessions.holder } });
254
274
  if (done.ok && "stopped" in done && done.stopped)
255
275
  stopped++;
256
276
  else
@@ -317,33 +337,9 @@ export async function startFlexibleThreadSession(store, sessions, input) {
317
337
  export async function stopFlexibleThreadSession(store, sessions, input) {
318
338
  if (typeof input.thread !== "string" || !ID.test(input.thread) || typeof input.reason !== "string" || input.reason.length < 1 || input.reason.length > 200)
319
339
  return refuse("invalid-request");
320
- const clocked = input.clock === undefined ? {} : { clock: input.clock };
321
- const revoked = revokeFlexibleAnswers(store, sessions.catalog, { thread: input.thread, reason: input.reason, ...clocked });
322
- if (!revoked.ok)
323
- return revoked;
324
- const session = sessions.threads.get(input.thread);
325
- if (session?.agent != null) {
326
- try {
327
- session.agent.stdin.end();
328
- }
329
- catch { }
330
- }
331
- const stopped = await stopFlexibleThreadAgent(store, { id: input.thread, reason: input.reason, ...clocked, io: sessions.io });
332
- const unverified = !("reason" in stopped) && !stopped.ok;
333
- if (session !== undefined) {
334
- session.agent = null;
335
- try {
336
- await session.relay?.close();
337
- }
338
- catch { }
339
- session.relay = null;
340
- if (!unverified)
341
- sessions.threads.delete(input.thread);
342
- }
343
- bump(sessions, input.thread);
344
- if ("reason" in stopped)
345
- return stopped;
346
- return { ok: true, stopped: stopped.ok, why: stopped.ok ? null : stopped.why };
340
+ if (input.expect !== undefined && (typeof input.expect.launch !== "string" || !ID.test(input.expect.launch) || typeof input.expect.holder !== "string" || input.expect.holder === ""))
341
+ return refuse("invalid-request");
342
+ return withFlexibleThreadLock(input.thread, () => stopSessionLocked(store, sessions, input));
347
343
  }
348
344
  function cardText(given, cap) {
349
345
  if (typeof given !== "string")
@@ -656,18 +652,13 @@ export async function beginFlexibleThreadTurn(store, sessions, input) {
656
652
  bump(sessions, turn.thread);
657
653
  return started;
658
654
  }
659
- if (started.launched === "started") {
660
- const child = started.child;
661
- if (child.stdout === null || child.stdin === null)
662
- return refuse("invalid-request");
663
- const attached = attachFlexibleAgent(store, sessions, { thread: turn.thread, turn: input.turn, launch: started.launchId, stdout: child.stdout, stdin: child.stdin,
664
- exited: listener => { child.once("exit", listener); }, ...clocked });
665
- if (!attached.ok)
666
- return attached;
667
- }
668
- else if (session.agent !== null && session.agent.launch === started.launchId) {
669
- session.agent.turn = input.turn;
670
- }
655
+ const child = started.child;
656
+ if (child.stdout === null || child.stdin === null)
657
+ return refuse("invalid-request");
658
+ const attached = attachFlexibleAgent(store, sessions, { thread: turn.thread, turn: input.turn, launch: started.launchId, stdout: child.stdout, stdin: child.stdin,
659
+ exited: listener => { child.once("exit", listener); }, ...clocked });
660
+ if (!attached.ok)
661
+ return attached;
671
662
  session.title ??= cardText(input.message.split("\n")[0], 80) || null;
672
663
  try {
673
664
  session.agent?.stdin.write(`${userFrame(input.message, randomUUID())}\n`);
@@ -802,7 +793,7 @@ export async function continueFlexibleThread(store, sessions, input) {
802
793
  ...(input.seams === undefined ? {} : { seams: input.seams }), ...(input.proven === undefined ? {} : { proven: input.proven }) });
803
794
  if (!begun.ok)
804
795
  return begun;
805
- return { ok: true, turn: admitted.turn, seq: admitted.seq, fresh: begun.launched === "started", replayed: admitted.replayed };
796
+ return { ok: true, turn: admitted.turn, seq: admitted.seq, fresh: begun.launched === "started", replayed: admitted.replayed, ...(admitted.resent === undefined ? {} : { resent: admitted.resent }) };
806
797
  });
807
798
  return locked;
808
799
  }
@@ -895,8 +886,12 @@ export const FLEXIBLE_SHIP_STOPPING = "Toolroll is stopping the thread's agent f
895
886
  export async function flexibleThreadShipTerms(store, input) {
896
887
  if (typeof input.thread !== "string" || !ID.test(input.thread))
897
888
  return refuse("invalid-request");
898
- if (ownThread(store, input.thread, input.by) === null)
889
+ const owned = ownThread(store, input.thread, input.by);
890
+ if (owned === null)
899
891
  return refuse("thread-unknown");
892
+ const needs = flexibleShipNeeds(store, owned.repo);
893
+ if (needs !== null)
894
+ return { ok: false, reason: needs.reason, message: needs.message };
900
895
  const shown = await flexibleShipTerms(store, { thread: input.thread, by: input.by.name });
901
896
  if (!shown.ok)
902
897
  return shown;
@@ -1142,6 +1137,11 @@ function endWordsOf(store, turn, status) {
1142
1137
  if (status !== "interrupted" && status !== "unknown" && status !== "withdrawn")
1143
1138
  return {};
1144
1139
  const detail = store.handle.prepare("SELECT end_detail FROM thread_turn WHERE id = ?").get(turn)?.["end_detail"];
1140
+ if (status === "unknown" && (detail === null || detail === undefined || detail === "The agent stopped with an error.")) {
1141
+ const connection = relayFailureWords(store, turn);
1142
+ if (connection !== null)
1143
+ return { endWords: connection };
1144
+ }
1145
1145
  if (typeof detail !== "string" || detail.trim() === "")
1146
1146
  return {};
1147
1147
  const words = cleanLiveText(detail).trim().slice(0, 500);
@@ -1153,12 +1153,31 @@ function withoutRefusedLines(store, turn, records) {
1153
1153
  if (turn === null || !records.some(one => one.k === "say" && one.t.some(line => AGENT_API_ERROR.test(line))))
1154
1154
  return records;
1155
1155
  const row = flexibleTurn(store, turn);
1156
- if (row?.status !== "interrupted")
1156
+ if (row === null)
1157
+ return records;
1158
+ const words = row.status === "interrupted" ? endWordsOf(store, turn, row.status).endWords : relayFailureWords(store, turn) ?? undefined;
1159
+ if (row.status !== "interrupted" && words === undefined)
1157
1160
  return records;
1158
- const words = endWordsOf(store, turn, row.status).endWords;
1159
1161
  const explained = words === undefined ? FLEXIBLE_REFUSED_LINE_WORDS : `Toolroll: ${words}`;
1160
1162
  return records.map(one => one.k !== "say" || !one.t.some(line => AGENT_API_ERROR.test(line)) ? one : { ...one, t: [explained] });
1161
1163
  }
1164
+ function relayFailureWords(store, turn) {
1165
+ const call = store.handle.prepare("SELECT status, http_status FROM thread_relay_call WHERE turn = ? AND route = 'messages' ORDER BY id DESC LIMIT 1").get(turn);
1166
+ if (call === undefined)
1167
+ return null;
1168
+ const next = "Review changes, then reply to retry.";
1169
+ if (call["status"] === "incomplete")
1170
+ return `Model connection lost. ${next}`;
1171
+ if (call["status"] !== "upstream-error")
1172
+ return null;
1173
+ if (call["http_status"] === null)
1174
+ return `Can't reach the model. ${next}`;
1175
+ if (call["http_status"] === 429)
1176
+ return "Too many model requests. Review changes, then reply later.";
1177
+ if (Number(call["http_status"]) >= 500)
1178
+ return `The model service failed. ${next}`;
1179
+ return null;
1180
+ }
1162
1181
  function recordedTitle(store, thread) {
1163
1182
  const title = store.handle.prepare("SELECT title FROM flexible_thread_meta WHERE thread = ?").get(thread)?.["title"];
1164
1183
  return typeof title === "string" && title !== "" ? title : null;
@@ -1220,3 +1239,52 @@ export async function removeFlexibleThreadCopy(store, input) {
1220
1239
  const removed = await removeFlexibleThread(store, { id: input.thread, by: input.by, now: input.now, ...(input.prove === undefined ? {} : { prove: input.prove }) });
1221
1240
  return removed.ok ? { ok: true } : { ok: false, reason: removed.reason, message: removed.message };
1222
1241
  }
1242
+ export function flexibleShipNeedsFor(store, asked) {
1243
+ if (typeof asked !== "string" || !/^[0-9a-f]{8,32}$/.test(asked))
1244
+ return null;
1245
+ const found = store.handle.prepare("SELECT repo FROM flexible_thread WHERE state = 'ready' AND substr(id, 1, ?) = ? LIMIT 2").all(asked.length, asked);
1246
+ if (found.length !== 1)
1247
+ return null;
1248
+ const needs = flexibleShipNeeds(store, String(found[0]["repo"]));
1249
+ return needs === null ? null : { reason: needs.reason, message: needs.message };
1250
+ }
1251
+ async function stopSessionLocked(store, sessions, input) {
1252
+ const clocked = input.clock === undefined ? {} : { clock: input.clock };
1253
+ const expect = input.expect;
1254
+ if (input.whileOff === true && flexibleAvailable(store))
1255
+ return { ok: true, stopped: true, why: null };
1256
+ if (expect !== undefined) {
1257
+ const now = unsettledLaunch(store, input.thread);
1258
+ if (now === null || now.id !== expect.launch || now.holder !== expect.holder) {
1259
+ const exited = flexibleLaunch(store, expect.launch)?.state === "exited";
1260
+ return { ok: true, stopped: exited, why: exited ? null : "another launch of this thread holds it now" };
1261
+ }
1262
+ }
1263
+ const revoked = revokeFlexibleAnswers(store, sessions.catalog, { thread: input.thread, reason: input.reason, ...clocked, ...(expect === undefined ? {} : { connection: expect.launch }) });
1264
+ if (!revoked.ok)
1265
+ return revoked;
1266
+ const session = sessions.threads.get(input.thread);
1267
+ const ours = session !== undefined && (expect === undefined || session.agent === null || session.agent.launch === expect.launch);
1268
+ if (ours && session?.agent != null) {
1269
+ try {
1270
+ session.agent.stdin.end();
1271
+ }
1272
+ catch { }
1273
+ }
1274
+ const stopped = await stopFlexibleThreadAgent(store, { id: input.thread, reason: input.reason, ...clocked, io: sessions.io, ...(expect === undefined ? {} : { expect }) });
1275
+ const unverified = !("reason" in stopped) && !stopped.ok;
1276
+ if (session !== undefined && ours) {
1277
+ session.agent = null;
1278
+ try {
1279
+ await session.relay?.close();
1280
+ }
1281
+ catch { }
1282
+ session.relay = null;
1283
+ if (!unverified)
1284
+ sessions.threads.delete(input.thread);
1285
+ }
1286
+ bump(sessions, input.thread);
1287
+ if ("reason" in stopped)
1288
+ return stopped;
1289
+ return { ok: true, stopped: stopped.ok, why: stopped.ok ? null : stopped.why };
1290
+ }
@@ -18,6 +18,7 @@ import { localActNow } from "./local-owner.js";
18
18
  import { assignmentOf } from "./assignment.js";
19
19
  import { completeAndOpenPullRequest, mergePullRequest } from "./pull-request-flow.js";
20
20
  import { fullCheckGate } from "./result-follow-ups.js";
21
+ import { CHECK_RECOVERY_HELD, readCheckRecoveryHoldsForRun } from "./check-recovery-hold.js";
21
22
  import { runCheckLevel } from "./check-levels.js";
22
23
  import { FLEXIBLE_FILED_PREFIX } from "./flexible-merge-guard.js";
23
24
  import { run } from "./exec.js";
@@ -70,6 +71,7 @@ const WORDS = Object.freeze({
70
71
  "proof-refused": "That didn't prove it's you, or you can't approve work in this project. Nothing changed.",
71
72
  "handoff-failed": "The changes were imported, but their check task couldn't be made. The import is kept: ship again, or remove it.",
72
73
  "approval-refused": "The changes were imported, but their check task couldn't be approved. The import is kept: ship again, or remove it.",
74
+ "recovery-held": "Checks are on hold after recovery. Earlier execution is unverified.",
73
75
  "not-found": "There's no such Ship.",
74
76
  "wrong-state": "This Ship can't do that now.",
75
77
  "cancelled": "The merge was stopped for good.",
@@ -128,6 +130,23 @@ function destinationOf(store, repo) {
128
130
  return null;
129
131
  return { repo: grant.githubRepo, remote: grant.remote, base: grant.base, method: grant.mergeMethod ?? "squash", capabilities: [...grant.capabilities].sort(), draft: grant.draft };
130
132
  }
133
+ const shellWord = (text) => /^[A-Za-z0-9_./~+@%=:,-]+$/.test(text) ? text : `'${text.replace(/'/g, "'\\''")}'`;
134
+ export function flexibleShipNeeds(store, repo) {
135
+ const noCheck = store.liveVerifyCommand(repo) === null;
136
+ const noPullRequests = destinationOf(store, repo) === null;
137
+ if (!noCheck && !noPullRequests)
138
+ return null;
139
+ const setCheck = `toolroll verify set --repo ${shellWord(repo)} --command "<your test command>"`;
140
+ const setPullRequests = `toolroll publish setup --repo ${shellWord(repo)} --yes`;
141
+ if (noCheck && noPullRequests)
142
+ return { reason: "no-check", short: "Needs a check command and pull requests, which this project doesn't have yet.",
143
+ message: `This project has no check command and can't open pull requests yet, and Ship needs both. Set a check with \`${setCheck}\`, then turn on pull requests with \`${setPullRequests}\` (or both in Settings → Projects). Nothing was shipped.` };
144
+ if (noCheck)
145
+ return { reason: "no-check", short: "Needs a check command, which this project doesn't have yet.",
146
+ message: `This project has no check command yet, and Ship needs one: Toolroll merges only once it passes. Set one with \`${setCheck}\` (or in Settings → Projects). Nothing was shipped.` };
147
+ return { reason: "no-publishing", short: "Needs pull requests, which this project can't open yet.",
148
+ message: `This project can't open pull requests yet, and Ship needs them: the merge goes through one. Turn them on with \`${setPullRequests}\` (or in Settings → Projects). Nothing was shipped.` };
149
+ }
131
150
  export async function flexibleShipTerms(store, input) {
132
151
  const thread = flexibleThread(store, input.thread);
133
152
  if (thread === null)
@@ -352,8 +371,10 @@ function shipOfTask(store, taskId) {
352
371
  }
353
372
  const inFlight = new Set();
354
373
  export const FLEXIBLE_STALE_MERGE_MS = 15 * 60_000;
355
- function cancelArmed(store, ship, why, now, actor = "toolroll") {
374
+ function cancelArmed(store, ship, why, now, actor = "toolroll", recoveryGuard = false) {
356
375
  return store.transact(() => {
376
+ if (recoveryGuard)
377
+ proveShipCheckRecovery(store, ship.taskId);
357
378
  const moved = store.handle.prepare("UPDATE flexible_ship SET state = 'cancelled', detail = ?, state_at = ? WHERE id = ? AND state IN ('armed', 'completed')").run(why.slice(0, 2000), now.toISOString(), ship.id);
358
379
  if (Number(moved.changes) !== 1)
359
380
  return false;
@@ -419,7 +440,19 @@ export async function mergeArmedFlexible(store, input) {
419
440
  return { ok: true, state: "waiting", why: "its merge is under way; its outcome is read back from GitHub" };
420
441
  if (found.state !== "armed" && found.state !== "completed")
421
442
  return refuse("wrong-state", found.state);
422
- const stop = (why) => { cancelArmed(store, found, why, clock()); return refuse("cancelled", why); };
443
+ if (shipCheckRecoveryHeld(store, found.taskId))
444
+ return refuse("recovery-held");
445
+ const stop = (why) => {
446
+ try {
447
+ cancelArmed(store, found, why, clock(), "toolroll", true);
448
+ }
449
+ catch (error) {
450
+ if (error instanceof ShipStop)
451
+ return error.refusal;
452
+ throw error;
453
+ }
454
+ return refuse("cancelled", why);
455
+ };
423
456
  const lapsed = authorityProblem(store, found);
424
457
  if (lapsed !== null)
425
458
  return stop(lapsed);
@@ -430,8 +463,18 @@ export async function mergeArmedFlexible(store, input) {
430
463
  catch {
431
464
  return { ok: true, state: "waiting", why: "the project can't be read" };
432
465
  }
433
- const read = hardenedGit(input.runner ?? run, "read", { repo: project });
434
- const based = await read("git", ["--no-replace-objects", "merge-base", "--is-ancestor", found.base, `refs/heads/${found.terms.github.base}`], { cwd: project, timeoutMs: 30_000 });
466
+ const read = hardenedGit((file, args, options) => { proveShipCheckRecovery(store, found.taskId); return (input.runner ?? run)(file, args, options); }, "read", { repo: project });
467
+ let based;
468
+ try {
469
+ based = await read("git", ["--no-replace-objects", "merge-base", "--is-ancestor", found.base, `refs/heads/${found.terms.github.base}`], { cwd: project, timeoutMs: 30_000 });
470
+ }
471
+ catch (error) {
472
+ if (error instanceof ShipStop)
473
+ return error.refusal;
474
+ throw error;
475
+ }
476
+ if (shipCheckRecoveryHeld(store, found.taskId))
477
+ return refuse("recovery-held");
435
478
  if (based.code === 1)
436
479
  return stop(`its starting commit is no longer on ${found.terms.github.base}`);
437
480
  if (based.code !== 0)
@@ -457,15 +500,17 @@ export async function mergeArmedFlexible(store, input) {
457
500
  const again = rowOfTask(store, input.taskId);
458
501
  if (again === null || again.state !== "armed")
459
502
  throw new ShipStop(refuse("wrong-state"));
503
+ proveShipCheckRecovery(store, again.taskId);
460
504
  const problem = authorityProblem(store, again);
461
505
  if (problem !== null) {
462
- cancelArmed(store, again, problem, clock());
506
+ cancelArmed(store, again, problem, clock(), "toolroll", true);
463
507
  cancelled = refuse("cancelled", problem);
464
508
  return;
465
509
  }
466
510
  const who = verifyApproverStanding(store, again.approvedBy, again.approvedGeneration, [again.repo]);
467
511
  if (!who.ok)
468
512
  throw new ShipStop(refuse("not-an-approver"));
513
+ proveShipCheckRecovery(store, again.taskId);
469
514
  const opened = completeAndOpenPullRequest(store, { taskId: input.taskId, digest: receipt.digest, runId: newest.id, who: who.who, root: input.root }, clock());
470
515
  if (!opened.ok)
471
516
  throw new ShipStop(refuse("wrong-state", opened.message));
@@ -473,6 +518,7 @@ export async function mergeArmedFlexible(store, input) {
473
518
  throw new ShipStop(refuse("wrong-state", "its pull request would go somewhere other than the shipped commit and destination"));
474
519
  }
475
520
  const at = clock().toISOString();
521
+ proveShipCheckRecovery(store, again.taskId);
476
522
  store.handle.prepare("UPDATE flexible_ship SET state = 'completed', merge_head = ?, merge_at = ?, check_receipt = ?, state_at = ? WHERE id = ? AND state = 'armed'").run(head, at, check, at, again.id);
477
523
  store.recordAction({ at, actor: again.approvedBy, repo: again.repo, taskId: input.taskId, runId: newest.id, source: "work", action: "flexible ship completed", outcome: head,
478
524
  detail: `ship ${again.id} · checked head ${head} · check receipt ${check} · pull request owed to ${again.terms.github.repo} ${again.terms.github.base}` });
@@ -480,7 +526,7 @@ export async function mergeArmedFlexible(store, input) {
480
526
  }
481
527
  catch (error) {
482
528
  if (error instanceof ShipStop)
483
- return error.refusal.reason === "cancelled" ? error.refusal : { ok: true, state: "waiting", why: error.refusal.message };
529
+ return error.refusal.reason === "cancelled" || error.refusal.reason === "recovery-held" ? error.refusal : { ok: true, state: "waiting", why: error.refusal.message };
484
530
  throw error;
485
531
  }
486
532
  if (cancelled !== null)
@@ -499,24 +545,38 @@ export async function mergeArmedFlexible(store, input) {
499
545
  const prNumber = publication.prNumber;
500
546
  const token = randomBytes(16).toString("hex");
501
547
  const destination = (seen) => pullRequestElsewhere(found, seen, prNumber) ?? (seen.head !== found.mergeHead ? "its pull request on GitHub shows another commit than the one whose check passed" : null);
548
+ if (shipCheckRecoveryHeld(store, found.taskId))
549
+ return refuse("recovery-held");
502
550
  inFlight.add(token);
503
551
  let merged;
504
552
  try {
505
553
  merged = await mergePullRequest(store, { runId: newest.id, by: found.approvedBy, flexibleShip: found.id, flexibleToken: token, clock, destination, ...(input.exec === undefined ? {} : { exec: input.exec }),
506
554
  proceed: seen => reserveMerge(store, { ship: found.id, token, runId: newest.id, root: input.root, now: clock(), seen, prNumber }) });
507
555
  }
556
+ catch (error) {
557
+ if (error instanceof ShipStop)
558
+ return error.refusal;
559
+ throw error;
560
+ }
508
561
  finally {
509
562
  inFlight.delete(token);
510
563
  }
511
564
  const landedElsewhere = merged.ok ? (merged.seen === undefined ? "GitHub didn't say where it merged" : destination(merged.seen)) : merged.reason === "elsewhere" ? merged.message : null;
512
565
  if (landedElsewhere !== null) {
566
+ let held = false;
513
567
  store.transact(() => {
568
+ if (shipCheckRecoveryHeld(store, found.taskId)) {
569
+ held = true;
570
+ return;
571
+ }
514
572
  const moved = store.handle.prepare("UPDATE flexible_ship SET state = 'cancelled', merge_token = NULL, merge_reserved_at = NULL, detail = ?, state_at = ? WHERE id = ? AND state IN ('completed', 'merging')")
515
573
  .run(`${landedElsewhere} (GitHub reports it merged there, not as this Ship's merge)`.slice(0, 2000), clock().toISOString(), found.id);
516
574
  if (Number(moved.changes) === 1)
517
575
  store.recordAction({ at: clock().toISOString(), actor: "toolroll", repo: found.repo, taskId: input.taskId, runId: newest.id, source: "policy",
518
576
  action: "flexible merge cancelled", outcome: "merged-elsewhere", detail: `ship ${found.id} · ${landedElsewhere}`.slice(0, 2000) });
519
577
  });
578
+ if (held)
579
+ return { ok: true, state: "waiting", why: WORDS["recovery-held"] };
520
580
  return refuse("cancelled", landedElsewhere);
521
581
  }
522
582
  const after = rowOfTask(store, input.taskId);
@@ -540,10 +600,11 @@ function reserveMerge(store, input) {
540
600
  const ship = readRow(store.handle.prepare("SELECT * FROM flexible_ship WHERE id = ?").get(input.ship));
541
601
  if (ship === null || ship.state !== "completed" || ship.taskId === null)
542
602
  return false;
603
+ proveShipCheckRecovery(store, ship.taskId);
543
604
  const elsewhere = pullRequestElsewhere(ship, input.seen, input.prNumber);
544
605
  const problem = elsewhere ?? authorityProblem(store, ship);
545
606
  if (problem !== null) {
546
- cancelArmed(store, ship, problem, input.now);
607
+ cancelArmed(store, ship, problem, input.now, "toolroll", true);
547
608
  return false;
548
609
  }
549
610
  const newest = newestRun(store, ship.taskId);
@@ -552,6 +613,7 @@ function reserveMerge(store, input) {
552
613
  if (passingCheck(store, input.root, newest.id, ship, input.now) !== ship.checkReceipt)
553
614
  return false;
554
615
  const at = input.now.toISOString();
616
+ proveShipCheckRecovery(store, ship.taskId);
555
617
  const moved = store.handle.prepare("UPDATE flexible_ship SET state = 'merging', merge_token = ?, merge_reserved_at = ?, state_at = ? WHERE id = ? AND state = 'completed'").run(input.token, at, at, ship.id);
556
618
  if (Number(moved.changes) !== 1)
557
619
  return false;
@@ -582,7 +644,12 @@ async function settleMerging(store, ship, exec, clock) {
582
644
  const elsewhere = pullRequestElsewhere(ship, { base, url }, publication.prNumber);
583
645
  const outcome = elsewhere !== null ? "cancelled" : state === "MERGED" ? "merged" : state === "OPEN" && headOid === ship.mergeHead ? "completed" : "cancelled";
584
646
  const why = elsewhere !== null ? `${elsewhere}${state === "MERGED" ? " (GitHub merged it there)" : ""}` : `its pull request is ${state.toLowerCase()} on GitHub${headOid !== ship.mergeHead ? " on another commit" : ""}`;
647
+ let held = false;
585
648
  store.transact(() => {
649
+ if (shipCheckRecoveryHeld(store, ship.taskId) && !(state === "MERGED" && elsewhere === null && headOid === ship.mergeHead)) {
650
+ held = true;
651
+ return;
652
+ }
586
653
  const moved = store.handle.prepare(`UPDATE flexible_ship SET state = ?, merge_token = NULL, merge_reserved_at = NULL, state_at = ?${outcome === "cancelled" ? ", detail = ?" : ""} WHERE id = ? AND state = 'merging' AND merge_token = ?`)
587
654
  .run(...(outcome === "cancelled" ? [outcome, at, why.slice(0, 2000), ship.id, ship.mergeToken] : [outcome, at, ship.id, ship.mergeToken]));
588
655
  if (Number(moved.changes) !== 1)
@@ -590,6 +657,8 @@ async function settleMerging(store, ship, exec, clock) {
590
657
  store.recordAction({ at, actor: "toolroll", repo: ship.repo, taskId: ship.taskId, runId: newest?.id ?? null, source: "policy", action: outcome === "merged" ? "flexible merged" : outcome === "completed" ? "flexible merge released" : "flexible merge cancelled",
591
658
  outcome: outcome === "merged" ? commit ?? "merged" : outcome, detail: `ship ${ship.id} · read back from GitHub: ${state.toLowerCase()}` });
592
659
  });
660
+ if (held)
661
+ return { ok: true, state: "waiting", why: WORDS["recovery-held"] };
593
662
  if (outcome === "merged")
594
663
  return { ok: true, state: "merged" };
595
664
  if (outcome === "completed")
@@ -747,3 +816,14 @@ export async function removeFlexibleImport(store, input) {
747
816
  });
748
817
  return { ok: true };
749
818
  }
819
+ function shipCheckRecoveryHeld(store, taskId) {
820
+ if (taskId === null || store.handle.prepare("SELECT 1 FROM action_ledger WHERE action = ? LIMIT 1").get(CHECK_RECOVERY_HELD) === undefined)
821
+ return false;
822
+ const ref = store.lookupRef(taskId);
823
+ const seed = ref === null ? undefined : store.handle.prepare("SELECT id FROM run WHERE task_ref = ? ORDER BY id DESC LIMIT 1").get(ref.id);
824
+ return seed === undefined || readCheckRecoveryHoldsForRun(store, Number(seed["id"])).kind !== "no-evidence";
825
+ }
826
+ function proveShipCheckRecovery(store, taskId) {
827
+ if (shipCheckRecoveryHeld(store, taskId))
828
+ throw new ShipStop(refuse("recovery-held"));
829
+ }
@@ -473,3 +473,13 @@ export function signInEpochOf(store, person) {
473
473
  function raiseSignInEpoch(store, person) {
474
474
  store.handle.prepare("INSERT INTO flexible_sign_in_epoch (person, epoch) VALUES (?, 1) ON CONFLICT (person) DO UPDATE SET epoch = epoch + 1").run(person);
475
475
  }
476
+ export function signInForInteractiveStands(store, sessionId) {
477
+ const session = store.handle.prepare("SELECT * FROM flexible_interactive_session WHERE id = ? AND state IN ('prepared', 'active')").get(sessionId);
478
+ if (session === undefined || session["provider"] !== "claude" || session["billing"] !== "subscription")
479
+ return false;
480
+ const thread = store.handle.prepare("SELECT created_by FROM flexible_thread WHERE id = ?").get(session["thread"]);
481
+ if (thread === undefined || thread["created_by"] !== session["owner"] || signInEpochOf(store, String(session["owner"])) !== session["sign_in_epoch"])
482
+ return false;
483
+ const billing = flexibleSignInBilling(store, { name: String(session["owner"]), generation: Number(session["account_generation"]) });
484
+ return billing.ok && billing.billing === "subscription";
485
+ }
@@ -2,7 +2,9 @@ import { createHash } from "node:crypto";
2
2
  import { flexibleAvailable } from "./flexible-available.js";
3
3
  import { FLEXIBLE_LAPSE_WORDS, FLEXIBLE_LEVEL_WORDS, FLEXIBLE_UNAVAILABLE, flexibleStanding, FULL_ACCESS_WORDS, OPEN_NETWORK_WORDS } from "./flexible.js";
4
4
  import { flexibleNetworkDigest, flexibleThreadNetwork } from "./flexible-launcher.js";
5
+ import { FLEXIBLE_RELAY_UPSTREAMS } from "./flexible-relay-upstreams.js";
5
6
  import { flexibleSignInBilling, flexibleSignInStatus } from "./flexible-sign-in.js";
7
+ import { flexibleShipNeeds } from "./flexible-ship.js";
6
8
  import { networkWords } from "./egress.js";
7
9
  import { agentModelName } from "./model-names.js";
8
10
  import { CLAUDE_EXACT } from "./model-catalog.js";
@@ -26,6 +28,12 @@ export const FLEXIBLE_UNKNOWN_COST_WORDS = "If Toolroll can't measure what a tur
26
28
  export function flexibleStartCard(store, input) {
27
29
  if (!flexibleAvailable(store))
28
30
  return refuse("not-available");
31
+ const helperModels = [...new Set(input.helperModels ?? [])].sort();
32
+ if (helperModels.some(model => !FLEXIBLE_RELAY_UPSTREAMS.claude.helperModels.test(model)))
33
+ return refuse("invalid-request");
34
+ const runtime = input.runtime ?? "stream-json";
35
+ if (runtime !== "stream-json" && runtime !== "interactive")
36
+ return refuse("invalid-request");
29
37
  const model = input.model === null || input.model === "" ? FLEXIBLE_DEFAULT_MODEL : input.model;
30
38
  if (typeof input.repo !== "string" || input.repo === "" || typeof model !== "string" || !RELAY_MODEL.test(model) || typeof input.message !== "string"
31
39
  || typeof input.by?.name !== "string" || !Number.isSafeInteger(input.by.generation))
@@ -47,11 +55,14 @@ export function flexibleStartCard(store, input) {
47
55
  if (!credential.ok)
48
56
  return refuse(credential.reason);
49
57
  const billing = credential.billing;
58
+ if (runtime === "interactive" && billing !== "subscription")
59
+ return refuse("invalid-request");
50
60
  const signedIn = flexibleSignInStatus(store, input.by.name);
51
61
  const savedOn = signedIn.state === "none" ? null : signedIn.savedAt.slice(0, 10);
52
62
  const open = network.mode === "open";
53
63
  const project = store.handle.prepare("SELECT name FROM project WHERE path = ?").get(input.repo)?.["name"];
54
64
  const caps = terms.caps;
65
+ const shipNeeds = flexibleShipNeeds(store, input.repo);
55
66
  const decisions = [
56
67
  { label: "Project", words: typeof project === "string" ? project : input.repo, lines: typeof project === "string" ? [input.repo] : [], fields: ["flexible.repo"] },
57
68
  { label: "Level", words: `${FLEXIBLE_LEVEL_WORDS.full}: no permission prompts inside the sandbox`, lines: [FULL_ACCESS_WORDS], fields: ["flexible.level"], risky: true },
@@ -66,9 +77,16 @@ export function flexibleStartCard(store, input) {
66
77
  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.`,
67
78
  FLEXIBLE_UNKNOWN_COST_WORDS,
68
79
  ], fields: ["flexible.caps"], ...(caps.measuredMicrousdPerDay === null ? { risky: true } : {}) },
69
- { label: "Ship", words: FLEXIBLE_SHIP_WORDS, fields: ["flexible.ship"] },
80
+ shipNeeds === null ? { label: "Ship", words: FLEXIBLE_SHIP_WORDS, fields: ["flexible.ship"] }
81
+ : { label: "Ship", words: shipNeeds.short, lines: [`After that: ${lowerFirst(FLEXIBLE_SHIP_WORDS)}`], fields: ["flexible.ship"] },
70
82
  { 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"] },
71
83
  ];
84
+ if (runtime === "interactive") {
85
+ decisions.splice(decisions.findIndex(row => row.label === "Limits"), 1);
86
+ decisions.push({ label: "Concurrent agents", words: `${plural(caps.liveThreads, "thread")} at once in this project`, fields: ["flexible.caps"] });
87
+ decisions.push({ label: "Runtime", words: "Interactive Claude, using your subscription; no turn or cost limits", lines: helperModels.length === 0 ? [] : [`Permitted helper models: ${helperModels.join(", ")}`], fields: ["flexible.agent"] });
88
+ decisions.find(row => row.label === "Agent").lines = ["Your Claude subscription powers this interactive session. Your sign-in stays with Toolroll."];
89
+ }
72
90
  const warnings = [
73
91
  { words: "The agent can read this repository's whole history, not just the commit it starts from.", fields: ["flexible.repository"] },
74
92
  { 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"] },
@@ -76,10 +94,10 @@ export function flexibleStartCard(store, input) {
76
94
  ];
77
95
  const digestOfMessage = createHash("sha256").update(input.message, "utf8").digest("hex");
78
96
  const networkDigest = flexibleNetworkDigest(network);
79
- 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,
97
+ const key = createHash("sha256").update(JSON.stringify({ v: 1, kind: "standing-orders:flexible-start", termsId: standing.id, digest: standing.digest, repo: input.repo, by: input.by, runtime, helperModels, model, level: "full", billing,
80
98
  network: networkDigest, message: digestOfMessage, decisions, warnings }), "utf8").digest("hex").slice(0, 32);
81
99
  const summary = { revision: null, revisionNotes: [], revisionChanges: [], decisions, why: null, differs: [], warnings, usual: [], usualLabel: "Other settings", usualSummary: "", key };
82
- return { ok: true, card: { summary, digest: standing.digest, network: networkDigest, model, level: "full", billing, terms } };
100
+ return { ok: true, card: { summary, termsId: standing.id, digest: standing.digest, network: networkDigest, model, level: "full", billing, runtime, helperModels, terms } };
83
101
  }
84
102
  export const FLEXIBLE_NEXT_WORDS = Object.freeze({
85
103
  "turn-on": "Threads are off. Turn them on in Settings → General, or with `toolroll config set flexible on`. Nothing was started.",
@@ -5,7 +5,7 @@ import { homedir, tmpdir } from "node:os";
5
5
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
6
6
  import { flexibleAvailable } from "./flexible-available.js";
7
7
  import { FLEXIBLE_UNAVAILABLE } from "./flexible.js";
8
- import { buildCacheEnv, fenceFor, FLEXIBLE_THREADS_DIR, grantFolder, PROTECTED_DIRS, PROTECTED_FILES, runFolders, srtTermsOf } from "./agent-fence.js";
8
+ import { buildCacheEnv, fenceFor, FLEXIBLE_THREADS_DIR, grantFolder, plainAgentEnv, PROTECTED_DIRS, PROTECTED_FILES, runFolders, srtTermsOf } from "./agent-fence.js";
9
9
  import { ACP_AGENTS, ACP_PROVIDER_IDS } from "./acp-agents.js";
10
10
  import { confined, ContainmentRefusal, run } from "./exec.js";
11
11
  import { SANDBOX_LAUNCH_SPEC, SEATBELT_NO_KEYCHAIN } from "./sandbox-runtime.js";
@@ -437,9 +437,8 @@ export function flexibleThreadFence(store, input) {
437
437
  return { ok: true, launch: { ...made, fenceGrants: grants }, paths, thread };
438
438
  }
439
439
  export function flexibleThreadEnv(paths, proxy, base = process.env) {
440
- const kept = ["PATH", "LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES", "TERM", "TZ", "USER", "LOGNAME", "SHELL", "COLORTERM"];
441
440
  return {
442
- ...Object.fromEntries(kept.flatMap(name => base[name] === undefined ? [] : [[name, base[name]]])),
441
+ ...plainAgentEnv(base),
443
442
  HOME: real(homedir()), TMPDIR: paths.tmp, ...buildCacheEnv(paths.cache),
444
443
  GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1",
445
444
  ...proxy,
@@ -173,10 +173,22 @@ export function admitFlexibleTurn(store, input) {
173
173
  const delegation = flexibleDelegationAtUse(store, { repo, starter: input.starter, digest: input.digest, level: input.level, freshProof: input.freshProof });
174
174
  if (!delegation.ok)
175
175
  return delegation;
176
- const same = readTurn(store.handle.prepare("SELECT * FROM thread_turn WHERE thread = ? AND request_key = ? AND status <> 'withdrawn'").get(input.thread, input.requestKey));
177
- if (same !== null) {
178
- if (same.status !== "admitted")
176
+ const attempts = store.handle.prepare(`SELECT * FROM thread_turn WHERE thread = ? AND (request_key = ? OR substr(request_key, 1, ?) = ?) AND status <> 'withdrawn' ORDER BY seq DESC`)
177
+ .all(input.thread, input.requestKey, input.requestKey.length + AGAIN.length, `${input.requestKey}${AGAIN}`);
178
+ let same = readTurn(attempts[0]);
179
+ let requestKey = input.requestKey;
180
+ let resent;
181
+ if (same !== null && same.status !== "admitted") {
182
+ const detail = text(attempts[0]["end_detail"]);
183
+ if (same.status === "running" || turnLaunched(store, same.id))
184
+ return { ok: false, reason: "already-sent", message: deliveredWords(same, detail) };
185
+ requestKey = `${input.requestKey}${AGAIN}${attempts.length}`;
186
+ if (requestKey.length > 128)
179
187
  return refuse("already-sent");
188
+ resent = { seq: same.seq, detail };
189
+ same = null;
190
+ }
191
+ if (same !== null) {
180
192
  if (same.termsId !== delegation.termsId) {
181
193
  withdrawTurn(store, same, "admitted under terms that have since ended", now.toISOString());
182
194
  }
@@ -219,13 +231,13 @@ export function admitFlexibleTurn(store, input) {
219
231
  const seq = Number(store.handle.prepare("SELECT COALESCE(MAX(seq), 0) + 1 AS n FROM thread_turn WHERE thread = ?").get(input.thread)["n"]);
220
232
  const at = now.toISOString();
221
233
  store.handle.prepare(`INSERT INTO thread_turn (id, thread, seq, repo, owner, owner_generation, terms_id, terms_digest, level, provider, model, billing, request_key, holder, admitted_at, utc_day, rail_reserved, status)
222
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'admitted')`).run(id, input.thread, seq, repo, input.starter.name, input.starter.generation, delegation.termsId, delegation.digest, input.level, input.provider, input.model, input.billing, input.requestKey, input.holder, at, day, railReserved);
234
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'admitted')`).run(id, input.thread, seq, repo, input.starter.name, input.starter.generation, delegation.termsId, delegation.digest, input.level, input.provider, input.model, input.billing, requestKey, input.holder, at, day, railReserved);
223
235
  if (chosenLevel !== null && FLEXIBLE_LEVELS.indexOf(input.level) > FLEXIBLE_LEVELS.indexOf(chosenLevel)) {
224
236
  store.handle.prepare("UPDATE flexible_thread_level SET level = ?, set_by = ?, set_at = ? WHERE thread = ?").run(input.level, input.starter.name, at, input.thread);
225
237
  }
226
238
  store.recordAction({ at, actor: input.starter.name, repo, taskId: null, runId: null, source: "policy", action: "flexible turn admitted", outcome: "admitted",
227
239
  detail: `thread ${input.thread} · turn ${seq} · ${input.level} · ${input.provider} ${input.model} · ${input.billing} · terms ${delegation.digest}` });
228
- return { ok: true, turn: id, seq, replayed: false };
240
+ return { ok: true, turn: id, seq, replayed: false, ...(resent === undefined ? {} : { resent }) };
229
241
  });
230
242
  }
231
243
  function countsRefusal(store, repo, person, terms, now) {
@@ -502,3 +514,12 @@ export function interruptFlexibleTurnSignIn(store, input) {
502
514
  return { ok: true, interrupted: done };
503
515
  });
504
516
  }
517
+ const AGAIN = ":again-";
518
+ function turnLaunched(store, turn) {
519
+ return store.handle.prepare("SELECT 1 AS hit FROM action_ledger WHERE action = 'flexible agent launched' AND detail LIKE ? LIMIT 1").get(`turn ${turn} · %`) !== undefined;
520
+ }
521
+ function deliveredWords(turn, detail) {
522
+ const state = turn.status === "running" ? "it is still working" : turn.status === "finished" ? "it finished" : turn.status === "interrupted" ? "it was stopped" : "its outcome is unknown";
523
+ const why = detail === null || detail.trim() === "" || turn.status === "running" || turn.status === "finished" ? "" : ` (${detail.trim().slice(0, 300)})`;
524
+ return `That message already reached the agent in turn ${turn.seq}, and ${state}${why}. Nothing new was started.`;
525
+ }