toolroll 0.9.116 → 0.9.118

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 (136) hide show
  1. package/CHANGELOG.md +46 -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 +93 -16
  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 +12 -2
  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/coding-context.js +16 -2
  31. package/dist/coding-provider.js +7 -3
  32. package/dist/coding-workspace.js +5 -5
  33. package/dist/connect-cli.js +257 -11
  34. package/dist/contracts/chat-actions.js +4 -0
  35. package/dist/contracts/console-api.js +14 -3
  36. package/dist/contracts/engine-api.js +331 -2
  37. package/dist/contracts/lead-tools.js +56 -2
  38. package/dist/contracts/provider.js +1 -1
  39. package/dist/contracts/route.js +1 -1
  40. package/dist/contracts/terminal-connection.js +50 -0
  41. package/dist/converse.js +80 -4
  42. package/dist/device-pair.js +280 -0
  43. package/dist/direct-chat-artifacts.js +347 -0
  44. package/dist/direct-chat-catalog.js +311 -0
  45. package/dist/direct-chat-fence.js +96 -0
  46. package/dist/direct-chat-git.js +343 -0
  47. package/dist/direct-chat-laptop.js +19 -0
  48. package/dist/direct-chat-schema.js +181 -0
  49. package/dist/direct-chat-ship.js +861 -0
  50. package/dist/direct-chat-workspace.js +389 -0
  51. package/dist/direct-chat.js +2107 -0
  52. package/dist/doctor.js +1 -1
  53. package/dist/easy-start.js +18 -0
  54. package/dist/egress.js +25 -4
  55. package/dist/engine-chat.js +454 -0
  56. package/dist/engine-reads.js +141 -13
  57. package/dist/exec.js +4 -3
  58. package/dist/flexible-agents.js +8 -16
  59. package/dist/flexible-session.js +91 -47
  60. package/dist/flexible-ship.js +87 -7
  61. package/dist/flexible-start.js +4 -1
  62. package/dist/flexible-thread.js +2 -3
  63. package/dist/flexible-turns.js +26 -5
  64. package/dist/flow-triggers.js +13 -4
  65. package/dist/flows-ui.js +54 -20
  66. package/dist/handoff-cli.js +630 -0
  67. package/dist/invoke.js +71 -17
  68. package/dist/lead-contract.js +5 -4
  69. package/dist/lead-doors.js +80 -1
  70. package/dist/lead-progress.js +9 -0
  71. package/dist/lead-tools.js +681 -10
  72. package/dist/lead.js +37 -9
  73. package/dist/live-bus.js +11 -0
  74. package/dist/live-terminal.js +132 -12
  75. package/dist/local-handoff.js +363 -0
  76. package/dist/local-owner-acts.js +264 -2
  77. package/dist/local-owner.js +16 -1
  78. package/dist/multiplayer-handoff.js +528 -0
  79. package/dist/multiplayer-presence.js +471 -0
  80. package/dist/names.js +17 -4
  81. package/dist/needs-you.js +10 -0
  82. package/dist/operate.js +280 -19
  83. package/dist/planner.js +6 -1
  84. package/dist/policy.js +2 -2
  85. package/dist/project-delete-ui.js +18 -11
  86. package/dist/project-delete.js +65 -4
  87. package/dist/project-skills.js +28 -13
  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/scout.js +6 -2
  102. package/dist/serve.js +49 -5
  103. package/dist/server/chat.js +94 -13
  104. package/dist/server/direct-chat.js +583 -0
  105. package/dist/server/engine-api.js +219 -21
  106. package/dist/server/flows.js +43 -10
  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/skills-manifest.js +57 -0
  123. package/dist/store.js +499 -56
  124. package/dist/subscription-chat.js +33 -6
  125. package/dist/subscription-usage.js +233 -0
  126. package/dist/task-live.js +2 -1
  127. package/dist/teardown-git.js +34 -4
  128. package/dist/terminal-connection.js +159 -0
  129. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  130. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  131. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  132. package/dist/tui/linux-x64/toolroll-tui +0 -0
  133. package/dist/tui-contract.js +1 -1
  134. package/dist/tui-launch.js +32 -1
  135. package/dist/workspace-identity-schema.js +21 -0
  136. package/package.json +4 -2
@@ -1,6 +1,6 @@
1
1
  import { agentSaidOf, planProblemsOf } from "./store.js";
