toolroll 0.9.114 → 0.9.116

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 (96) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/dist/agent-state-words.js +1 -1
  3. package/dist/assignment-ui.js +1 -1
  4. package/dist/browser/terminal.css +1 -1
  5. package/dist/browser/terminal.js +1 -1
  6. package/dist/browser/workspace.css +2 -2
  7. package/dist/browser/workspace.js +29 -28
  8. package/dist/chat-controls.js +1 -1
  9. package/dist/chat-quiet.js +2 -2
  10. package/dist/chat-voice.js +3 -3
  11. package/dist/check-levels.js +1 -1
  12. package/dist/claim.js +7 -2
  13. package/dist/cli.js +1 -0
  14. package/dist/code-map-cli.js +2 -1
  15. package/dist/coding-shipping-ui.js +2 -1
  16. package/dist/console-instance.js +21 -1
  17. package/dist/contracts/console-api.js +6 -2
  18. package/dist/contracts/engine-api.js +32 -4
  19. package/dist/demo-chat.js +1 -1
  20. package/dist/design/kit.css +3 -0
  21. package/dist/design/kit.js +1 -1
  22. package/dist/dispatch.js +19 -2
  23. package/dist/easy-start.js +23 -11
  24. package/dist/engine-reads.js +98 -7
  25. package/dist/export.js +16 -4
  26. package/dist/flexible-authority-end.js +94 -0
  27. package/dist/flexible-everyday-schema.js +76 -0
  28. package/dist/flexible-interactive-schema.js +133 -0
  29. package/dist/flexible-interactive.js +94 -0
  30. package/dist/flexible-laptop.js +38 -0
  31. package/dist/flexible-relay.js +9 -3
  32. package/dist/flexible-session.js +430 -10
  33. package/dist/flexible-ship.js +77 -12
  34. package/dist/flexible-sign-in.js +16 -1
  35. package/dist/flexible-start.js +17 -2
  36. package/dist/flexible-thread.js +1 -1
  37. package/dist/flexible-turns.js +9 -0
  38. package/dist/flexible-ui.js +3 -2
  39. package/dist/flexible.js +13 -0
  40. package/dist/flow-card-task.js +1 -1
  41. package/dist/home-groups.js +1 -1
  42. package/dist/lead-status.js +5 -3
  43. package/dist/lead-tools.js +1 -0
  44. package/dist/local-owner-acts.js +44 -1
  45. package/dist/local-owner.js +10 -0
  46. package/dist/needs-you.js +18 -6
  47. package/dist/operate-remote-arguments.js +1 -1
  48. package/dist/operate.js +250 -32
  49. package/dist/plan-problems-schema.js +4 -0
  50. package/dist/planner.js +17 -6
  51. package/dist/release-cli.js +2 -2
  52. package/dist/result-actions.js +1 -2
  53. package/dist/retention-ui.js +1 -1
  54. package/dist/scope.js +18 -7
  55. package/dist/server/chat.js +3 -3
  56. package/dist/server/console.css +15 -10
  57. package/dist/server/engine-api.js +161 -15
  58. package/dist/server/flows.js +4 -3
  59. package/dist/server/home.js +1 -1
  60. package/dist/server/kit.js +2 -2
  61. package/dist/server/render-chat.js +1 -1
  62. package/dist/server/render-pages.js +1 -1
  63. package/dist/server/render-tasks.js +21 -12
  64. package/dist/server/route-table.js +16 -0
  65. package/dist/server/settings-sections.js +6 -2
  66. package/dist/server/settings.js +22 -8
  67. package/dist/server/task-views.js +10 -4
  68. package/dist/server/tasks.js +51 -4
  69. package/dist/settings-kit.js +3 -3
  70. package/dist/skills-ui.js +3 -2
  71. package/dist/spend-report.js +2 -2
  72. package/dist/spend.js +3 -3
  73. package/dist/store.js +202 -7
  74. package/dist/subagent-admin.js +23 -10
  75. package/dist/subagent-backup-schema.js +36 -0
  76. package/dist/subagent-backup.js +92 -0
  77. package/dist/subagent-week.js +2 -2
  78. package/dist/subagent-work.js +70 -47
  79. package/dist/subagents-ui.js +6 -2
  80. package/dist/subagents.js +5 -2
  81. package/dist/subscription-chat.js +4 -0
  82. package/dist/surface.js +8 -1
  83. package/dist/task-status.js +13 -13
  84. package/dist/telegram-status.js +3 -3
  85. package/dist/terminal-safety.js +114 -0
  86. package/dist/toolroll-update.js +2 -1
  87. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  88. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  89. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  90. package/dist/tui/linux-x64/toolroll-tui +0 -0
  91. package/dist/tui-launch.js +20 -1
  92. package/dist/tui.js +1 -1
  93. package/dist/work-index.js +23 -10
  94. package/dist/workspace-ui.js +5 -5
  95. package/dist/youiyoux-intake.js +1 -1
  96. package/package.json +2 -2
@@ -1,14 +1,16 @@
1
1
  import { createHash, randomBytes, randomUUID } from "node:crypto";
2
2
  import { StringDecoder } from "node:string_decoder";
3
3
  import { flexibleAvailable } from "./flexible-available.js";
4
+ import { interruptTurnAndStop, openFlexibleStops, requireFlexibleStop, settleExitedStops } from "./flexible-authority-end.js";
4
5
  import { FLEXIBLE_LEVEL_WORDS, FLEXIBLE_UNAVAILABLE, isFlexibleLevel } from "./flexible.js";
