toolroll 0.9.112 → 0.9.113

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 (42) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +28 -29
  3. package/dist/contracts/console-api.js +2 -1
  4. package/dist/contracts/engine-api.js +12 -0
  5. package/dist/easy-start.js +4 -1
  6. package/dist/engine-reads.js +15 -0
  7. package/dist/fast-terms.js +8 -4
  8. package/dist/flexible-agents.js +2 -8
  9. package/dist/flexible-answers.js +4 -26
  10. package/dist/flexible-available.js +31 -1
  11. package/dist/flexible-import.js +2 -14
  12. package/dist/flexible-launch.js +15 -3
  13. package/dist/flexible-launcher.js +0 -5
  14. package/dist/flexible-relay.js +7 -4
  15. package/dist/flexible-session.js +123 -32
  16. package/dist/flexible-setting-schema.js +10 -0
  17. package/dist/flexible-ship.js +8 -18
  18. package/dist/flexible-start.js +2 -2
  19. package/dist/flexible-thread.js +21 -27
  20. package/dist/flexible-turns.js +7 -17
  21. package/dist/flexible.js +9 -11
  22. package/dist/flow-triggers.js +4 -1
  23. package/dist/live-terminal.js +28 -0
  24. package/dist/local-owner.js +1 -0
  25. package/dist/operate.js +60 -4
  26. package/dist/release.js +1 -0
  27. package/dist/serve.js +9 -0
  28. package/dist/server/engine-api.js +91 -27
  29. package/dist/server/mutation-key.js +6 -0
  30. package/dist/server/route-table.js +3 -0
  31. package/dist/server/settings-section-table.js +3 -0
  32. package/dist/server/settings-sections.js +23 -0
  33. package/dist/server/settings.js +36 -3
  34. package/dist/server/terminals.js +3 -3
  35. package/dist/settings-proofs.js +2 -0
  36. package/dist/store.js +18 -4
  37. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  38. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  39. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  40. package/dist/tui/linux-x64/toolroll-tui +0 -0
  41. package/dist/work-index.js +4 -0
  42. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomBytes, randomUUID } from "node:crypto";
2
2
  import { StringDecoder } from "node:string_decoder";
3
- import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
3
+ import { flexibleAvailable } from "./flexible-available.js";
4
4
  import { FLEXIBLE_LEVEL_WORDS, FLEXIBLE_UNAVAILABLE, isFlexibleLevel } from "./flexible.js";
5
5
  import { lowerFlexibleThreadLevel, recoverFlexibleLaunchesOf, startFlexibleTurn } from "./flexible-agents.js";
6
6
  import { decideFlexibleAnswer, expireFlexibleAnswers, flexibleRequestsOf, noteFlexibleToolActivity, openFlexibleAnswerCatalog, recordFlexibleRequest, recoverFlexibleAnswersOf, revokeFlexibleAnswers, sendFlexibleAnswer, streamAnswerSender, } from "./flexible-answers.js";
@@ -8,7 +8,7 @@ import { startIdentityOf } from "./flexible-custody.js";
8
8
  import { defaultCustodyIO, flexibleTurnLaunched } from "./flexible-launch.js";
9
9
  import { flexibleRelayBilling, startFlexibleRelay } from "./flexible-relay.js";
10
10
  import { flexibleThread, prepareFlexibleThread, removeFlexibleThread, stopFlexibleThreadAgent } from "./flexible-thread.js";
11
- import { admitFlexibleTurn, finishFlexibleTurn, flexibleTurn, withdrawFlexibleTurn } from "./flexible-turns.js";
11
+ import { admitFlexibleTurn, finishFlexibleTurn, flexibleTurn, interruptFlexibleThreadTurns, interruptFlexibleTurnsOf, withdrawFlexibleTurn } from "./flexible-turns.js";
12
12
  import { userFrame } from "./live-input.js";
13
13
  import { cleanLiveText, createLiveRecorder, HIDDEN_LINE, liveSecretHit } from "./live-records.js";
14
14
  import { primaryResultEvent } from "./stream-scope.js";
@@ -74,8 +74,6 @@ function holderLife(holder, io) {
74
74
  return sha16(row.start) === named[2] ? "alive" : "gone";
75
75
  }