2
- import { failedAttemptSentence, latestFinishedAttempt, stopSuggestionOf } from "./needs-you.js";
3
- import { planSourceOf, retryPinsOf } from "./local-owner-acts.js";
2
+ import { codexOfflineDependencySuggestion, failedAttemptSentence, latestFinishedAttempt, stopSuggestionOf } from "./needs-you.js";
3
+ import { pendingAgentChangeOf, planSourceOf, retryPinsOf } from "./local-owner-acts.js";
4
4
  import { assignmentOf, owedAcceptance, personCompletionRefusal } from "./assignment.js";
5
5
  import { assignmentCardOf } from "./assignment-ui.js";
6
6
  import { assignmentStageOf, stageOfCode } from "./task-status.js";
@@ -9,18 +9,24 @@ import { stepRowsOf } from "./workspace-ui.js";
9
9
  import { approvalOf } from "./scope.js";
10
10
  import { approvalSummaryOf, summaryContextOf } from "./approval-summary.js";
11
11
  import { taskWorkSummaryOf } from "./work-summary.js";
12
- import { terminalDiffView } from "./result-evidence-readers.js";
13
- import { parseReviewDiff } from "./server/render-results.js";
12
+ import { structuredHandoffView, terminalDiffView } from "./result-evidence-readers.js";
13
+ import { parseReviewDiff, proofBundleView } from "./server/render-results.js";
14
+ import { parseReport } from "./scout-report.js";
14
15
  import { revisionSourceOf } from "./result-review.js";
15
16
  import { DIFF_CONTEXT_MAX, ENGINE_API_VERSION } from "./contracts/engine-api.js";
16
17
  import { agentSetupOf, detectionLines, NO_AGENT_YET, npmRegistryOf } from "./agent-detect.js";
17
- import { scanPatchForSecrets } from "./evidence.js";
18
+ import { readVerifiedArtifact, reportShotsOf, scanPatchForSecrets } from "./evidence.js";
18
19
  import { fastCompletionProblem } from "./fast-start.js";
19
20
  import { viewedGitSync } from "./teardown-git.js";
20
21
  import { wasInterrupted } from "./run-ending.js";
22
+ import { agentChoicesFor, routeOfTask } from "./agentconfig.js";
21
23
  export const isResultRun = (run) => run.finishedAt !== null && (run.role === "builder" || run.role === "scout");
24
+ export const isTakeOverRun = (run) => run.role === "builder" || run.role === "scout";
25
+ const VALID_SHA = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
26
+ export const validSha = (value) => value !== null && value !== undefined && VALID_SHA.test(value) ? value : null;
27
+ export const takeOverRevisionOf = (run) => validSha(run.headRevision) ?? validSha(run.baseRevision);
22
28
  const AUTOMATIC = new Set(["auto-check", "auto-green"]);