5
6
  import { lowerFlexibleThreadLevel, recoverFlexibleLaunchesOf, startFlexibleTurn } from "./flexible-agents.js";
6
7
  import { decideFlexibleAnswer, expireFlexibleAnswers, flexibleRequestsOf, noteFlexibleToolActivity, openFlexibleAnswerCatalog, recordFlexibleRequest, recoverFlexibleAnswersOf, revokeFlexibleAnswers, sendFlexibleAnswer, streamAnswerSender, } from "./flexible-answers.js";
7
8
  import { startIdentityOf } from "./flexible-custody.js";
8
- import { defaultCustodyIO, flexibleTurnLaunched } from "./flexible-launch.js";
9
+ import { defaultCustodyIO, flexibleTurnLaunched, unsettledLaunch } from "./flexible-launch.js";
10
+ import { cancelFlexibleShip, flexibleShipsOf, flexibleShipTerms, sendBackFlexible, shipFlexible } from "./flexible-ship.js";
9
11
  import { startFlexibleRelay } from "./flexible-relay.js";
10
12
  import { flexibleSignInBilling } from "./flexible-sign-in.js";
11
- import { flexibleThread, prepareFlexibleThread, removeFlexibleThread, stopFlexibleThreadAgent } from "./flexible-thread.js";
13
+ import { flexibleThread, prepareFlexibleThread, removeFlexibleThread, stopFlexibleThreadAgent, withFlexibleThreadLock } from "./flexible-thread.js";
12
14
  import { admitFlexibleTurn, finishFlexibleTurn, flexibleTurn, interruptFlexibleThreadTurns, interruptFlexibleTurnsOf, withdrawFlexibleTurn } from "./flexible-turns.js";
13
15
  import { userFrame } from "./live-input.js";
14
16
  import { cleanLiveText, createLiveRecorder, HIDDEN_LINE, liveSecretHit } from "./live-records.js";
@@ -129,8 +131,15 @@ export async function settleFlexibleStops(store, sessions, input = {}) {
129
131
  pending++;
130
132
  }
131
133
  }
134
+ try {
135
+ store.transact(() => { settleExitedStops(store, (input.clock ?? systemClock)().toISOString()); });
136
+ }
137
+ catch { }
132
138
  return { ok: true, stopped, pending };
133
139
  }
140
+ const required = await settleStopRequirements(store, sessions, clocked);
141
+ stopped += required.stopped;
142
+ pending += required.pending;
134
143
  const unresolved = store.handle.prepare("SELECT thread, id FROM flexible_thread_launch WHERE holder = ? AND state = 'unresolved' ORDER BY started_at, id").all(sessions.holder)
135
144
  .map(row => ({ thread: String(row["thread"]), launch: String(row["id"]) }));
