toolroll 0.9.112 → 0.9.114

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 (52) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +28 -29
  3. package/dist/backup.js +29 -0
  4. package/dist/contracts/console-api.js +5 -1
  5. package/dist/contracts/engine-api.js +12 -0
  6. package/dist/easy-start.js +12 -7
  7. package/dist/engine-reads.js +20 -2
  8. package/dist/fast-terms.js +8 -4
  9. package/dist/flexible-agents.js +2 -8
  10. package/dist/flexible-answers.js +4 -26
  11. package/dist/flexible-available.js +31 -1
  12. package/dist/flexible-import.js +2 -14
  13. package/dist/flexible-launch.js +15 -3
  14. package/dist/flexible-launcher.js +0 -5
  15. package/dist/flexible-relay.js +66 -75
  16. package/dist/flexible-session.js +130 -36
  17. package/dist/flexible-setting-schema.js +10 -0
  18. package/dist/flexible-ship.js +8 -18
  19. package/dist/flexible-sign-in-schema.js +47 -0
  20. package/dist/flexible-sign-in-slot.js +4 -0
  21. package/dist/flexible-sign-in.js +470 -0
  22. package/dist/flexible-start.js +27 -8
  23. package/dist/flexible-thread.js +21 -27
  24. package/dist/flexible-turns.js +22 -17
  25. package/dist/flexible.js +9 -11
  26. package/dist/flow-triggers.js +4 -1
  27. package/dist/live-terminal.js +28 -0
  28. package/dist/local-owner.js +1 -0
  29. package/dist/operate.js +170 -4
  30. package/dist/release.js +1 -0
  31. package/dist/serve.js +9 -0
  32. package/dist/server/engine-api.js +112 -32
  33. package/dist/server/mutation-key.js +6 -0
  34. package/dist/server/people-tokens.js +10 -1
  35. package/dist/server/route-table.js +6 -0
  36. package/dist/server/settings-section-table.js +7 -0
  37. package/dist/server/settings-sections.js +87 -1
  38. package/dist/server/settings.js +123 -3
  39. package/dist/server/terminals.js +3 -3
  40. package/dist/settings-groups-ui.js +3 -0
  41. package/dist/settings-proofs.js +5 -0
  42. package/dist/store.js +71 -5
  43. package/dist/tool-secret-store.js +105 -0
  44. package/dist/toolroll-update.js +2 -1
  45. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  46. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  47. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  48. package/dist/tui/linux-x64/toolroll-tui +0 -0
  49. package/dist/tui-contract.js +2 -1
  50. package/dist/tui-launch.js +3 -1
  51. package/dist/work-index.js +4 -0
  52. package/package.json +1 -1
@@ -1,14 +1,15 @@
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";
7
7
  import { startIdentityOf } from "./flexible-custody.js";
8
8
  import { defaultCustodyIO, flexibleTurnLaunched } from "./flexible-launch.js";
9
- import { flexibleRelayBilling, startFlexibleRelay } from "./flexible-relay.js";
9
+ import { startFlexibleRelay } from "./flexible-relay.js";
10
+ import { flexibleSignInBilling } from "./flexible-sign-in.js";
10
11
  import { flexibleThread, prepareFlexibleThread, removeFlexibleThread, stopFlexibleThreadAgent } from "./flexible-thread.js";
11
- import { admitFlexibleTurn, finishFlexibleTurn, flexibleTurn, withdrawFlexibleTurn } from "./flexible-turns.js";
12
+ import { admitFlexibleTurn, finishFlexibleTurn, flexibleTurn, interruptFlexibleThreadTurns, interruptFlexibleTurnsOf, withdrawFlexibleTurn } from "./flexible-turns.js";
12
13
  import { userFrame } from "./live-input.js";
13
14
  import { cleanLiveText, createLiveRecorder, HIDDEN_LINE, liveSecretHit } from "./live-records.js";
14
15
  import { primaryResultEvent } from "./stream-scope.js";
@@ -74,8 +75,6 @@ function holderLife(holder, io) {
74
75
  return sha16(row.start) === named[2] ? "alive" : "gone";
75
76
  }