76
76
  export function openFlexibleSessions(store, input = {}) {
77
- if (!FLEXIBLE_AVAILABLE)
78
- return refuse("not-available");
79
77
  const io = input.io ?? defaultCustodyIO();
80
78
  const holder = holderOf(input.pid ?? process.pid, io);
81
79
  if (holder === null)
@@ -86,8 +84,6 @@ export function openFlexibleSessions(store, input = {}) {
86
84
  return { ok: true, sessions: { holder, catalog: opened.catalog, io, threads: new Map(), changes: new Map(), waiters: new Map() } };
87
85
  }
88
86
  export async function closeFlexibleSessions(store, sessions, input = {}) {
89
- if (!FLEXIBLE_AVAILABLE)
90
- return refuse("not-available");
91
87
  for (const thread of [...sessions.threads.keys()]) {
92
88
  try {
93
89
  await stopFlexibleThreadSession(store, sessions, { thread, reason: "Toolroll stopped", ...(input.clock === undefined ? {} : { clock: input.clock }) });
@@ -98,17 +94,124 @@ export async function closeFlexibleSessions(store, sessions, input = {}) {
98
94
  bumpAll(sessions);
99
95
  return { ok: true };
100
96
  }
97
+ export function flexibleWorkOpen(store) {
98
+ try {
99
+ return store.handle.prepare(`SELECT 1 AS open FROM flexible_thread_launch WHERE state <> 'exited'
100
+ UNION ALL SELECT 1 AS open FROM thread_turn WHERE status IN ('admitted', 'running') LIMIT 1`).get() !== undefined;
101
+ }
102
+ catch {
103
+ return true;
104
+ }
105
+ }
106
+ export function flexibleThreadsExist(store) {
107
+ try {
108
+ return store.handle.prepare("SELECT 1 AS made FROM flexible_thread LIMIT 1").get() !== undefined;
109
+ }
110
+ catch {
111
+ return true;
112
+ }
113
+ }
114
+ export async function settleFlexibleStops(store, sessions, input = {}) {
115
+ const clocked = input.clock === undefined ? {} : { clock: input.clock };
116
+ let stopped = 0, pending = 0;
117
+ if (!flexibleAvailable(store)) {
118
+ 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"]));
119
+ for (const thread of new Set([...sessions.threads.keys(), ...durable])) {
120
+ try {
121
+ const done = await stopFlexibleThreadSession(store, sessions, { thread, reason: "interactive agent threads were turned off", ...clocked });
122
+ if (done.ok && "stopped" in done && done.stopped)
123
+ stopped++;
124
+ else
125
+ pending++;
126
+ }
127
+ catch {
128
+ pending++;
129
+ }
130
+ }
131
+ return { ok: true, stopped, pending };
132
+ }
133
+ 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)
134
+ .map(row => ({ thread: String(row["thread"]), launch: String(row["id"]) }));
135
+ for (const one of unresolved) {
136
+ try {
137
+ const done = await stopFlexibleThreadAgent(store, { id: one.thread, reason: "its earlier stop wasn't verified", ...clocked, io: sessions.io, expect: { launch: one.launch, holder: sessions.holder } });
138
+ if (!("reason" in done) && done.ok) {
139
+ stopped++;
140
+ const kept = sessions.threads.get(one.thread);
141
+ if (kept !== undefined && kept.agent === null && kept.relay === null) {
142
+ sessions.threads.delete(one.thread);
143
+ bump(sessions, one.thread);
144
+ }
145
+ }
146
+ else
147
+ pending++;
148
+ }
149
+ catch {
150
+ pending++;
151
+ }
152
+ }
153
+ return { ok: true, stopped, pending };
154
+ }
155
+ export async function stopFlexibleThreadsEverywhere(store, input) {
156
+ const io = input.io ?? defaultCustodyIO();
157
+ const clocked = input.clock === undefined ? {} : { clock: input.clock };
158
+ const report = { stopped: [], survivors: [] };
159
+ const lives = new Map();
160
+ const lifeOf = (holder) => { if (!lives.has(holder))
161
+ lives.set(holder, holderLife(holder, io)); return lives.get(holder); };
162
+ const launches = store.handle.prepare("SELECT id, thread, holder FROM flexible_thread_launch WHERE state <> 'exited' ORDER BY started_at, id").all()
163
+ .map(row => ({ launch: String(row["id"]), thread: String(row["thread"]), holder: String(row["holder"]) }));
164
+ for (const one of launches) {
165
+ const gone = lifeOf(one.holder) === "gone";
166
+ let done;
167
+ try {
168
+ done = await stopFlexibleThreadAgent(store, { id: one.thread, reason: input.reason, io, ...clocked, ...(gone ? { holderGone: true } : {}), expect: { launch: one.launch, holder: one.holder } });
169
+ }
170
+ catch (error) {
171
+ report.survivors.push({ thread: one.thread, pids: [], why: error instanceof Error ? error.message : "its stop failed" });
172
+ continue;
173
+ }
174
+ if ("reason" in done) {
175
+ report.survivors.push({ thread: one.thread, pids: [], why: done.message });
176
+ continue;
177
+ }
178
+ if (done.ok) {
179
+ report.stopped.push({ thread: one.thread, network: false });
180
+ continue;
181
+ }
182
+ if (done.survivors.length === 0 && done.blockers.length === 0) {
183
+ interruptFlexibleThreadTurns(store, { thread: one.thread, detail: `the thread's agent was stopped (${input.reason})`, ...clocked });
184
+ report.stopped.push({ thread: one.thread, network: true });
185
+ }
186
+ else
187
+ report.survivors.push({ thread: one.thread, pids: [...done.survivors], why: done.why });
188
+ }
189
+ const holders = new Set(store.handle.prepare("SELECT DISTINCT holder FROM thread_turn WHERE status IN ('admitted', 'running')").all().map(row => String(row["holder"])));
190
+ const goneHolders = [...new Set([...holders, ...launches.map(one => one.holder)])].filter(holder => lifeOf(holder) === "gone"
191
+ && store.handle.prepare("SELECT 1 AS open FROM flexible_thread_launch WHERE holder = ? AND state <> 'exited'").get(holder) === undefined);
192
+ if (goneHolders.length > 0) {
193
+ for (const holder of goneHolders)
194
+ interruptFlexibleTurnsOf(store, { holder, ...clocked });
195
+ const opened = openFlexibleAnswerCatalog(store);
196
+ if (opened.ok) {
197
+ try {
198
+ for (const holder of goneHolders)
199
+ recoverFlexibleAnswersOf(store, opened.catalog, { holder, ...clocked });
200
+ }
201
+ finally {
202
+ opened.catalog.close();
203
+ }
204
+ }
205
+ }
206
+ return report;
207
+ }
101
208
  export function tickFlexibleSessions(store, sessions, input = {}) {
102
- if (!FLEXIBLE_AVAILABLE)
103
- return refuse("not-available");
104
209
  const expired = expireFlexibleAnswers(store, sessions.catalog, input.clock === undefined ? {} : { clock: input.clock });
105
210
  if (expired.ok && expired.uncertain > 0)
106
211
  bumpAll(sessions);
107
212
  return expired;
108
213
  }
109
214
  export async function recoverFlexibleHolders(store, sessions, input = {}) {
110
- if (!FLEXIBLE_AVAILABLE)
111
- return refuse("not-available");
112
215
  const clocked = input.clock === undefined ? {} : { clock: input.clock };
113
216
  const holders = new Set([
114
217
  ...store.handle.prepare("SELECT DISTINCT holder FROM flexible_thread_launch WHERE state <> 'exited'").all().map(row => String(row["holder"])),
@@ -135,7 +238,7 @@ export async function recoverFlexibleHolders(store, sessions, input = {}) {
135
238
  return { ok: true, recovered, unresolved, unknown };
136
239
  }
137
240
  export async function startFlexibleThreadSession(store, sessions, input) {
138
- if (!FLEXIBLE_AVAILABLE)
241
+ if (!flexibleAvailable(store))
139
242
  return refuse("not-available");
140
243
  if (typeof input.thread !== "string" || !ID.test(input.thread))
141
244
  return refuse("invalid-request");
@@ -151,8 +254,6 @@ export async function startFlexibleThreadSession(store, sessions, input) {
151
254
  return { ok: true, relayPort: relay.port };
152
255
  }
153
256
  export async function stopFlexibleThreadSession(store, sessions, input) {
154
- if (!FLEXIBLE_AVAILABLE)
155
- return refuse("not-available");
156
257
  if (typeof input.thread !== "string" || !ID.test(input.thread) || typeof input.reason !== "string" || input.reason.length < 1 || input.reason.length > 200)
157
258
  return refuse("invalid-request");
158
259
  const clocked = input.clock === undefined ? {} : { clock: input.clock };
@@ -167,6 +268,7 @@ export async function stopFlexibleThreadSession(store, sessions, input) {
167
268
  catch { }
168
269
  }
169
270
  const stopped = await stopFlexibleThreadAgent(store, { id: input.thread, reason: input.reason, ...clocked, io: sessions.io });
271
+ const unverified = !("reason" in stopped) && !stopped.ok;
170
272
  if (session !== undefined) {
171
273
  session.agent = null;
172
274
  try {
@@ -174,7 +276,8 @@ export async function stopFlexibleThreadSession(store, sessions, input) {
174
276
  }
175
277
  catch { }
176
278
  session.relay = null;
177
- sessions.threads.delete(input.thread);
279
+ if (!unverified)
280
+ sessions.threads.delete(input.thread);
178
281
  }
179
282
  bump(sessions, input.thread);
180
283
  if ("reason" in stopped)
@@ -301,7 +404,7 @@ function frameFor(session, requestRef, answer) {
301
404
  return Buffer.from(`${JSON.stringify({ type: "control_response", response: { subtype: "success", request_id: requestRef, response } })}\n`, "utf8");
302
405
  }
303
406
  export function attachFlexibleAgent(store, sessions, input) {
304
- if (!FLEXIBLE_AVAILABLE)
407
+ if (!flexibleAvailable(store))
305
408
  return refuse("not-available");
306
409
  if (typeof input.thread !== "string" || !ID.test(input.thread) || typeof input.launch !== "string" || !ID.test(input.launch) || (input.turn !== null && (typeof input.turn !== "string" || !ID.test(input.turn))))
307
410
  return refuse("invalid-request");
@@ -402,8 +505,6 @@ export function attachFlexibleAgent(store, sessions, input) {
402
505
  return { ok: true };
403
506
  }
404
507
  export function endFlexibleThreadTurn(store, sessions, input) {
405
- if (!FLEXIBLE_AVAILABLE)
406
- return refuse("not-available");
407
508
  if (typeof input.thread !== "string" || !ID.test(input.thread) || typeof input.turn !== "string" || !ID.test(input.turn))
408
509
  return refuse("invalid-request");
409
510
  const clocked = input.clock === undefined ? {} : { clock: input.clock };
@@ -420,8 +521,6 @@ export function endFlexibleThreadTurn(store, sessions, input) {
420
521
  return revoked;
421
522
  }
422
523
  export async function lowerFlexibleThreadSession(store, sessions, input) {
423
- if (!FLEXIBLE_AVAILABLE)
424
- return refuse("not-available");
425
524
  if (typeof input.thread !== "string" || !ID.test(input.thread) || !isFlexibleLevel(input.level))
426
525
  return refuse("invalid-request");
427
526
  const clocked = input.clock === undefined ? {} : { clock: input.clock };
@@ -435,7 +534,7 @@ export async function lowerFlexibleThreadSession(store, sessions, input) {
435
534
  return lowered;
436
535
  }
437
536
  export async function beginFlexibleThreadTurn(store, sessions, input) {
438
- if (!FLEXIBLE_AVAILABLE)
537
+ if (!flexibleAvailable(store))
439
538
  return refuse("not-available");
440
539
  if (typeof input.turn !== "string" || !ID.test(input.turn) || typeof input.message !== "string" || input.message.trim() === "" || input.message.length > 100_000)
441
540
  return refuse("invalid-request");
@@ -501,7 +600,7 @@ export async function beginFlexibleThreadTurn(store, sessions, input) {
501
600
  return { ok: true, launched: started.launched, launchId: started.launchId };
502
601
  }
503
602
  export async function startFlexibleThread(store, sessions, input) {
504
- if (!FLEXIBLE_AVAILABLE)
603
+ if (!flexibleAvailable(store))
505
604
  return refuse("not-available");
506
605
  if (typeof input.repo !== "string" || typeof input.digest !== "string" || typeof input.model !== "string" || typeof input.message !== "string" || input.message.trim() === ""
507
606
  || typeof input.startKey !== "string" || !/^[0-9a-f]{32}$/.test(input.startKey) || (input.billing !== "subscription" && input.billing !== "api-key"))
@@ -525,6 +624,8 @@ export async function startFlexibleThread(store, sessions, input) {
525
624
  return { ok: false, reason: "start-in-progress", message: "This thread is still starting. Nothing new was started; look at your threads in a moment." };
526
625
  }
527
626
  }
627
+ if (!flexibleAvailable(store))
628
+ return refuse("not-available");
528
629
  const billing = flexibleRelayBilling(store);
529
630
  if (!billing.ok)
530
631
  return billing;
@@ -578,7 +679,7 @@ async function discardRefusedStart(store, sessions, input) {
578
679
  catch { }
579
680
  }
580
681
  export async function answerFlexibleRequest(store, sessions, input) {
581
- if (!FLEXIBLE_AVAILABLE)
682
+ if (!flexibleAvailable(store))
582
683
  return refuse("not-available");
583
684
  if (typeof input.thread !== "string" || !ID.test(input.thread) || typeof input.request !== "string" || !ID.test(input.request) || typeof input.shownDigest !== "string"
584
685
  || typeof input.choice !== "object" || input.choice === null || typeof input.held !== "function")
@@ -649,8 +750,6 @@ function ownThread(store, thread, viewer) {
649
750
  return row === null || row.state !== "ready" || row.createdBy !== viewer.name ? null : row;
650
751
  }
651
752
  export function flexibleThreadLiveOf(store, sessions, input) {
652
- if (!FLEXIBLE_AVAILABLE)
653
- return refuse("not-available");
654
753
  const thread = ownThread(store, input.thread, input.viewer);
655
754
  if (thread === null)
656
755
  return refuse("thread-unknown");
@@ -671,8 +770,6 @@ export function flexibleThreadLiveOf(store, sessions, input) {
671
770
  return { ok: true, live, window: { ok: true, records, cursor: `${session.epoch}.${next}`, restarted, earlier, quarantined: 0, skipped: 0, more: next < total }, facts };
672
771
  }
673
772
  export function flexibleThreadsOf(store, sessions, input) {
674
- if (!FLEXIBLE_AVAILABLE)
675
- return refuse("not-available");
676
773
  if (typeof input.owner !== "string")
677
774
  return refuse("invalid-request");
678
775
  const rows = store.handle.prepare("SELECT id FROM flexible_thread WHERE created_by = ? AND state = 'ready' ORDER BY created_at DESC, id LIMIT 50").all(input.owner).map(row => String(row["id"]));
@@ -684,23 +781,17 @@ export function flexibleThreadsOf(store, sessions, input) {
684
781
  return { ok: true, threads };
685
782
  }
686
783
  export function admitFlexibleThreadOwner(store, sessions, input) {
687
- if (!FLEXIBLE_AVAILABLE)
688
- return refuse("not-available");
689
784
  const thread = ownThread(store, input.thread, input.viewer);
690
785
  return thread === null || !input.canAccess(thread.repo) ? refuse("thread-unknown") : { ok: true, repo: thread.repo };
691
786
  }
692
787
  export const FLEXIBLE_WAIT_MS = 20_000;
693
788
  export const FLEXIBLE_WAITERS_MAX = 64;
694
789
  export function flexibleThreadChangeOf(sessions, input) {
695
- if (!FLEXIBLE_AVAILABLE)
696
- return refuse("not-available");
697
790
  if (typeof input.thread !== "string" || !ID.test(input.thread))
698
791
  return refuse("invalid-request");
699
792
  return { ok: true, change: sessions.changes.get(input.thread) ?? 0 };
700
793
  }
701
794
  export function waitFlexibleThreadChange(sessions, input) {
702
- if (!FLEXIBLE_AVAILABLE)
703
- return refuse("not-available");
704
795
  if (typeof input.thread !== "string" || !ID.test(input.thread) || !Number.isSafeInteger(input.since) || !Number.isSafeInteger(input.ms) || input.ms < 0 || input.ms > FLEXIBLE_WAIT_MS)
705
796
  return refuse("invalid-request");
706
797
  if ((sessions.changes.get(input.thread) ?? 0) !== input.since)
@@ -0,0 +1,10 @@
1
+ export const V171_SCHEMA = `
2
+ CREATE TABLE IF NOT EXISTS flexible_setting (
3
+ id INTEGER PRIMARY KEY CHECK (id = 1),
4
+ enabled INTEGER NOT NULL CHECK (enabled IN (0,1)),
5
+ updated_by TEXT NOT NULL,
6
+ updated_at TEXT NOT NULL
7
+ );
8
+ `;
9
+ export const V171_TABLES = Object.freeze(["flexible_setting"]);
10
+ export const V171_STEPS = Object.freeze(["flexible-setting"]);
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomBytes } from "node:crypto";
2
2
  import { realpathSync } from "node:fs";
3
- import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
3
+ import { flexibleAvailable } from "./flexible-available.js";
4
4
  import { FLEXIBLE_UNAVAILABLE, flexibleNetworkOf, flexibleStanding, flexibleTwoPerson } from "./flexible.js";
5
5
  import { flexibleThread, flexibleThreadBranch, withFlexibleThreadLock } from "./flexible-thread.js";
6
6
  import { flexibleImportRef, flexibleTaskBranch, importFlexibleCandidate, readFlexibleCandidate, removeFlexibleImportRefs, settleInterruptedImport } from "./flexible-import.js";
@@ -111,8 +111,6 @@ function destinationOf(store, repo) {
111
111
  return { repo: grant.githubRepo, remote: grant.remote, base: grant.base, method: grant.mergeMethod ?? "squash", capabilities: [...grant.capabilities].sort(), draft: grant.draft };
112
112
  }
113
113
  export async function flexibleShipTerms(store, input) {
114
- if (!FLEXIBLE_AVAILABLE)
115
- return refuse("not-available");
116
114
  const thread = flexibleThread(store, input.thread);
117
115
  if (thread === null)
118
116
  return refuse("thread-unknown");
@@ -145,8 +143,6 @@ export async function flexibleShipTerms(store, input) {
145
143
  return { ok: true, terms, digest, summary: flexibleShipSummary(terms, digest) };
146
144
  }
147
145
  export async function shipFlexible(store, input) {
148
- if (!FLEXIBLE_AVAILABLE)
149
- return refuse("not-available");
150
146
  const first = flexibleThread(store, input.thread);
151
147
  if (first === null)
152
148
  return refuse("thread-unknown");
@@ -226,6 +222,8 @@ async function fileAndSeal(store, input) {
226
222
  return kept(refuse("handoff-failed", "its task's branch couldn't be made"));
227
223
  try {
228
224
  return store.transact(() => {
225
+ if (!flexibleAvailable(store))
226
+ throw new ShipStop(refuse("not-available"));
229
227
  const row = store.handle.prepare("SELECT state FROM flexible_ship WHERE id = ?").get(digest);
230
228
  if (row?.["state"] !== "imported")
231
229
  throw new ShipStop(refuse("wrong-state"));
@@ -283,8 +281,6 @@ function readRow(row) {
283
281
  mergeToken: text("merge_token"), mergeReservedAt: text("merge_reserved_at"), delegationId: Number(row["delegation_id"]), stateAt: String(row["state_at"]) };
284
282
  }
285
283
  export function flexibleShipsOf(store, thread) {
286
- if (!FLEXIBLE_AVAILABLE)
287
- return refuse("not-available");
288
284
  const rows = store.handle.prepare("SELECT * FROM flexible_ship WHERE thread = ? ORDER BY seq DESC").all(thread);
289
285
  return { ok: true, ships: rows.map(readRow).filter((one) => one !== null) };
290
286
  }
@@ -352,7 +348,7 @@ function passingCheck(store, root, runId, ship, now) {
352
348
  return view.value.head === ship.candidate && view.value.command.digest === ship.terms.check.digest && result.exitCode === 0 ? evidence.digest : null;
353
349
  }
354
350
  export async function mergeArmedFlexible(store, input) {
355
- if (!FLEXIBLE_AVAILABLE)
351
+ if (!flexibleAvailable(store))
356
352
  return refuse("not-available");
357
353
  const clock = input.clock ?? (() => new Date());
358
354
  const found = rowOfTask(store, input.taskId);
@@ -394,6 +390,8 @@ export async function mergeArmedFlexible(store, input) {
394
390
  return { ok: true, state: "waiting", why: "its result isn't ready to complete yet" };
395
391
  try {
396
392
  store.transact(() => {
393
+ if (!flexibleAvailable(store))
394
+ throw new ShipStop(refuse("not-available"));
397
395
  const again = rowOfTask(store, input.taskId);
398
396
  if (again === null || again.state !== "armed")
399
397
  throw new ShipStop(refuse("wrong-state"));
@@ -472,6 +470,8 @@ export async function mergeArmedFlexible(store, input) {
472
470
  return { ok: true, state: "waiting", why: merged.message };
473
471
  }
474
472
  function reserveMerge(store, input) {
473
+ if (!flexibleAvailable(store))
474
+ return false;
475
475
  const ship = readRow(store.handle.prepare("SELECT * FROM flexible_ship WHERE id = ?").get(input.ship));
476
476
  if (ship === null || ship.state !== "completed" || ship.taskId === null)
477
477
  return false;
@@ -553,8 +553,6 @@ async function settleUncertainMerges(store, exec, clock) {
553
553
  return settled;
554
554
  }
555
555
  export async function reconcileFlexibleShips(store, input) {
556
- if (!FLEXIBLE_AVAILABLE)
557
- return refuse("not-available");
558
556
  const stuck = store.handle.prepare("SELECT * FROM flexible_ship WHERE state = 'approved' ORDER BY thread, seq").all();
559
557
  let settled = 0;
560
558
  for (const raw of stuck) {
@@ -587,8 +585,6 @@ export async function reconcileFlexibleShips(store, input) {
587
585
  return { ok: true, settled };
588
586
  }
589
587
  export async function flexibleArmedPass(store, input) {
590
- if (!FLEXIBLE_AVAILABLE)
591
- return refuse("not-available");
592
588
  const clock = input.clock ?? (() => new Date());
593
589
  const runner = input.runner === undefined ? {} : { runner: input.runner };
594
590
  const reconciled = await reconcileFlexibleShips(store, { now: clock(), ...runner });
@@ -629,8 +625,6 @@ function ownersShip(store, taskId, by) {
629
625
  return ship;
630
626
  }
631
627
  export function cancelFlexibleShip(store, input) {
632
- if (!FLEXIBLE_AVAILABLE)
633
- return refuse("not-available");
634
628
  if (machineActing())
635
629
  return refuse("machine-proof");
636
630
  return store.transact(() => {
@@ -644,8 +638,6 @@ export function cancelFlexibleShip(store, input) {
644
638
  });
645
639
  }
646
640
  export function sendBackFlexible(store, input) {
647
- if (!FLEXIBLE_AVAILABLE)
648
- return refuse("not-available");
649
641
  if (machineActing())
650
642
  return refuse("machine-proof");
651
643
  const feedback = input.feedback.trim();
@@ -664,8 +656,6 @@ export function sendBackFlexible(store, input) {
664
656
  });
665
657
  }
666
658
  export async function removeFlexibleImport(store, input) {
667
- if (!FLEXIBLE_AVAILABLE)
668
- return refuse("not-available");
669
659
  if (machineActing())
670
660
  return refuse("machine-proof");
671
661
  const ship = readRow(store.handle.prepare("SELECT * FROM flexible_ship WHERE id = ?").get(input.ship));
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
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
5
  import { flexibleRelayBilling } from "./flexible-relay.js";
@@ -23,7 +23,7 @@ const lowerFirst = (text) => text.charAt(0).toLowerCase() + text.slice(1);
23
23
  export const FLEXIBLE_SHIP_WORDS = "One press. Toolroll merges only when the project's required check passes on that exact commit. A failed or missing check never merges, there is no merge anyway, and any change to the commit cancels it.";
24
24
  export const FLEXIBLE_UNKNOWN_COST_WORDS = "If Toolroll can't measure what a turn on an API key cost, that turn holds the monthly budgets it counts toward until the month ends, and a daily dollar limit until the next day (UTC).";
25
25
  export function flexibleStartCard(store, input) {
26
- if (!FLEXIBLE_AVAILABLE)
26
+ if (!flexibleAvailable(store))
27
27
  return refuse("not-available");
28
28
  const model = input.model === null || input.model === "" ? FLEXIBLE_DEFAULT_MODEL : input.model;
29
29
  if (typeof input.repo !== "string" || input.repo === "" || typeof model !== "string" || !RELAY_MODEL.test(model) || typeof input.message !== "string"
@@ -3,7 +3,7 @@ import { createHash, randomBytes } from "node:crypto";
3
3
  import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
6
- import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
6
+ import { flexibleAvailable } from "./flexible-available.js";
7
7
  import { FLEXIBLE_UNAVAILABLE } from "./flexible.js";
8
8
  import { buildCacheEnv, fenceFor, FLEXIBLE_THREADS_DIR, grantFolder, PROTECTED_DIRS, PROTECTED_FILES, runFolders, srtTermsOf } from "./agent-fence.js";
9
9
  import { ACP_AGENTS, ACP_PROVIDER_IDS } from "./acp-agents.js";
@@ -13,9 +13,10 @@ import { hardenedGit, lazyFetchSetting, recordedCommonDir } from "./teardown-git
13
13
  import { withCheckoutLock } from "./git-views.js";
14
14
  import { processMayBeAlive } from "./process-liveness.js";
15
15
  import { startIdentityOf } from "./flexible-custody.js";
16
- import { defaultCustodyIO, holdLaunch, recordGateShut, recordLaunchOpened, recordLive, recordNeverStarted, recordSpawning, settleLaunch, unsettledLaunch } from "./flexible-launch.js";
16
+ import { defaultCustodyIO, holdLaunch, recordGateShut, recordLive, reserveLaunchOpen, recordNeverStarted, recordSpawning, settleLaunch, unsettledLaunch } from "./flexible-launch.js";
17
17
  import { readProjectRefs, saveRefSnapshot } from "./flexible-refs.js";
18
18
  import { projectRowKnown } from "./store.js";
19
+ import { readProjectRegistryNow } from "./repos.js";
19
20
  import { poolRootOf } from "./worktree.js";
20
21
  export const FLEXIBLE_THREAD_ID = /^[0-9a-f]{32}$/;
21
22
  export const flexibleKeepRef = (id) => `refs/toolroll/threads/${id}/base`;
@@ -167,12 +168,12 @@ function reserveProtectedNames(repo) {
167
168
  writeFileSync(join(repo, ".git", "info", "exclude"), ["# Toolroll: placeholders that hold protected names (flexible-thread.ts)", ...reserved, ""].join("\n"), { mode: 0o644, flag: "wx" });
168
169
  }
169
170
  export async function prepareFlexibleThread(store, input) {
170
- if (!FLEXIBLE_AVAILABLE)
171
+ if (!flexibleAvailable(store))
171
172
  return refuse("not-available");
172
173
  const state = stateFolderOf(store);
173
174
  if (state === null)
174
175
  return refuse("no-state-folder");
175
- if (!projectRowKnown(store, input.repo))
176
+ if (!flexibleProjectKnown(store, input.repo))
176
177
  return refuse("not-a-project");
177
178
  if (!BASE_NAME.test(input.base) || input.base.includes(".."))
178
179
  return refuse("base-unknown");
@@ -260,8 +261,6 @@ export async function prepareFlexibleThread(store, input) {
260
261
  }
261
262
  }
262
263
  export async function removeFlexibleThread(store, input) {
263
- if (!FLEXIBLE_AVAILABLE)
264
- return refuse("not-available");
265
264
  if (!FLEXIBLE_THREAD_ID.test(input.id))
266
265
  return refuse("thread-unknown");
267
266
  return withThreadLock(input.id, () => removeLocked(store, input));
@@ -383,7 +382,7 @@ function threadReadOnly(paths) {
383
382
  ...TOP_PROTECTED.map(one => join(paths.repo, one.name))].sort();
384
383
  }
385
384
  export function flexibleThreadFence(store, input) {
386
- if (!FLEXIBLE_AVAILABLE)
385
+ if (!flexibleAvailable(store))
387
386
  return refuse("not-available");
388
387
  const network = input.network;
389
388
  if (!Number.isSafeInteger(network.proxyPort) || network.proxyPort < 1 || network.proxyPort > 65_535 || typeof network.token !== "string" || network.token === "")
@@ -399,7 +398,7 @@ export function flexibleThreadFence(store, input) {
399
398
  return refuse("thread-unknown");
400
399
  if (thread.state !== "ready")
401
400
  return refuse("thread-not-ready");
402
- if (!projectRowKnown(store, thread.repo))
401
+ if (!flexibleProjectKnown(store, thread.repo))
403
402
  return refuse("not-a-project");
404
403
  let project, objects;
405
404
  try {
@@ -513,8 +512,6 @@ function withThreadLock(id, work, timeoutMs) {
513
512
  return withCheckoutLock(real(homedir()), `flexible-thread:${id}`, work, timeoutMs);
514
513
  }
515
514
  export async function withFlexibleThreadLock(id, work, timeoutMs) {
516
- if (!FLEXIBLE_AVAILABLE)
517
- return refuse("not-available");
518
515
  if (!FLEXIBLE_THREAD_ID.test(id))
519
516
  return refuse("thread-unknown");
520
517
  return withThreadLock(id, work, timeoutMs);
@@ -538,7 +535,7 @@ function stopUnopenedLaunch(child) {
538
535
  }
539
536
  }
540
537
  export async function flexibleThreadSpawn(store, input, file, args, platform = process.platform, seams = {}) {
541
- if (!FLEXIBLE_AVAILABLE)
538
+ if (!flexibleAvailable(store))
542
539
  return refuse("not-available");
543
540
  if (!FLEXIBLE_THREAD_ID.test(input.id))
544
541
  return refuse("thread-unknown");
@@ -622,7 +619,9 @@ async function spawnLocked(store, input, file, args, platform, seams) {
622
619
  }
623
620
  let shut;
624
621
  try {
625
- shut = input.beforeOpen?.() ?? null;
622
+ if (typeof input.beforeOpen !== "function")
623
+ throw new Error("the start has no last re-check");
624
+ shut = reserveLaunchOpen(store, { launch: record.id, thread: input.id, turn: input.launch.turn, check: input.beforeOpen });
626
625
  }
627
626
  catch (error) {
628
627
  shut = error instanceof Error ? error.message : "the start couldn't be re-checked";
@@ -636,24 +635,10 @@ async function spawnLocked(store, input, file, args, platform, seams) {
636
635
  recordGateShut(store, { launch: record.id, thread: input.id, pid: pid, detail: `stopped before it ran: ${shut}` });
637
636
  return refuse("thread-not-ready", shut);
638
637
  }
639
- try {
640
- recordLaunchOpened(store, { launch: record.id, thread: input.id, turn: input.launch.turn });
641
- }
642
- catch {
643
- try {
644
- child.stdin?.destroy();
645
- }
646
- catch { }
647
- stopUnopenedLaunch(child);
648
- recordGateShut(store, { launch: record.id, thread: input.id, pid: pid, detail: "stopped before it ran: its launch couldn't be recorded" });
649
- return refuse("thread-not-ready", "its launch couldn't be recorded");
650
- }
651
638
  child.stdin.write("start\n");
652
639
  return { ok: true, pid: pid, launchId: record.id, launch, fenceDigest, child };
653
640
  }
654
641
  export async function stopFlexibleThreadAgent(store, input) {
655
- if (!FLEXIBLE_AVAILABLE)
656
- return refuse("not-available");
657
642
  if (!FLEXIBLE_THREAD_ID.test(input.id))
658
643
  return refuse("thread-unknown");
659
644
  return withThreadLock(input.id, async () => {
@@ -668,9 +653,18 @@ export async function stopFlexibleThreadAgent(store, input) {
668
653
  });
669
654
  }
670
655
  export function flexibleThreadCodexProfile(store, input) {
671
- if (!FLEXIBLE_AVAILABLE)
656
+ if (!flexibleAvailable(store))
672
657
  return refuse("not-available");
673
658
  void store;
674
659
  void input;
675
660
  return refuse("codex-unsupported");
676
661
  }
662
+ export function flexibleProjectKnown(store, repo) {
663
+ if (projectRowKnown(store, repo))
664
+ return true;
665
+ const file = store.databaseFile();
666
+ if (file === null || file === "" || file === ":memory:")
667
+ return false;
668
+ const registry = readProjectRegistryNow(join(dirname(file), "repos.json"));
669
+ return !("error" in registry) && registry.repos.includes(repo);
670
+ }