23
- export function stepCardsOf({ store, family, now, access, evidenceRoot, viewer = null }) {
29
+ export function stepCardsOf({ store, family, now, access, evidenceRoot, viewer = null, withChoices = false }) {
24
30
  const current = family.current, root = family.root;
25
31
  const ref = store.lookupRef(current.id);
26
32
  const scope = store.getScope(current.id);
@@ -84,13 +90,18 @@ export function stepCardsOf({ store, family, now, access, evidenceRoot, viewer =
84
90
  chain: justCode ? "just-code" : "plan-first",
85
91
  headline: current.state === "cancelled" ? "Cancelled" : card?.status.headline ?? null,
86
92
  liveRun: live?.id ?? null,
93
+ latestRun: runs.reduce((max, run) => max === null || run.id > max ? run.id : max, null),
94
+ models: (() => {
95
+ const routed = routeOfTask(store, current.id, ref, now);
96
+ return routed?.kind === "route" ? routed.route.legs.map(leg => ({ phase: leg.phase, provider: leg.provider, model: leg.model, chosen: leg.chosen })) : null;
97
+ })(),
87
98
  cards,
88
99
  review: assignment !== null && assignment.state === "ready-to-check" && assignment.receipt !== null && assignment.receipt.taskId === current.id
89
100
  ? { run: assignment.receipt.runId, receipt: assignment.receipt.digest, source: revisionSourceOf(scope?.digest ?? null),
90
101
  accept: acceptFactsOf(store, assignment, viewer, evidenceRoot) } : null,
91
102
  shell: shellOf(store, family, assignment !== null && assignment.state === "ready-to-check" && assignment.receipt !== null && assignment.receipt.taskId === current.id
92
103
  ? assignment.receipt.runId : builds[0]?.id ?? null),
93
- failure: current.state === "failed" ? failureOf(store, ref?.id ?? null, builds) : null,
104
+ failure: current.state === "failed" ? failureOf(store, ref?.id ?? null, current.repo, builds) : null,
94
105
  waiting: (() => {
95
106
  const waiting = waitingOf(store, current.id, now);
96
107
  if (waiting === null)
@@ -105,6 +116,9 @@ export function stepCardsOf({ store, family, now, access, evidenceRoot, viewer =
105
116
  planQueued: planQueuedOf(store, current.state, ref, scope, live !== null, now),
106
117
  approval: scope !== null && approved && scope.approvedBy !== null
107
118
  ? { by: scope.approvedBy, you: viewer !== null && scope.approvedBy === viewer, automatic: AUTOMATIC.has(String(scope.approvalBasis ?? "")) } : null,
119
+ scopeDigest: scope?.digest ?? null,
120
+ agentChoices: scope === null || !withChoices ? null : agentChoicesOf(store, current.id, ref, now),
121
+ pendingAgentChange: ref === null ? null : pendingAgentChangeOf(store, ref.id),
108
122
  room: `task:${encodeURIComponent(root.id)}`,
109
123
  };
110
124
  }
@@ -113,20 +127,27 @@ export const SHELL_NO_COMMIT = "This build has no saved commit to open a termina
113
127
  function shellOf(store, family, runId) {
114
128
  if (runId === null)
115
129
  return null;
116
- const run = resultRunsOf(store, family).find(one => one.id === runId) ?? null;
130
+ const run = resultRunsOf(store, family).find(one => one.id === runId)
131
+ ?? takeOverRunsOf(store, family).find(one => one.id === runId)
132
+ ?? null;
117
133
  if (run === null)
118
134
  return { run: runId, why: SHELL_NO_RESULT };
119
- const revision = run.headRevision;
120
- if (revision === null || !/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(revision))
135
+ if (takeOverRevisionOf(run) === null)
121
136
  return { run: runId, why: SHELL_NO_COMMIT };
122
137
  return { run: runId, why: null };
123
138
  }
124
- function failureOf(store, taskRef, builds) {
139
+ function failureOf(store, taskRef, repo, builds) {
125
140
  const last = latestFinishedAttempt(builds);
126
141
  const failedInARow = taskRef === null ? 0
127
142
  : Number(store.handle.prepare("SELECT strikes FROM task_ref WHERE id = ?").get(taskRef)?.["strikes"] ?? 0);
128
- return { line: failedAttemptSentence(last?.reason), failedInARow, suggestion: last === null ? null : stopSuggestionOf(last.reason),
129
- agentSaid: last === null ? null : agentSaidOf(store, last.id) };
143
+ const agentSaid = last === null ? null : agentSaidOf(store, last.id);
144
+ const codexHint = last === null || last.provider !== "codex" ? null : codexOfflineDependencySuggestion({
145
+ provider: last.provider,
146
+ agentSaid,
147
+ hasSetup: repo !== null && store.liveWorktreeSetup(repo) !== null,
148
+ });
149
+ return { line: failedAttemptSentence(last?.reason), failedInARow, suggestion: last === null ? null : (codexHint ?? stopSuggestionOf(last.reason)),
150
+ agentSaid };
130
151
  }
131
152
  function cancelledCards(builds, at) {
132
153
  const out = [];
@@ -198,6 +219,9 @@ function runFacts(runs) {
198
219
  export function resultRunsOf(store, family) {
199
220
  return family.versions.flatMap(version => store.runsFor(version.refId)).filter(isResultRun).sort((a, b) => b.id - a.id);
200
221
  }
222
+ export function takeOverRunsOf(store, family) {
223
+ return family.versions.flatMap(version => store.runsFor(version.refId)).filter(isTakeOverRun).sort((a, b) => b.id - a.id);
224
+ }
201
225
  export function patchFiles(text) {
202
226
  return text.replace(/\r\n/g, "\n").split(/^(?=diff --git )/m).filter(part => part.startsWith("diff --git ")).map(part => part.replace(/\n$/, ""));
203
227
  }
@@ -337,6 +361,104 @@ export function resultDiffContextOf(store, evidenceRoot, taskId, run, file, from
337
361
  });
338
362
  return answer(lines, lineCount, null);
339
363
  }
364
+ export function taskResultOf(store, evidenceRoot, family, run) {
365
+ const ref = store.lookupRef(family.current.id);
366
+ const deliverable = ref?.deliverable === "report" || run?.role === "scout" ? "report" : "code";
367
+ if (run === null) {
368
+ return {
369
+ version: ENGINE_API_VERSION,
370
+ task: family.root.id,
371
+ deliverable,
372
+ run: null,
373
+ role: null,
374
+ outcome: null,
375
+ verdict: null,
376
+ summary: null,
377
+ report: null,
378
+ handoff: null,
379
+ screenshots: [],
380
+ };
381
+ }
382
+ const artifacts = store.artifactsFor(run.id);
383
+ const reportArtifact = [...artifacts].reverse().find(one => one.kind === "report");
384
+ let report = null;
385
+ if (reportArtifact !== undefined) {
386
+ let read;
387
+ try {
388
+ read = readVerifiedArtifact(evidenceRoot, reportArtifact);
389
+ }
390
+ catch {
391
+ read = { ok: false, problem: "the report file could not be read" };
392
+ }
393
+ if (!read.ok) {
394
+ report = { ok: false, problem: read.problem };
395
+ }
396
+ else {
397
+ const parsed = parseReport(read.content.toString("utf8"), { stored: true });
398
+ if (!parsed.ok) {
399
+ report = {
400
+ ok: false,
401
+ problem: reportArtifact.truncated
402
+ ? "the report was shortened at storage and cannot be read; the missing part was never captured"
403
+ : "the stored report is not a report this console can read",
404
+ };
405
+ }
406
+ else {
407
+ const shots = reportShotsOf(artifacts, evidenceRoot, run.id, parsed.report.images).map(shot => ({
408
+ file: shot.file,
409
+ caption: shot.caption,
410
+ url: shot.url,
411
+ artifactUrl: shot.artifactId === null ? null : `/r/${run.id}/evidence/${shot.artifactId}`,
412
+ problem: shot.problem,
413
+ }));
414
+ report = {
415
+ ok: true,
416
+ title: parsed.report.title,
417
+ summary: parsed.report.summary,
418
+ document: parsed.report.report,
419
+ truncated: reportArtifact.truncated,
420
+ items: parsed.report.items,
421
+ followUps: parsed.report.followUps,
422
+ shots,
423
+ };
424
+ }
425
+ }
426
+ }
427
+ const handoffView = structuredHandoffView(artifacts, evidenceRoot);
428
+ const handoff = handoffView === null ? null : {
429
+ conclusion: handoffView.conclusion,
430
+ changes: handoffView.changes,
431
+ verification: handoffView.verification,
432
+ followUps: handoffView.followUps,
433
+ decisions: handoffView.report.decisions,
434
+ assumptions: handoffView.report.assumptions,
435
+ notDone: handoffView.report.notDone,
436
+ risks: handoffView.report.risks,
437
+ };
438
+ const proof = proofBundleView(store, run, artifacts, evidenceRoot);
439
+ const screenshots = (proof?.screenshots ?? [])
440
+ .filter(one => one.problem === null)
441
+ .map(one => ({
442
+ caption: one.caption,
443
+ path: one.path,
444
+ url: `/r/${run.id}/evidence/${one.artifactId}`,
445
+ }));
446
+ const verdictRow = store.proofVerdictFor(run.id);
447
+ const summary = (report !== null && report.ok ? report.summary : null) ?? handoff?.conclusion ?? null;
448
+ return {
449
+ version: ENGINE_API_VERSION,
450
+ task: family.root.id,
451
+ deliverable,
452
+ run: run.id,
453
+ role: run.role,
454
+ outcome: run.outcome,
455
+ verdict: verdictRow?.verdict ?? null,
456
+ summary,
457
+ report,
458
+ handoff,
459
+ screenshots,
460
+ };
461
+ }
340
462
  export function setupOf(id, home = null) {
341
463
  const setup = agentSetupOf(id);
342
464
  if (setup === null)
@@ -445,3 +567,9 @@ function planQueuedOf(store, state, ref, scope, live, now) {
445
567
  return false;
446
568
  return store.activeHolds(ref.id, now).length === 0;
447
569
  }
570
+ function agentChoicesOf(store, taskId, ref, now) {
571
+ const routed = routeOfTask(store, taskId, ref, now);
572
+ const choices = agentChoicesFor(store, ref?.repo ?? null, routed?.kind === "route" ? routed.route : null);
573
+ const pairs = (phase) => choices[phase].filter(one => one.selectable).map(one => ({ provider: one.provider, model: one.model }));
574
+ return { plan: pairs("plan"), build: pairs("build") };
575
+ }
package/dist/exec.js CHANGED
@@ -1234,7 +1234,7 @@ export function runAcpSession(file, args, options = {}) {
1234
1234
  registerOwned(options.owner, child);
1235
1235
  if (options.processGroup === true && container === null)
1236
1236
  observeProcessTree(child, options);
1237
- const conversation = createAcpConversation({ cwd: options.cwd ?? process.cwd(), prompt: acp.prompt, model: acp.model, expect: acp.expect });
1237
+ const conversation = createAcpConversation({ cwd: options.cwd ?? process.cwd(), prompt: acp.prompt, model: acp.model, expect: acp.expect, authMethod: acp.authMethod ?? null });
1238
1238
  const agentNames = [...new Set([file, ...args.slice(0, 2)].filter(one => one.startsWith("/")).map(one => one.split("/").pop()).filter(one => one !== ""))];
1239
1239
  let stderr = "";
1240
1240
  let timedOut = false;
@@ -1267,14 +1267,15 @@ export function runAcpSession(file, args, options = {}) {
1267
1267
  let handshakePhase = null;
1268
1268
  const armHandshake = () => {
1269
1269
  const phase = conversation.phase();
1270
- if (phase === handshakePhase || (phase !== "initialize" && phase !== "session" && phase !== "model"))
1270
+ if (phase === handshakePhase || (phase !== "initialize" && phase !== "authenticate" && phase !== "session" && phase !== "model"))
1271
1271
  return;
1272
1272
  handshakePhase = phase;
1273
1273
  const limit = acp.handshakeMs ?? ACP_HANDSHAKE_MS;
1274
1274
  later(limit, () => {
1275
1275
  if (settled || conversation.phase() !== phase)
1276
1276
  return;
1277
- conversation.refuse(`the agent took more than ${limit / 1000} s to answer ${phase === "initialize" ? "initialize" : phase === "session" ? "session/new" : "the model choice"}`);
1277
+ const stepName = phase === "initialize" ? "initialize" : phase === "authenticate" ? "authenticate" : phase === "session" ? "session/new" : "the model choice";
1278
+ conversation.refuse(`the agent took more than ${limit / 1000} s to answer ${stepName}`);
1278
1279
  forceKill();
1279
1280
  });
1280
1281
  };
@@ -2,10 +2,9 @@ import { join } from "node:path";
2
2
  import { flexibleAvailable } from "./flexible-available.js";
3
3
  import { flexibleDelegationAtUse, FLEXIBLE_LEVEL_WORDS, FLEXIBLE_LEVELS, FLEXIBLE_UNAVAILABLE, isFlexibleLevel } from "./flexible.js";
4
4
  import { threadLevelAllowed, FLEXIBLE_PROVEN } from "./flexible-levels.js";
5
- import { defaultCustodyIO, flexibleLaunch, freshProviderFolder, onLaunchStopped, unsettledLaunch, watchLaunch } from "./flexible-launch.js";
5
+ import { flexibleLaunch, freshProviderFolder, onLaunchStopped, unsettledLaunch, watchLaunch } from "./flexible-launch.js";
6
6
  import { relayUrlInside } from "./flexible-relay.js";
7
- import { startIdentityOf } from "./flexible-custody.js";
8
- import { flexibleFenceDigest, flexibleThread, flexibleThreadFence, flexibleThreadSpawn, stopFlexibleThreadAgent, withFlexibleThreadLock } from "./flexible-thread.js";
7
+ import { flexibleThread, flexibleThreadFence, flexibleThreadSpawn, stopFlexibleThreadAgent, withFlexibleThreadLock } from "./flexible-thread.js";
9
8
  import { beginFlexibleTurn, finishFlexibleTurn, flexibleTurn, interruptFlexibleTurnsOf, withdrawFlexibleTurn, withdrawFlexibleTurnsAbove } from "./flexible-turns.js";
10
9
  import { CLAUDE_BUILD_ISOLATION_ARGV, HEADLESS_DISALLOWED_TOOLS } from "./provider.js";
11
10
  const WORDS = Object.freeze({
@@ -78,7 +77,7 @@ export async function startFlexibleTurn(store, input) {
78
77
  await unused();
79
78
  throw error;
80
79
  }
81
- if (!started.ok || started.launched === "reused")
80
+ if (!started.ok)
82
81
  await unused();
83
82
  return started;
84
83
  }
@@ -91,7 +90,6 @@ async function startLocked(store, input) {
91
90
  const clocked = input.clock === undefined ? {} : { clock: input.clock };
92
91
  if (turn.holder !== input.holder)
93
92
  return { ok: false, reason: "held-elsewhere", message: "Another Toolroll process holds this turn, so this one didn't touch it." };
94
- const io = input.seams?.io ?? defaultCustodyIO();
95
93
  const withdraw = (refusal) => { withdrawFlexibleTurn(store, { turn: turn.id, holder: input.holder, detail: refusal.message, ...clocked }); return refusal; };
96
94
  const allowed = threadLevelAllowed(store.orgPolicy(), turn.provider, turn.level, input.proven ?? FLEXIBLE_PROVEN);
97
95
  if (!allowed.ok)
@@ -102,16 +100,8 @@ async function startLocked(store, input) {
102
100
  return withdraw(fenced);
103
101
  const running = unsettledLaunch(store, turn.thread);
104
102
  if (running !== null) {
105
- const same = running.state === "live" && running.holder === input.holder && running.provider === turn.provider && running.level === turn.level
106
- && running.leaderPid !== null && running.leaderStart !== null && startIdentityOf(running.leaderPid, io) === running.leaderStart
107
- && running.fenceDigest === flexibleFenceDigest(fenced.launch);
108
- if (same) {
109
- const begun = beginFlexibleTurn(store, { turn: turn.id, holder: input.holder, ...clocked });
110
- if (!begun.ok)
111
- return begun;
112
- return { ok: true, launched: "reused", launchId: running.id };
113
- }
114
- const stopped = await stopFlexibleThreadAgent(store, { id: turn.thread, reason: "its agent was replaced", ...clocked, ...(input.seams?.io === undefined ? {} : { io: input.seams.io }), keepTurn: turn.id });
103
+ const stopped = await stopFlexibleThreadAgent(store, { id: turn.thread, reason: "its agent was replaced", ...clocked, ...(input.seams?.io === undefined ? {} : { io: input.seams.io }), keepTurn: turn.id,
104
+ expect: { launch: running.id, holder: running.holder } });
115
105
  if ("reason" in stopped)
116
106
  return withdraw(stopped);
117
107
  if (!stopped.ok)
@@ -155,8 +145,10 @@ async function startLocked(store, input) {
155
145
  if (issued !== null)
156
146
  onLaunchStopped(spawned.launchId, issued.revoke);
157
147
  const stopWatching = watchLaunch(store, spawned.launchId, fenced.paths.folder, input.seams?.io);
148
+ const launchId = spawned.launchId;
158
149
  spawned.child.once("exit", () => {
159
- void stopFlexibleThreadAgent(store, { id: turn.thread, reason: "its agent exited", ...(input.seams?.io === undefined ? {} : { io: input.seams.io }) }).catch(() => { });
150
+ void stopFlexibleThreadAgent(store, { id: turn.thread, reason: "its agent exited", expect: { launch: launchId, holder: input.holder }, ...(input.seams?.io === undefined ? {} : { io: input.seams.io }) })
151
+ .then(settled => { input.seams?.exitSettled?.(launchId, settled); }, () => { input.seams?.exitSettled?.(launchId, null); });
160
152
  });
161
153
  return { ok: true, launched: "started", launchId: spawned.launchId, pid: spawned.pid, child: spawned.child, stopWatching };
162
154
  }
@@ -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;
@@ -1244,3 +1239,52 @@ export async function removeFlexibleThreadCopy(store, input) {
1244
1239
  const removed = await removeFlexibleThread(store, { id: input.thread, by: input.by, now: input.now, ...(input.prove === undefined ? {} : { prove: input.prove }) });
1245
1240
  return removed.ok ? { ok: true } : { ok: false, reason: removed.reason, message: removed.message };
1246
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
+ }