76
77
  export function openFlexibleSessions(store, input = {}) {
77
- if (!FLEXIBLE_AVAILABLE)
78
- return refuse("not-available");
79
78
  const io = input.io ?? defaultCustodyIO();
80
79
  const holder = holderOf(input.pid ?? process.pid, io);
81
80
  if (holder === null)
@@ -86,8 +85,6 @@ export function openFlexibleSessions(store, input = {}) {
86
85
  return { ok: true, sessions: { holder, catalog: opened.catalog, io, threads: new Map(), changes: new Map(), waiters: new Map() } };
87
86
  }
88
87
  export async function closeFlexibleSessions(store, sessions, input = {}) {
89
- if (!FLEXIBLE_AVAILABLE)
90
- return refuse("not-available");
91
88
  for (const thread of [...sessions.threads.keys()]) {
92
89
  try {
93
90
  await stopFlexibleThreadSession(store, sessions, { thread, reason: "Toolroll stopped", ...(input.clock === undefined ? {} : { clock: input.clock }) });
@@ -98,17 +95,124 @@ export async function closeFlexibleSessions(store, sessions, input = {}) {
98
95
  bumpAll(sessions);
99
96
  return { ok: true };
100
97
  }
98
+ export function flexibleWorkOpen(store) {
99
+ try {
100
+ return store.handle.prepare(`SELECT 1 AS open FROM flexible_thread_launch WHERE state <> 'exited'
101
+ UNION ALL SELECT 1 AS open FROM thread_turn WHERE status IN ('admitted', 'running') LIMIT 1`).get() !== undefined;
102
+ }
103
+ catch {
104
+ return true;
105
+ }
106
+ }
107
+ export function flexibleThreadsExist(store) {
108
+ try {
109
+ return store.handle.prepare("SELECT 1 AS made FROM flexible_thread LIMIT 1").get() !== undefined;
110
+ }
111
+ catch {
112
+ return true;
113
+ }
114
+ }
115
+ export async function settleFlexibleStops(store, sessions, input = {}) {
116
+ const clocked = input.clock === undefined ? {} : { clock: input.clock };
117
+ let stopped = 0, pending = 0;
118
+ if (!flexibleAvailable(store)) {
119
+ 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"]));
120
+ for (const thread of new Set([...sessions.threads.keys(), ...durable])) {
121
+ try {
122
+ const done = await stopFlexibleThreadSession(store, sessions, { thread, reason: "interactive agent threads were turned off", ...clocked });
123
+ if (done.ok && "stopped" in done && done.stopped)
124
+ stopped++;
125
+ else
126
+ pending++;
127
+ }
128
+ catch {
129
+ pending++;
130
+ }
131
+ }
132
+ return { ok: true, stopped, pending };
133
+ }
134
+ 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
+ .map(row => ({ thread: String(row["thread"]), launch: String(row["id"]) }));
136
+ for (const one of unresolved) {
137
+ try {
138
+ 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 } });
139
+ if (!("reason" in done) && done.ok) {
140
+ stopped++;
141
+ const kept = sessions.threads.get(one.thread);
142
+ if (kept !== undefined && kept.agent === null && kept.relay === null) {
143
+ sessions.threads.delete(one.thread);
144
+ bump(sessions, one.thread);
145
+ }
146
+ }
147
+ else
148
+ pending++;
149
+ }
150
+ catch {
151
+ pending++;
152
+ }
153
+ }
154
+ return { ok: true, stopped, pending };
155
+ }
156
+ export async function stopFlexibleThreadsEverywhere(store, input) {
157
+ const io = input.io ?? defaultCustodyIO();
158
+ const clocked = input.clock === undefined ? {} : { clock: input.clock };
159
+ const report = { stopped: [], survivors: [] };
160
+ const lives = new Map();
161
+ const lifeOf = (holder) => { if (!lives.has(holder))
162
+ 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()
164
+ .map(row => ({ launch: String(row["id"]), thread: String(row["thread"]), holder: String(row["holder"]) }));
165
+ for (const one of launches) {
166
+ const gone = lifeOf(one.holder) === "gone";
167
+ let done;
168
+ try {
169
+ done = await stopFlexibleThreadAgent(store, { id: one.thread, reason: input.reason, io, ...clocked, ...(gone ? { holderGone: true } : {}), expect: { launch: one.launch, holder: one.holder } });
170
+ }
171
+ catch (error) {
172
+ report.survivors.push({ thread: one.thread, pids: [], why: error instanceof Error ? error.message : "its stop failed" });
173
+ continue;
174
+ }
175
+ if ("reason" in done) {
176
+ report.survivors.push({ thread: one.thread, pids: [], why: done.message });
177
+ continue;
178
+ }
179
+ if (done.ok) {
180
+ report.stopped.push({ thread: one.thread, network: false });
181
+ continue;
182
+ }
183
+ if (done.survivors.length === 0 && done.blockers.length === 0) {
184
+ interruptFlexibleThreadTurns(store, { thread: one.thread, detail: `the thread's agent was stopped (${input.reason})`, ...clocked });
185
+ report.stopped.push({ thread: one.thread, network: true });
186
+ }
187
+ else
188
+ report.survivors.push({ thread: one.thread, pids: [...done.survivors], why: done.why });
189
+ }
190
+ 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
+ const goneHolders = [...new Set([...holders, ...launches.map(one => one.holder)])].filter(holder => lifeOf(holder) === "gone"
192
+ && store.handle.prepare("SELECT 1 AS open FROM flexible_thread_launch WHERE holder = ? AND state <> 'exited'").get(holder) === undefined);
193
+ if (goneHolders.length > 0) {
194
+ for (const holder of goneHolders)
195
+ interruptFlexibleTurnsOf(store, { holder, ...clocked });
196
+ const opened = openFlexibleAnswerCatalog(store);
197
+ if (opened.ok) {
198
+ try {
199
+ for (const holder of goneHolders)
200
+ recoverFlexibleAnswersOf(store, opened.catalog, { holder, ...clocked });
201
+ }
202
+ finally {
203
+ opened.catalog.close();
204
+ }
205
+ }
206
+ }
207
+ return report;
208
+ }
101
209
  export function tickFlexibleSessions(store, sessions, input = {}) {
102
- if (!FLEXIBLE_AVAILABLE)
103
- return refuse("not-available");
104
210
  const expired = expireFlexibleAnswers(store, sessions.catalog, input.clock === undefined ? {} : { clock: input.clock });
105
211
  if (expired.ok && expired.uncertain > 0)
106
212
  bumpAll(sessions);
107
213
  return expired;
108
214
  }
109
215
  export async function recoverFlexibleHolders(store, sessions, input = {}) {
110
- if (!FLEXIBLE_AVAILABLE)
111
- return refuse("not-available");
112
216
  const clocked = input.clock === undefined ? {} : { clock: input.clock };
113
217
  const holders = new Set([
114
218
  ...store.handle.prepare("SELECT DISTINCT holder FROM flexible_thread_launch WHERE state <> 'exited'").all().map(row => String(row["holder"])),
@@ -135,7 +239,7 @@ export async function recoverFlexibleHolders(store, sessions, input = {}) {
135
239
  return { ok: true, recovered, unresolved, unknown };
136
240
  }
137
241
  export async function startFlexibleThreadSession(store, sessions, input) {
138
- if (!FLEXIBLE_AVAILABLE)
242
+ if (!flexibleAvailable(store))
139
243
  return refuse("not-available");
140
244
  if (typeof input.thread !== "string" || !ID.test(input.thread))
141
245
  return refuse("invalid-request");
@@ -151,8 +255,6 @@ export async function startFlexibleThreadSession(store, sessions, input) {
151
255
  return { ok: true, relayPort: relay.port };
152
256
  }
153
257
  export async function stopFlexibleThreadSession(store, sessions, input) {
154
- if (!FLEXIBLE_AVAILABLE)
155
- return refuse("not-available");
156
258
  if (typeof input.thread !== "string" || !ID.test(input.thread) || typeof input.reason !== "string" || input.reason.length < 1 || input.reason.length > 200)
157
259
  return refuse("invalid-request");
158
260
  const clocked = input.clock === undefined ? {} : { clock: input.clock };
@@ -167,6 +269,7 @@ export async function stopFlexibleThreadSession(store, sessions, input) {
167
269
  catch { }
168
270
  }
169
271
  const stopped = await stopFlexibleThreadAgent(store, { id: input.thread, reason: input.reason, ...clocked, io: sessions.io });
272
+ const unverified = !("reason" in stopped) && !stopped.ok;
170
273
  if (session !== undefined) {
171
274
  session.agent = null;
172
275
  try {
@@ -174,7 +277,8 @@ export async function stopFlexibleThreadSession(store, sessions, input) {
174
277
  }
175
278
  catch { }
176
279
  session.relay = null;
177
- sessions.threads.delete(input.thread);
280
+ if (!unverified)
281
+ sessions.threads.delete(input.thread);
178
282
  }
179
283
  bump(sessions, input.thread);
180
284
  if ("reason" in stopped)
@@ -301,7 +405,7 @@ function frameFor(session, requestRef, answer) {
301
405
  return Buffer.from(`${JSON.stringify({ type: "control_response", response: { subtype: "success", request_id: requestRef, response } })}\n`, "utf8");
302
406
  }
303
407
  export function attachFlexibleAgent(store, sessions, input) {
304
- if (!FLEXIBLE_AVAILABLE)
408
+ if (!flexibleAvailable(store))
305
409
  return refuse("not-available");
306
410
  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
411
  return refuse("invalid-request");
@@ -402,8 +506,6 @@ export function attachFlexibleAgent(store, sessions, input) {
402
506
  return { ok: true };
403
507
  }
404
508
  export function endFlexibleThreadTurn(store, sessions, input) {
405
- if (!FLEXIBLE_AVAILABLE)
406
- return refuse("not-available");
407
509
  if (typeof input.thread !== "string" || !ID.test(input.thread) || typeof input.turn !== "string" || !ID.test(input.turn))
408
510
  return refuse("invalid-request");
409
511
  const clocked = input.clock === undefined ? {} : { clock: input.clock };
@@ -420,8 +522,6 @@ export function endFlexibleThreadTurn(store, sessions, input) {
420
522
  return revoked;
421
523
  }
422
524
  export async function lowerFlexibleThreadSession(store, sessions, input) {
423
- if (!FLEXIBLE_AVAILABLE)
424
- return refuse("not-available");
425
525
  if (typeof input.thread !== "string" || !ID.test(input.thread) || !isFlexibleLevel(input.level))
426
526
  return refuse("invalid-request");
427
527
  const clocked = input.clock === undefined ? {} : { clock: input.clock };
@@ -435,7 +535,7 @@ export async function lowerFlexibleThreadSession(store, sessions, input) {
435
535
  return lowered;
436
536
  }
437
537
  export async function beginFlexibleThreadTurn(store, sessions, input) {
438
- if (!FLEXIBLE_AVAILABLE)
538
+ if (!flexibleAvailable(store))
439
539
  return refuse("not-available");
440
540
  if (typeof input.turn !== "string" || !ID.test(input.turn) || typeof input.message !== "string" || input.message.trim() === "" || input.message.length > 100_000)
441
541
  return refuse("invalid-request");
@@ -501,7 +601,7 @@ export async function beginFlexibleThreadTurn(store, sessions, input) {
501
601
  return { ok: true, launched: started.launched, launchId: started.launchId };
502
602
  }
503
603
  export async function startFlexibleThread(store, sessions, input) {
504
- if (!FLEXIBLE_AVAILABLE)
604
+ if (!flexibleAvailable(store))
505
605
  return refuse("not-available");
506
606
  if (typeof input.repo !== "string" || typeof input.digest !== "string" || typeof input.model !== "string" || typeof input.message !== "string" || input.message.trim() === ""
507
607
  || typeof input.startKey !== "string" || !/^[0-9a-f]{32}$/.test(input.startKey) || (input.billing !== "subscription" && input.billing !== "api-key"))
@@ -525,11 +625,15 @@ export async function startFlexibleThread(store, sessions, input) {
525
625
  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
626
  }
527
627
  }
528
- const billing = flexibleRelayBilling(store);
628
+ if (!flexibleAvailable(store))
629
+ return refuse("not-available");
630
+ const billing = flexibleSignInBilling(store, input.by);
529
631
  if (!billing.ok)
530
- return billing;
632
+ return { ok: false, reason: billing.reason, message: billing.reason === "no-sign-in"
633
+ ? "Threads use your own Claude sign-in, and you haven't saved one (or it was removed). Nothing was started."
634
+ : "Claude didn't accept your sign-in for threads. Save a new one, then start again. Nothing was started." };
531
635
  if (billing.billing !== input.billing)
532
- return { ok: false, reason: "billing-changed", message: "Toolroll's Claude sign-in for Flexible threads changed since the terms were shown. Look at them again before starting. Nothing was started." };
636
+ return { ok: false, reason: "billing-changed", message: "Your Claude sign-in for threads changed since the terms were shown. Look at them again before starting. Nothing was started." };
533
637
  const admitted = admitFlexibleTurn(store, { thread: id, starter: input.by, digest: input.digest, level: "full", freshProof: input.freshProof === true, provider: "claude", model: input.model,
534
638
  billing: input.billing, requestKey, holder: sessions.holder, clock, opening: true });
535
639
  if (!admitted.ok)
@@ -578,7 +682,7 @@ async function discardRefusedStart(store, sessions, input) {
578
682
  catch { }
579
683
  }
580
684
  export async function answerFlexibleRequest(store, sessions, input) {
581
- if (!FLEXIBLE_AVAILABLE)
685
+ if (!flexibleAvailable(store))
582
686
  return refuse("not-available");
583
687
  if (typeof input.thread !== "string" || !ID.test(input.thread) || typeof input.request !== "string" || !ID.test(input.request) || typeof input.shownDigest !== "string"
584
688
  || typeof input.choice !== "object" || input.choice === null || typeof input.held !== "function")
@@ -649,8 +753,6 @@ function ownThread(store, thread, viewer) {
649
753
  return row === null || row.state !== "ready" || row.createdBy !== viewer.name ? null : row;
650
754
  }
651
755
  export function flexibleThreadLiveOf(store, sessions, input) {
652
- if (!FLEXIBLE_AVAILABLE)
653
- return refuse("not-available");
654
756
  const thread = ownThread(store, input.thread, input.viewer);
655
757
  if (thread === null)
656
758
  return refuse("thread-unknown");
@@ -671,8 +773,6 @@ export function flexibleThreadLiveOf(store, sessions, input) {
671
773
  return { ok: true, live, window: { ok: true, records, cursor: `${session.epoch}.${next}`, restarted, earlier, quarantined: 0, skipped: 0, more: next < total }, facts };
672
774
  }
673
775
  export function flexibleThreadsOf(store, sessions, input) {
674
- if (!FLEXIBLE_AVAILABLE)
675
- return refuse("not-available");
676
776
  if (typeof input.owner !== "string")
677
777
  return refuse("invalid-request");
678
778
  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 +784,17 @@ export function flexibleThreadsOf(store, sessions, input) {
684
784
  return { ok: true, threads };
685
785
  }
686
786
  export function admitFlexibleThreadOwner(store, sessions, input) {
687
- if (!FLEXIBLE_AVAILABLE)
688
- return refuse("not-available");
689
787
  const thread = ownThread(store, input.thread, input.viewer);
690
788
  return thread === null || !input.canAccess(thread.repo) ? refuse("thread-unknown") : { ok: true, repo: thread.repo };
691
789
  }
692
790
  export const FLEXIBLE_WAIT_MS = 20_000;
693
791
  export const FLEXIBLE_WAITERS_MAX = 64;
694
792
  export function flexibleThreadChangeOf(sessions, input) {
695
- if (!FLEXIBLE_AVAILABLE)
696
- return refuse("not-available");
697
793
  if (typeof input.thread !== "string" || !ID.test(input.thread))
698
794
  return refuse("invalid-request");
699
795
  return { ok: true, change: sessions.changes.get(input.thread) ?? 0 };
700
796
  }
701
797
  export function waitFlexibleThreadChange(sessions, input) {
702
- if (!FLEXIBLE_AVAILABLE)
703
- return refuse("not-available");
704
798
  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
799
  return refuse("invalid-request");
706
800
  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));
@@ -0,0 +1,47 @@
1
+ export const V172_SCHEMA = `
2
+ CREATE TABLE IF NOT EXISTS flexible_sign_in (
3
+ person TEXT NOT NULL CHECK (length(person) BETWEEN 1 AND 200),
4
+ account_generation INTEGER NOT NULL CHECK (account_generation >= 0),
5
+ generation TEXT NOT NULL CHECK (length(generation) = 32 AND generation NOT GLOB '*[^0-9a-f]*'),
6
+ kind TEXT NOT NULL CHECK (kind IN ('setup-token')),
7
+ state TEXT NOT NULL CHECK (state IN ('staged', 'active', 'retiring')),
8
+ save_op TEXT CHECK (save_op IS NULL OR (length(save_op) = 32 AND save_op NOT GLOB '*[^0-9a-f]*')),
9
+ proof TEXT NOT NULL CHECK (proof IN ('password-now', 'sso-now', 'restored')),
10
+ staged_at TEXT NOT NULL,
11
+ retire_after TEXT,
12
+ activated_at TEXT,
13
+ retired_at TEXT,
14
+ check_outcome TEXT NOT NULL DEFAULT 'not-checked' CHECK (check_outcome IN ('not-checked', 'accepted', 'refused', 'inconclusive', 'unreachable')),
15
+ check_status INTEGER CHECK (check_status IS NULL OR check_status BETWEEN 100 AND 599),
16
+ checked_at TEXT,
17
+ PRIMARY KEY (person, generation),
18
+ CHECK ((state = 'staged') = (save_op IS NOT NULL)),
19
+ CHECK (state <> 'staged' OR retire_after IS NOT NULL),
20
+ CHECK (state <> 'active' OR activated_at IS NOT NULL),
21
+ CHECK (state <> 'retiring' OR retired_at IS NOT NULL)
22
+ );
23
+ CREATE UNIQUE INDEX IF NOT EXISTS flexible_sign_in_one_active ON flexible_sign_in (person) WHERE state = 'active';
24
+ CREATE TABLE IF NOT EXISTS flexible_sign_in_epoch (
25
+ person TEXT PRIMARY KEY CHECK (length(person) BETWEEN 1 AND 200),
26
+ epoch INTEGER NOT NULL CHECK (epoch >= 1)
27
+ );
28
+ CREATE INDEX IF NOT EXISTS thread_relay_call_sign_in_refused ON thread_relay_call (sign_in_person, sign_in_generation) WHERE sign_in_refused = 1;
29
+ `;
30
+ export const V172_ADDED_COLUMNS = Object.freeze({
31
+ thread_relay_call: {
32
+ sign_in_person: { definition: "TEXT CHECK (sign_in_person IS NULL OR length(sign_in_person) BETWEEN 1 AND 200)", saved: "NULL" },
33
+ sign_in_generation: { definition: "TEXT CHECK (sign_in_generation IS NULL OR (length(sign_in_generation) = 32 AND sign_in_generation NOT GLOB '*[^0-9a-f]*'))", saved: "NULL" },
34
+ sign_in_refused: { definition: "INTEGER CHECK (sign_in_refused IS NULL OR (sign_in_refused = 1 AND sign_in_person IS NOT NULL AND sign_in_generation IS NOT NULL AND status = 'upstream-error'))", saved: "NULL" },
35
+ sign_in_epoch: { definition: "INTEGER CHECK (sign_in_epoch IS NULL OR sign_in_epoch >= 0)", saved: "NULL" },
36
+ },
37
+ thread_relay_pending: {
38
+ sign_in_person: { definition: "TEXT CHECK (sign_in_person IS NULL OR length(sign_in_person) BETWEEN 1 AND 200)", saved: "NULL" },
39
+ sign_in_generation: { definition: "TEXT CHECK (sign_in_generation IS NULL OR (length(sign_in_generation) = 32 AND sign_in_generation NOT GLOB '*[^0-9a-f]*'))", saved: "NULL" },
40
+ sign_in_epoch: { definition: "INTEGER CHECK (sign_in_epoch IS NULL OR sign_in_epoch >= 0)", saved: "NULL" },
41
+ },
42
+ });
43
+ export const V172_TABLES = Object.freeze(["flexible_sign_in", "flexible_sign_in_epoch"]);
44
+ export const V172_STEPS = Object.freeze(["flexible-sign-in-columns", "flexible-sign-in"]);
45
+ export const V172_OBJECTS = Object.freeze([
46
+ ["table", "flexible_sign_in"], ["index", "flexible_sign_in_one_active"], ["table", "flexible_sign_in_epoch"], ["index", "thread_relay_call_sign_in_refused"],
47
+ ]);
@@ -0,0 +1,4 @@
1
+ import { createHash } from "node:crypto";
2
+ export function signInSlot(person) {
3
+ return createHash("sha256").update(`toolroll:flexible-sign-in:${person}`, "utf8").digest("hex").slice(0, 16);
4
+ }