136
145
  for (const one of unresolved) {
@@ -160,7 +169,12 @@ export async function stopFlexibleThreadsEverywhere(store, input) {
160
169
  const lives = new Map();
161
170
  const lifeOf = (holder) => { if (!lives.has(holder))
162
171
  lives.set(holder, holderLife(holder, io)); return lives.get(holder); };
163
- const launches = store.handle.prepare("SELECT id, thread, holder FROM flexible_thread_launch WHERE state <> 'exited' ORDER BY started_at, id").all()
172
+ const launches = (input.thread !== undefined
173
+ ? store.handle.prepare("SELECT id, thread, holder FROM flexible_thread_launch WHERE state <> 'exited' AND thread = ? ORDER BY started_at, id").all(input.thread)
174
+ : input.owner === undefined
175
+ ? store.handle.prepare("SELECT id, thread, holder FROM flexible_thread_launch WHERE state <> 'exited' ORDER BY started_at, id").all()
176
+ : store.handle.prepare(`SELECT l.id AS id, l.thread AS thread, l.holder AS holder FROM flexible_thread_launch l JOIN flexible_thread t ON t.id = l.thread
177
+ WHERE l.state <> 'exited' AND t.created_by = ? ORDER BY l.started_at, l.id`).all(input.owner))
164
178
  .map(row => ({ launch: String(row["id"]), thread: String(row["thread"]), holder: String(row["holder"]) }));
165
179
  for (const one of launches) {
166
180
  const gone = lifeOf(one.holder) === "gone";
@@ -187,6 +201,12 @@ export async function stopFlexibleThreadsEverywhere(store, input) {
187
201
  else
188
202
  report.survivors.push({ thread: one.thread, pids: [...done.survivors], why: done.why });
189
203
  }
204
+ try {
205
+ store.transact(() => { settleExitedStops(store, (input.clock ?? systemClock)().toISOString()); });
206
+ }
207
+ catch { }
208
+ if (input.owner !== undefined || input.thread !== undefined)
209
+ return report;
190
210
  const holders = new Set(store.handle.prepare("SELECT DISTINCT holder FROM thread_turn WHERE status IN ('admitted', 'running')").all().map(row => String(row["holder"])));
191
211
  const goneHolders = [...new Set([...holders, ...launches.map(one => one.holder)])].filter(holder => lifeOf(holder) === "gone"
192
212
  && store.handle.prepare("SELECT 1 AS open FROM flexible_thread_launch WHERE holder = ? AND state <> 'exited'").get(holder) === undefined);
@@ -206,6 +226,46 @@ export async function stopFlexibleThreadsEverywhere(store, input) {
206
226
  }
207
227
  return report;
208
228
  }
229
+ export const FLEXIBLE_AUTHORITY_MOVED_WORDS = "Your Claude sign-in for threads no longer counts (it was removed, or your Toolroll account changed), so Toolroll stopped this turn.";
230
+ async function settleStopRequirements(store, sessions, clocked) {
231
+ const at = () => (clocked.clock ?? systemClock)().toISOString();
232
+ let stopped = 0, pending = 0;
233
+ try {
234
+ store.transact(() => {
235
+ for (const row of store.handle.prepare(`SELECT t.id AS turn, t.owner AS owner, d.sign_in_epoch AS epoch, d.account_generation AS generation FROM thread_turn t
236
+ JOIN flexible_turn_dispatch d ON d.turn = t.id WHERE t.status = 'running' AND t.holder = ?`).all(sessions.holder)) {
237
+ const owner = String(row["owner"]);
238
+ const epochNow = Number(store.handle.prepare("SELECT epoch FROM flexible_sign_in_epoch WHERE person = ?").get(owner)?.["epoch"] ?? 0);
239
+ const account = store.accountOf(owner);
240
+ const moved = epochNow !== Number(row["epoch"]) || account === null || account.revokedAt !== null || account.generation !== Number(row["generation"]);
241
+ if (moved)
242
+ interruptTurnAndStop(store, { turn: String(row["turn"]), words: FLEXIBLE_AUTHORITY_MOVED_WORDS, reason: "its owner's authority moved since its turn began", at: at() });
243
+ }
244
+ settleExitedStops(store, at());
245
+ });
246
+ }
247
+ catch { }
248
+ for (const one of openFlexibleStops(store)) {
249
+ const launch = store.handle.prepare("SELECT holder, state FROM flexible_thread_launch WHERE id = ?").get(one.launch);
250
+ if (launch === undefined || launch["state"] === "exited" || String(launch["holder"]) !== sessions.holder)
251
+ continue;
252
+ try {
253
+ const done = await stopFlexibleThreadSession(store, sessions, { thread: one.thread, reason: one.reason, ...clocked });
254
+ if (done.ok && "stopped" in done && done.stopped)
255
+ stopped++;
256
+ else
257
+ pending++;
258
+ }
259
+ catch {
260
+ pending++;
261
+ }
262
+ }
263
+ try {
264
+ store.transact(() => { settleExitedStops(store, at()); });
265
+ }
266
+ catch { }
267
+ return { stopped, pending };
268
+ }
209
269
  export function tickFlexibleSessions(store, sessions, input = {}) {
210
270
  const expired = expireFlexibleAnswers(store, sessions.catalog, input.clock === undefined ? {} : { clock: input.clock });
211
271
  if (expired.ok && expired.uncertain > 0)
@@ -422,7 +482,11 @@ export function attachFlexibleAgent(store, sessions, input) {
422
482
  connection: { id: input.launch, frame: (ref, answer) => frameFor(session, ref, answer), send },
423
483
  recorder: createLiveRecorder({ base: thread.folder === "" ? null : `${thread.folder}/repo`, commands: false, clock }) };
424
484
  session.agent = link;
425
- const keep = (records) => {
485
+ let outputTurn = input.turn;
486
+ const keep = (given) => {
487
+ if (link.turn !== null)
488
+ outputTurn = link.turn;
489
+ const records = withoutRefusedLines(store, outputTurn, given);
426
490
  if (records.length === 0)
427
491
  return;
428
492
  session.records.push(...records);
@@ -468,7 +532,8 @@ export function attachFlexibleAgent(store, sessions, input) {
468
532
  }
469
533
  keep(link.recorder.observe(raw));
470
534
  if (primaryResultEvent(raw) && link.turn !== null) {
471
- void endFlexibleThreadTurn(store, sessions, { thread: input.thread, turn: link.turn, outcome: "finished", ...clocked });
535
+ const failed = raw["is_error"] === true;
536
+ void endFlexibleThreadTurn(store, sessions, { thread: input.thread, turn: link.turn, outcome: failed ? "unknown" : "finished", ...(failed ? { detail: "The agent stopped with an error." } : {}), ...clocked });
472
537
  }
473
538
  };
474
539
  const decoder = new StringDecoder("utf8");
@@ -512,8 +577,19 @@ export function endFlexibleThreadTurn(store, sessions, input) {
512
577
  const finished = finishFlexibleTurn(store, { turn: input.turn, holder: sessions.holder, outcome: input.outcome, usage: null, ...(input.detail === undefined ? {} : { detail: input.detail }), ...clocked });
513
578
  const revoked = revokeFlexibleAnswers(store, sessions.catalog, { thread: input.thread, turn: input.turn, reason: "the turn ended", ...clocked });
514
579
  const agent = sessions.threads.get(input.thread)?.agent;
515
- if (agent != null && agent.turn === input.turn)
516
- agent.turn = null;
580
+ if (agent != null && agent.turn === input.turn) {
581
+ const now = flexibleTurn(store, input.turn);
582
+ if (now !== null && now.status === "interrupted") {
583
+ try {
584
+ store.transact(() => { requireFlexibleStop(store, { launch: agent.launch, thread: input.thread, reason: "its turn was interrupted", at: (input.clock ?? systemClock)().toISOString() }); });
585
+ }
586
+ catch {
587
+ return revoked.ok ? { ok: false, reason: "stop-unrecorded", message: "Toolroll couldn't record that this agent must stop yet." } : revoked;
588
+ }
589
+ }
590
+ if (now === null || now.status !== "running")
591
+ agent.turn = null;
592
+ }
517
593
  bump(sessions, input.thread);
518
594
  if (!revoked.ok)
519
595
  return revoked;
@@ -639,6 +715,9 @@ export async function startFlexibleThread(store, sessions, input) {
639
715
  if (!admitted.ok)
640
716
  return admitted;
641
717
  turn = admitted.turn;
718
+ const title = cardText(input.message.split("\n")[0], 80);
719
+ if (title !== "")
720
+ store.handle.prepare("INSERT INTO flexible_thread_meta (thread, title) VALUES (?, ?) ON CONFLICT (thread) DO NOTHING").run(id, title);
642
721
  return { ok: true };
643
722
  },
644
723
  release: (_id, why) => {
@@ -681,6 +760,229 @@ async function discardRefusedStart(store, sessions, input) {
681
760
  }
682
761
  catch { }
683
762
  }
763
+ export const FLEXIBLE_THREAD_ENDED = "This thread has ended. Start a new thread to go on.";
764
+ export function flexibleThreadEnded(store, thread) {
765
+ return store.handle.prepare("SELECT 1 AS ended FROM flexible_thread_meta WHERE thread = ? AND ended_at IS NOT NULL").get(thread) !== undefined;
766
+ }
767
+ export async function continueFlexibleThread(store, sessions, input) {
768
+ if (!flexibleAvailable(store))
769
+ return refuse("not-available");
770
+ if (typeof input.thread !== "string" || !ID.test(input.thread) || typeof input.message !== "string" || input.message.trim() === "" || input.message.length > 100_000
771
+ || typeof input.key !== "string" || !ID.test(input.key) || typeof input.held !== "function")
772
+ return refuse("invalid-request");
773
+ if (input.launcher === null)
774
+ return refuse("no-network");
775
+ const clock = input.clock ?? systemClock;
776
+ const locked = await withFlexibleThreadLock(input.thread, async () => {
777
+ const admitted = store.transact(() => {
778
+ if (!input.held())
779
+ return { ok: false, reason: "session", message: "Your session here changed. Sign in again, then reply. Nothing was sent." };
780
+ if (ownThread(store, input.thread, input.by) === null)
781
+ return refuse("thread-unknown");
782
+ if (flexibleThreadEnded(store, input.thread))
783
+ return { ok: false, reason: "thread-ended", message: FLEXIBLE_THREAD_ENDED };
784
+ const last = store.handle.prepare("SELECT id FROM thread_turn WHERE thread = ? AND status <> 'withdrawn' ORDER BY seq DESC LIMIT 1").get(input.thread)?.["id"];
785
+ const before = typeof last === "string" ? flexibleTurn(store, last) : null;
786
+ if (before === null)
787
+ return { ok: false, reason: "no-turn", message: "This thread has no turn to continue from. Start a new thread." };
788
+ const billing = flexibleSignInBilling(store, input.by);
789
+ if (!billing.ok)
790
+ return { ok: false, reason: billing.reason, message: billing.reason === "no-sign-in"
791
+ ? "Threads use your own Claude sign-in, and you haven't saved one (or it was removed). Add one, then reply. Nothing was sent."
792
+ : "Claude didn't accept your sign-in for threads. Save a new one, then reply. Nothing was sent." };
793
+ const level = levelOf(store, input.thread) ?? before.level;
794
+ return admitFlexibleTurn(store, { thread: input.thread, starter: input.by, digest: before.termsDigest, level, freshProof: input.freshProof, provider: before.provider, model: before.model,
795
+ billing: billing.billing, requestKey: `reply:${input.key}`, holder: sessions.holder, clock });
796
+ });
797
+ if (!admitted.ok)
798
+ return admitted;
799
+ if (admitted.replayed && flexibleTurn(store, admitted.turn)?.status !== "admitted")
800
+ return { ok: false, reason: "already-sent", message: "That message already started a turn. Nothing new was started." };
801
+ const begun = await beginFlexibleThreadTurn(store, sessions, { turn: admitted.turn, message: input.message, launcher: input.launcher, clock,
802
+ ...(input.seams === undefined ? {} : { seams: input.seams }), ...(input.proven === undefined ? {} : { proven: input.proven }) });
803
+ if (!begun.ok)
804
+ return begun;
805
+ return { ok: true, turn: admitted.turn, seq: admitted.seq, fresh: begun.launched === "started", replayed: admitted.replayed };
806
+ });
807
+ return locked;
808
+ }
809
+ export const FLEXIBLE_STOPPED_WORDS = "You stopped this turn. The thread is still open: reply to go on.";
810
+ export const FLEXIBLE_ENDED_WORDS = "You ended this thread.";
811
+ export async function closeFlexibleThread(store, sessions, input) {
812
+ if (typeof input.thread !== "string" || !ID.test(input.thread) || (input.act !== "stop" && input.act !== "end"))
813
+ return refuse("invalid-request");
814
+ const clock = input.clock ?? systemClock;
815
+ const locked = await withFlexibleThreadLock(input.thread, async () => {
816
+ const at = clock().toISOString();
817
+ const recorded = store.transact(() => {
818
+ const account = store.accountOf(input.by.name);
819
+ if (account === null || account.revokedAt !== null || account.generation !== input.by.generation)
820
+ return { ok: false, reason: "stale-generation", message: "Your account changed since this started. Sign in again and retry. Nothing changed." };
821
+ if (input.prove !== undefined && !input.prove())
822
+ return { ok: false, reason: "proof-changed", message: "This install changed since you asked (another account, or a password), so this needs your password now. Nothing changed." };
823
+ if (ownThread(store, input.thread, input.by) === null)
824
+ return refuse("thread-unknown");
825
+ const ended = flexibleThreadEnded(store, input.thread);
826
+ if (input.act === "end") {
827
+ if (ended)
828
+ return { ok: true, already: true };
829
+ const title = recordedTitle(store, input.thread);
830
+ store.handle.prepare(`INSERT INTO flexible_thread_meta (thread, title, ended_at, ended_by, end_words) VALUES (?, ?, ?, ?, ?)
831
+ ON CONFLICT (thread) DO UPDATE SET ended_at = excluded.ended_at, ended_by = excluded.ended_by, end_words = excluded.end_words`)
832
+ .run(input.thread, title, at, input.by.name, FLEXIBLE_ENDED_WORDS);
833
+ store.recordAction({ at, actor: input.by.name, repo: flexibleThread(store, input.thread)?.repo ?? null, taskId: null, runId: null, source: "work", action: "flexible thread ended", outcome: "ended",
834
+ detail: `thread ${input.thread}` });
835
+ }
836
+ const words = input.act === "end" ? FLEXIBLE_ENDED_WORDS : FLEXIBLE_STOPPED_WORDS;
837
+ for (const row of store.handle.prepare("SELECT id FROM thread_turn WHERE thread = ? AND status = 'running'").all(input.thread)) {
838
+ interruptTurnAndStop(store, { turn: String(row["id"]), words, reason: input.act === "end" ? "its owner ended the thread" : "its owner stopped it", at });
839
+ }
840
+ for (const row of store.handle.prepare("SELECT id FROM thread_turn WHERE thread = ? AND status = 'admitted'").all(input.thread)) {
841
+ withdrawFlexibleTurn(store, { turn: String(row["id"]), holder: String(store.handle.prepare("SELECT holder FROM thread_turn WHERE id = ?").get(String(row["id"]))?.["holder"]), detail: words, clock: () => new Date(at) });
842
+ }
843
+ for (const row of store.handle.prepare("SELECT id FROM flexible_thread_launch WHERE thread = ? AND state <> 'exited'").all(input.thread)) {
844
+ requireFlexibleStop(store, { launch: String(row["id"]), thread: input.thread, reason: input.act === "end" ? "its owner ended the thread" : "its owner stopped it", at });
845
+ }
846
+ return { ok: true, already: ended && input.act === "end" };
847
+ });
848
+ if (!recorded.ok)
849
+ return recorded;
850
+ if (sessions !== null && unsettledHere(store, sessions, input.thread)) {
851
+ try {
852
+ await stopFlexibleThreadSession(store, sessions, { thread: input.thread, reason: input.act === "end" ? "its owner ended the thread" : "its owner stopped it", clock });
853
+ }
854
+ catch { }
855
+ }
856
+ try {
857
+ store.transact(() => { settleExitedStops(store, clock().toISOString()); });
858
+ }
859
+ catch { }
860
+ return { ok: true, already: recorded.already, stopPending: flexibleStopPending(store, input.thread) };
861
+ });
862
+ return locked;
863
+ }
864
+ function unsettledHere(store, sessions, thread) {
865
+ return store.handle.prepare("SELECT 1 AS held FROM flexible_thread_launch WHERE thread = ? AND state <> 'exited' AND holder = ?").get(thread, sessions.holder) !== undefined
866
+ || sessions.threads.get(thread)?.agent != null;
867
+ }
868
+ export const FLEXIBLE_ENDED_KEEP_MS = 7 * 24 * 60 * 60_000;
869
+ export async function tidyEndedFlexibleThreads(store, input) {
870
+ const before = new Date(input.now.getTime() - FLEXIBLE_ENDED_KEEP_MS).toISOString();
871
+ const due = store.handle.prepare(`SELECT m.thread AS thread, t.created_by AS owner FROM flexible_thread_meta m JOIN flexible_thread t ON t.id = m.thread
872
+ WHERE m.ended_at IS NOT NULL AND m.ended_at <= ? AND m.tidied_at IS NULL AND t.state IN ('ready', 'removing') ORDER BY m.ended_at LIMIT 20`).all(before)
873
+ .map(row => ({ thread: String(row["thread"]), owner: String(row["owner"]) }));
874
+ let tidied = 0, left = 0;
875
+ for (const one of due) {
876
+ let removed;
877
+ try {
878
+ removed = await removeFlexibleThread(store, { id: one.thread, by: one.owner, now: input.now });
879
+ }
880
+ catch {
881
+ left++;
882
+ continue;
883
+ }
884
+ if (!removed.ok) {
885
+ left++;
886
+ continue;
887
+ }
888
+ store.transact(() => { store.handle.prepare("UPDATE flexible_thread_meta SET tidied_at = ? WHERE thread = ? AND tidied_at IS NULL").run(input.now.toISOString(), one.thread); });
889
+ tidied++;
890
+ }
891
+ return { tidied, left };
892
+ }
893
+ export const FLEXIBLE_SHIP_WORKING = "The agent is still working on your last message. Wait for it, or stop its turn, then ship. Nothing was shipped.";
894
+ export const FLEXIBLE_SHIP_STOPPING = "Toolroll is stopping the thread's agent first. Nothing was shipped yet: try again in a moment.";
895
+ export async function flexibleThreadShipTerms(store, input) {
896
+ if (typeof input.thread !== "string" || !ID.test(input.thread))
897
+ return refuse("invalid-request");
898
+ if (ownThread(store, input.thread, input.by) === null)
899
+ return refuse("thread-unknown");
900
+ const shown = await flexibleShipTerms(store, { thread: input.thread, by: input.by.name });
901
+ if (!shown.ok)
902
+ return shown;
903
+ return { ok: true, digest: shown.digest, summary: shown.summary };
904
+ }
905
+ export async function shipFlexibleThread(store, sessions, input) {
906
+ if (typeof input.thread !== "string" || !ID.test(input.thread))
907
+ return refuse("invalid-request");
908
+ const clock = input.clock ?? systemClock;
909
+ const locked = await withFlexibleThreadLock(input.thread, async () => {
910
+ if (ownThread(store, input.thread, input.by) === null)
911
+ return refuse("thread-unknown");
912
+ if (store.handle.prepare("SELECT 1 AS busy FROM thread_turn WHERE thread = ? AND status IN ('admitted', 'running') LIMIT 1").get(input.thread) !== undefined) {
913
+ return { ok: false, reason: "thread-running", message: FLEXIBLE_SHIP_WORKING };
914
+ }
915
+ if (unsettledLaunch(store, input.thread) !== null) {
916
+ try {
917
+ store.transact(() => {
918
+ for (const row of store.handle.prepare("SELECT id FROM flexible_thread_launch WHERE thread = ? AND state <> 'exited'").all(input.thread)) {
919
+ requireFlexibleStop(store, { launch: String(row["id"]), thread: input.thread, reason: "its work is being shipped", at: clock().toISOString() });
920
+ }
921
+ });
922
+ }
923
+ catch { }
924
+ if (sessions !== null && unsettledHere(store, sessions, input.thread)) {
925
+ try {
926
+ await stopFlexibleThreadSession(store, sessions, { thread: input.thread, reason: "its work is being shipped", clock });
927
+ }
928
+ catch { }
929
+ }
930
+ else {
931
+ try {
932
+ await stopFlexibleThreadsEverywhereFor(store, { thread: input.thread, reason: "its work is being shipped", clock });
933
+ }
934
+ catch { }
935
+ }
936
+ const until = Date.now() + Math.max(0, Math.min(input.waitMs ?? 0, 30_000));
937
+ while (unsettledLaunch(store, input.thread) !== null && Date.now() < until)
938
+ await new Promise(resolve => setTimeout(resolve, 250));
939
+ if (unsettledLaunch(store, input.thread) !== null)
940
+ return { ok: false, reason: "stopping", message: FLEXIBLE_SHIP_STOPPING };
941
+ }
942
+ return shipFlexible(store, { thread: input.thread, by: input.by.name, proof: input.proof, shownDigest: input.shownDigest, shownKey: input.shownKey, now: input.now });
943
+ });
944
+ return locked;
945
+ }
946
+ async function stopFlexibleThreadsEverywhereFor(store, input) {
947
+ const owner = flexibleThread(store, input.thread)?.createdBy;
948
+ if (owner === undefined)
949
+ return;
950
+ const io = defaultCustodyIO();
951
+ for (const row of store.handle.prepare("SELECT id, holder FROM flexible_thread_launch WHERE thread = ? AND state <> 'exited'").all(input.thread)) {
952
+ await stopFlexibleThreadAgent(store, { id: input.thread, reason: input.reason, io, clock: input.clock, expect: { launch: String(row["id"]), holder: String(row["holder"]) } });
953
+ }
954
+ }
955
+ export function latestFlexibleShip(store, thread) {
956
+ const read = flexibleShipsOf(store, thread);
957
+ const one = read.ok ? read.ships[0] : undefined;
958
+ return one === undefined ? null : { id: one.id, seq: one.seq, state: one.state, taskId: one.taskId, candidate: one.candidate, base: one.terms.github.base, detail: one.detail,
959
+ reason: one.reason };
960
+ }
961
+ export function cancelFlexibleThreadShip(store, input) {
962
+ if (ownThread(store, input.thread, input.by) === null)
963
+ return refuse("thread-unknown");
964
+ const ship = latestFlexibleShip(store, input.thread);
965
+ if (ship === null || ship.taskId === null)
966
+ return { ok: false, reason: "not-found", message: "This thread has no Ship to cancel." };
967
+ return cancelFlexibleShip(store, { taskId: ship.taskId, by: input.by, now: input.now });
968
+ }
969
+ export async function sendBackFlexibleThread(store, sessions, input) {
970
+ if (!flexibleAvailable(store))
971
+ return refuse("not-available");
972
+ if (ownThread(store, input.thread, input.by) === null)
973
+ return refuse("thread-unknown");
974
+ if (flexibleThreadEnded(store, input.thread))
975
+ return { ok: false, reason: "thread-ended", message: "This thread has ended, so it can't take your note. Cancel the Ship, or start a new thread." };
976
+ const ship = latestFlexibleShip(store, input.thread);
977
+ if (ship === null || ship.taskId === null)
978
+ return { ok: false, reason: "not-found", message: "This thread has no Ship to send back." };
979
+ const sent = sendBackFlexible(store, { taskId: ship.taskId, by: input.by, feedback: input.feedback, now: input.now });
980
+ if (!sent.ok)
981
+ return sent;
982
+ const replied = await continueFlexibleThread(store, sessions, { thread: input.thread, by: input.by, message: sent.feedback, key: input.key, freshProof: input.freshProof, held: input.held,
983
+ launcher: input.launcher, ...(input.clock === undefined ? {} : { clock: input.clock }) });
984
+ return replied.ok ? { ok: true, turn: replied.turn, seq: replied.seq, fresh: replied.fresh } : replied;
985
+ }
684
986
  export async function answerFlexibleRequest(store, sessions, input) {
685
987
  if (!flexibleAvailable(store))
686
988
  return refuse("not-available");
@@ -739,12 +1041,15 @@ function factsOf(store, sessions, thread, session) {
739
1041
  }));
740
1042
  const project = store.handle.prepare("SELECT name FROM project WHERE path = ?").get(thread.repo)?.["name"];
741
1043
  const facts = {
742
- title: session?.title ?? `Thread ${thread.id.slice(0, 8)}`,
1044
+ title: recordedTitle(store, thread.id) ?? session?.title ?? `Thread ${thread.id.slice(0, 8)}`,
743
1045
  project: typeof project === "string" ? project : null,
744
1046
  level: levelOf(store, thread.id),
745
1047
  agent: turn === null ? null : { provider: turn.provider, model: turn.model },
746
- turn: turn === null ? null : { seq: turn.seq, status: turn.status, costUsd: turn.costBasis === null ? null : turn.costMicrousd / 1_000_000, costBasis: turn.costBasis },
1048
+ turn: turn === null ? null : { seq: turn.seq, status: turn.status, costUsd: turn.costBasis === null ? null : turn.costMicrousd / 1_000_000, costBasis: turn.costBasis,
1049
+ ...endWordsOf(store, turn.id, turn.status), billing: turn.billing },
747
1050
  questions,
1051
+ ...threadEndOf(store, thread.id),
1052
+ ...shipFactsOf(store, thread.id),
748
1053
  };
749
1054
  return { version: sha16(JSON.stringify(facts)), ...facts };
750
1055
  }
@@ -779,7 +1084,7 @@ export function flexibleThreadsOf(store, sessions, input) {
779
1084
  const threads = rows.map(id => flexibleThread(store, id)).filter(one => one !== null).map(thread => {
780
1085
  const session = sessions.threads.get(thread.id);
781
1086
  const facts = factsOf(store, sessions, thread, session);
782
- return { ...facts, id: thread.id, repo: thread.repo, live: session?.agent != null, waiting: facts.questions.filter(one => one.answerable).length };
1087
+ return { ...facts, id: thread.id, repo: thread.repo, live: session?.agent != null, waiting: facts.questions.filter(one => one.answerable).length, stopPending: flexibleStopPending(store, thread.id) };
783
1088
  });
784
1089
  return { ok: true, threads };
785
1090
  }
@@ -824,3 +1129,118 @@ export function waitFlexibleThreadChange(sessions, input) {
824
1129
  input.abandoned?.(() => finish("abandoned"));
825
1130
  });
826
1131
  }
1132
+ export function flexibleThreadTitleOf(store, thread) {
1133
+ try {
1134
+ const title = store.handle.prepare("SELECT title FROM flexible_thread_meta WHERE thread = ?").get(thread)?.["title"];
1135
+ if (typeof title === "string" && title !== "")
1136
+ return title;
1137
+ }
1138
+ catch { }
1139
+ return `Thread ${thread.slice(0, 8)}`;
1140
+ }
1141
+ function endWordsOf(store, turn, status) {
1142
+ if (status !== "interrupted" && status !== "unknown" && status !== "withdrawn")
1143
+ return {};
1144
+ const detail = store.handle.prepare("SELECT end_detail FROM thread_turn WHERE id = ?").get(turn)?.["end_detail"];
1145
+ if (status === "unknown" && (detail === null || detail === undefined || detail === "The agent stopped with an error.")) {
1146
+ const connection = relayFailureWords(store, turn);
1147
+ if (connection !== null)
1148
+ return { endWords: connection };
1149
+ }
1150
+ if (typeof detail !== "string" || detail.trim() === "")
1151
+ return {};
1152
+ const words = cleanLiveText(detail).trim().slice(0, 500);
1153
+ return words === "" ? {} : { endWords: words };
1154
+ }
1155
+ const AGENT_API_ERROR = /\bAPI Error\b|\bInvalid API key\b|Please run \/login|Failed to authenticate|"type"\s*:\s*"error"|\b(?:authentication|permission)_error\b/;
1156
+ export const FLEXIBLE_REFUSED_LINE_WORDS = "(The agent's error message is left out: Toolroll's note on this turn says what happened.)";
1157
+ function withoutRefusedLines(store, turn, records) {
1158
+ if (turn === null || !records.some(one => one.k === "say" && one.t.some(line => AGENT_API_ERROR.test(line))))
1159
+ return records;
1160
+ const row = flexibleTurn(store, turn);
1161
+ if (row === null)
1162
+ return records;
1163
+ const words = row.status === "interrupted" ? endWordsOf(store, turn, row.status).endWords : relayFailureWords(store, turn) ?? undefined;
1164
+ if (row.status !== "interrupted" && words === undefined)
1165
+ return records;
1166
+ const explained = words === undefined ? FLEXIBLE_REFUSED_LINE_WORDS : `Toolroll: ${words}`;
1167
+ return records.map(one => one.k !== "say" || !one.t.some(line => AGENT_API_ERROR.test(line)) ? one : { ...one, t: [explained] });
1168
+ }
1169
+ function relayFailureWords(store, turn) {
1170
+ 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);
1171
+ if (call === undefined)
1172
+ return null;
1173
+ const next = "Review changes, then reply to retry.";
1174
+ if (call["status"] === "incomplete")
1175
+ return `Model connection lost. ${next}`;
1176
+ if (call["status"] !== "upstream-error")
1177
+ return null;
1178
+ if (call["http_status"] === null)
1179
+ return `Can't reach the model. ${next}`;
1180
+ if (call["http_status"] === 429)
1181
+ return "Too many model requests. Review changes, then reply later.";
1182
+ if (Number(call["http_status"]) >= 500)
1183
+ return `The model service failed. ${next}`;
1184
+ return null;
1185
+ }
1186
+ function recordedTitle(store, thread) {
1187
+ const title = store.handle.prepare("SELECT title FROM flexible_thread_meta WHERE thread = ?").get(thread)?.["title"];
1188
+ return typeof title === "string" && title !== "" ? title : null;
1189
+ }
1190
+ export function flexibleStopPending(store, thread) {
1191
+ return store.handle.prepare("SELECT 1 AS open FROM flexible_stop_request WHERE thread = ? AND settled_at IS NULL LIMIT 1").get(thread) !== undefined;
1192
+ }
1193
+ function threadEndOf(store, thread) {
1194
+ const row = store.handle.prepare("SELECT end_words FROM flexible_thread_meta WHERE thread = ? AND ended_at IS NOT NULL").get(thread);
1195
+ if (row === undefined)
1196
+ return {};
1197
+ return { ended: { words: cleanLiveText(String(row["end_words"])).slice(0, 500), stopPending: flexibleStopPending(store, thread) } };
1198
+ }
1199
+ function shipWords(ship) {
1200
+ const commit = ship.candidate.slice(0, 12), detail = ship.detail === null ? null : cleanLiveText(ship.detail).slice(0, 300);
1201
+ switch (ship.state) {
1202
+ case "approved":
1203
+ case "imported": return "Shipping: its changes are being checked in quarantine.";
1204
+ case "armed": return `Shipping: checks run on commit ${commit}; Toolroll merges it once they pass.`;
1205
+ case "completed":
1206
+ case "merging": return `Shipping: its checks passed on commit ${commit}; Toolroll is merging it.`;
1207
+ case "merged": return `Shipped: merged into ${cleanLiveText(ship.base)}.`;
1208
+ case "cancelled": return `Ship stopped: ${detail ?? "it was cancelled"}.`;
1209
+ case "refused":
1210
+ case "failed": return `Ship refused: ${detail ?? "its import didn't pass"}.`;
1211
+ case "sent-back": return "Sent back to this thread with your note.";
1212
+ default: return `Ship ${ship.seq}: ${cleanLiveText(ship.state)}.`;
1213
+ }
1214
+ }
1215
+ function shipFactsOf(store, thread) {
1216
+ let ship;
1217
+ try {
1218
+ ship = latestFlexibleShip(store, thread);
1219
+ }
1220
+ catch {
1221
+ return {};
1222
+ }
1223
+ if (ship === null)
1224
+ return {};
1225
+ if (ship.state === "removed")
1226
+ return ship.reason === null ? {} : { ship: { seq: ship.seq, state: "refused", words: shipWords({ ...ship, state: "refused" }) } };
1227
+ return { ship: { seq: ship.seq, state: ship.state, words: shipWords(ship) } };
1228
+ }
1229
+ export function flexibleThreadRecords(store, input) {
1230
+ const rows = store.handle.prepare("SELECT id, repo, created_at FROM flexible_thread WHERE created_by = ? AND state = 'ready' ORDER BY created_at DESC, id LIMIT 50").all(input.owner);
1231
+ return rows.map(row => {
1232
+ const id = String(row["id"]), repo = String(row["repo"]);
1233
+ const last = store.handle.prepare("SELECT id, status FROM thread_turn WHERE thread = ? AND status <> 'withdrawn' ORDER BY seq DESC LIMIT 1").get(id);
1234
+ const status = last === undefined ? null : String(last["status"]);
1235
+ const project = store.handle.prepare("SELECT name FROM project WHERE path = ?").get(repo)?.["name"];
1236
+ const end = threadEndOf(store, id).ended, ship = shipFactsOf(store, id).ship;
1237
+ return { id, title: flexibleThreadTitleOf(store, id), repo, project: typeof project === "string" ? project : null, createdAt: String(row["created_at"]), turn: status,
1238
+ endWords: last === undefined || status === null ? null : endWordsOf(store, String(last["id"]), status).endWords ?? null, ended: end !== undefined, ship: ship?.state ?? null, shipWords: ship?.words ?? null };
1239
+ });
1240
+ }
1241
+ export async function removeFlexibleThreadCopy(store, input) {
1242
+ if (ownThread(store, input.thread, { name: input.by }) === null)
1243
+ return refuse("thread-unknown");
1244
+ const removed = await removeFlexibleThread(store, { id: input.thread, by: input.by, now: input.now, ...(input.prove === undefined ? {} : { prove: input.prove }) });
1245
+ return removed.ok ? { ok: true } : { ok: false, reason: removed.reason, message: removed.message };
1246
+ }