toolroll 0.9.113 → 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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,30 @@ Each release opens with one line on its theme, then **New**, **Changed**, **Fixe
4
4
  the ones it has). Each item is at most two lines and says where to find it. Notes for maintainers (CI, the release
5
5
  tooling) go on the GitHub release, not here. Entries before 0.9.104 use the older format.
6
6
 
7
+ ## 0.9.114 — 2026-11-17
8
+
9
+ Interactive agent threads (beta) now run on each person's own Claude sign-in.
10
+
11
+ ### New
12
+
13
+ - **Your Claude sign-in for threads.** Settings → General, or `toolroll config set flexible-sign-in`: paste a Claude
14
+ setup-token and confirm with your password. Toolroll checks it with a free token count and says what it found.
15
+ - **Each person uses their own.** A thread always runs on the sign-in of the person who started it, never someone
16
+ else's. Operators can remove a person's sign-in on People but never see or set it.
17
+
18
+ ### Changed
19
+
20
+ - **Turning on threads walks you through it in order:** threads on, then your sign-in, then the project's terms. The
21
+ workbench and the Agents page point to the next step.
22
+ - **When Claude can't be used, the thread says why and stops** (no sign-in, a refused sign-in, threads turned off)
23
+ instead of retrying silently or suggesting `/login`.
24
+
25
+ ### Fixed
26
+
27
+ - **Removing a sign-in, a password reset or a removed account** stops that person's running threads
28
+ at once, mid-answer too.
29
+ - **Saving a sign-in in the terminal always asks for your password,** even when a login is remembered on the computer.
30
+
7
31
  ## 0.9.113 — 2026-11-17
8
32
 
9
33
  The terminal workbench for people coming from herdr: a clear first screen, a build shell that can't take your keys by
package/dist/backup.js CHANGED
@@ -7,6 +7,7 @@ import { BACKUP_EVERY_HOURS, MAX_KEEP } from "./backup-ui.js";
7
7
  import { verifyLedgerChain } from "./ledger-chain.js";
8
8
  import { DEFAULT_LIVENESS_MS } from "./runner.js";
9
9
  import { openStore, readSchemaVersion, SCHEMA_VERSION } from "./store.js";
10
+ import { resetFlexibleSignInsForRestore } from "./flexible-sign-in.js";
10
11
  const BACKUP_NAME = /^(?:toolroll|standing-orders)-(?:([0-9a-f]{8})-)?(\d{4}-\d{2}-\d{2}-\d{6})(?:-(\d+))?\.db$/;
11
12
  export const OLDEST_RESTORABLE = 103;
12
13
  export { BACKUP_EVERY_HOURS, MAX_KEEP };
@@ -326,14 +327,41 @@ export async function restoreDatabase(options) {
326
327
  }
327
328
  report.savedAs = saved;
328
329
  const store = openStore(databaseFile);
330
+ let carried;
329
331
  try {
330
332
  const running = runningNow(store, new Date());
331
333
  if (running.length > 0)
332
334
  return refuse("running", `Toolroll started (${running.join(" and ")}). Stop it first, then restore. The database is unchanged.`);
335
+ carried = store.handle.prepare("SELECT person, generation, account_generation FROM flexible_sign_in").all()
336
+ .map(row => ({ person: String(row["person"]), generation: String(row["generation"]), accountGeneration: Number(row["account_generation"]) }));
333
337
  }
334
338
  finally {
335
339
  store.close();
336
340
  }
341
+ try {
342
+ const prepared = openStore(staged);
343
+ try {
344
+ prepared.transact(() => { resetFlexibleSignInsForRestore(prepared, { now, carried }); });
345
+ }
346
+ finally {
347
+ prepared.close();
348
+ }
349
+ const folded = connect(staged);
350
+ try {
351
+ folded.exec("PRAGMA wal_checkpoint(TRUNCATE)");
352
+ folded.exec("PRAGMA journal_mode = DELETE");
353
+ }
354
+ finally {
355
+ folded.close();
356
+ }
357
+ for (const suffix of ["-wal", "-shm", "-journal"])
358
+ rmSync(`${staged}${suffix}`, { force: true });
359
+ }
360
+ catch (error) {
361
+ for (const suffix of ["-wal", "-shm", "-journal"])
362
+ rmSync(`${staged}${suffix}`, { force: true });
363
+ return refuse("schema", `That backup doesn't open as a Toolroll database (${firstLine(error)}). The database is unchanged.`);
364
+ }
337
365
  const live = connect(databaseFile);
338
366
  try {
339
367
  live.exec("PRAGMA wal_checkpoint(TRUNCATE)");
@@ -346,6 +374,7 @@ export async function restoreDatabase(options) {
346
374
  rmSync(`${databaseFile}${suffix}`, { force: true });
347
375
  renameSync(staged, databaseFile);
348
376
  keepStaged = true;
377
+ options.afterPublish?.();
349
378
  let restored;
350
379
  try {
351
380
  restored = openStore(databaseFile);
@@ -52,6 +52,9 @@ export const CONSOLE_FORMS = {
52
52
  justMe: formContract("POST /settings/install-mode/solo", ["password"]),
53
53
  taskSizing: formContract("POST /settings/task-sizing", ["password", "enabled", "sizer"]),
54
54
  flexibleSwitch: formContract("POST /settings/flexible", ["password", "enabled"]),
55
+ flexibleSignIn: formContract("POST /settings/flexible-sign-in", ["token", "password"]),
56
+ flexibleSignInCheck: formContract("POST /settings/flexible-sign-in-check", ["password"]),
57
+ flexibleSignInClear: formContract("POST /settings/flexible-sign-in-clear", ["person", "password"]),
55
58
  releaseApproval: formContract("POST /settings/release-approval", ["repo", "action", "password"]),
56
59
  projectFlexible: formContract("POST /settings/project/flexible", ["repo", "action", "max", "digest", "password"]),
57
60
  threadAnswer: formContract("POST /agents/live/thread/<id>/answer", ["request", "card", "decision", "question", "answer"]),
@@ -188,8 +188,8 @@ export async function runEasyStart(mode, args, seams) {
188
188
  const session = {
189
189
  owned: () => ownedNow() !== null,
190
190
  stopped: stoppedOnItsOwn,
191
- openBrowser: async () => {
192
- const opened = await seams.openSignedIn();
191
+ openBrowser: async (page) => {
192
+ const opened = await seams.openSignedIn(page);
193
193
  return opened.ok ? "Opened in your browser." : `The browser couldn't be opened: ${opened.message}.`;
194
194
  },
195
195
  shouldAskBackground: () => ownedNow() !== null && !seams.serviceInstalled() && !seams.backgroundAsked(),
@@ -306,7 +306,7 @@ export function defaultEasyStartSeams(options) {
306
306
  spawnUp: args => spawnOwnedUp(args, { cwd, databaseFile: file }),
307
307
  runUpForeground: async (args) => (await import("./operate.js")).runOperate("up", [...args, "--db", file], options.write, options.operate ?? {}),
308
308
  openBrowser: async (url) => { (await import("./operate.js")).openBrowser(url); },
309
- openSignedIn: () => openLocalSignIn(file, options.build),
309
+ openSignedIn: page => openLocalSignIn(file, options.build, page === undefined ? {} : { then: page }),
310
310
  openTui: async (session) => {
311
311
  const { chooseTuiBinary, runTuiBinary } = await import("./tui-launch.js");
312
312
  const { engineContractDigest } = await import("./contracts/engine-api.js");
@@ -429,9 +429,11 @@ export async function openLocalSignIn(databaseFile, build, seams = {}) {
429
429
  try {
430
430
  const spent = ledgerSpent(store, "local link", null);
431
431
  const expiresAt = Date.now() + (seams.expiresMs ?? (await import("./server/session.js")).SIGN_IN_LINK_MS);
432
- const link = await (seams.request ?? (one => requestLocalLink(databaseFile, one, build)))(store);
433
- if (!link.ok)
434
- return link;
432
+ const asked = await (seams.request ?? (one => requestLocalLink(databaseFile, one, build)))(store);
433
+ if (!asked.ok)
434
+ return asked;
435
+ const { isTuiPage } = await import("./tui-contract.js");
436
+ const link = seams.then !== undefined && isTuiPage(seams.then) ? { ...asked, url: `${asked.url}?then=${seams.then}` } : asked;
435
437
  handed = true;
436
438
  const opened = await openSignInLink(link.url, {
437
439
  parent, spent, expiresAt, onEnd: () => store.close(),
@@ -341,8 +341,11 @@ export function setupOf(id, home = null) {
341
341
  return { install: setup.install, canInstall: setup.installRun !== null, signIn: setup.signIn, canSignIn: setup.signInRun !== null, key: setup.key, check: setup.check, note: setup.note,
342
342
  registry: registry.url, registryUnsure: registry.unsure };
343
343
  }
344
- export function agentsReadOf(detection, view = "full", home = null) {
345
- const agents = (detection?.agents ?? []).map(one => ({ id: one.id, name: one.name, state: one.state, how: one.how, signIn: one.signIn, ready: one.ready, next: one.next, setup: setupOf(one.id, home) }));
344
+ export function agentsReadOf(detection, view = "full", home = null, claudeNote = null) {
345
+ const agents = (detection?.agents ?? []).map(one => {
346
+ const setup = setupOf(one.id, home);
347
+ return { id: one.id, name: one.name, state: one.state, how: one.how, signIn: one.signIn, ready: one.ready, next: one.next, setup: one.id === "claude" && claudeNote !== null ? { ...setup, note: claudeNote } : setup };
348
+ });
346
349
  const first = detection?.firstTask ?? null;
347
350
  const firstTask = first === null ? null : { id: first, name: agents.find(one => one.id === first)?.name ?? first };
348
351
  if (view === "summary") {
@@ -9,33 +9,32 @@ import { FLEXIBLE_UNAVAILABLE } from "./flexible.js";
9
9
  import { issueRelayGrant, revokeRelayGrant } from "./flexible-launch.js";
10
10
  import { onRelayCancel } from "./flexible-relay-cancel.js";
11
11
  import { FLEXIBLE_RELAY_UPSTREAMS } from "./flexible-relay-upstreams.js";
12
- import { chargeFlexibleTurn, flexibleTurn } from "./flexible-turns.js";
13
- import { readHeldSecret } from "./tool-secret-store.js";
12
+ import { chargeFlexibleTurn, flexibleTurn, interruptFlexibleTurnSignIn } from "./flexible-turns.js";
13
+ import { signInEpochOf, signInForTurn, signInHoldsFor, signInRefusedBy, signInRefusedWords, signInStandsAt } from "./flexible-sign-in.js";
14
14
  const START_WORDS = Object.freeze({
15
15
  "not-available": FLEXIBLE_UNAVAILABLE,
16
16
  "invalid-request": "That isn't a thread Toolroll can start a sign-in relay for. Nothing was started.",
17
17
  "thread-unknown": "There's no such thread, or it isn't ready.",
18
18
  "no-state-folder": "Toolroll's state folder can't be found, so its sign-in relay can't start.",
19
- "no-credential": "Toolroll holds no Claude sign-in for Flexible threads yet, so no thread can start. Nothing was started.",
20
19
  });
21
20
  const refuse = (reason) => ({ ok: false, reason, message: START_WORDS[reason] });
22
21
  export const LINUX_SECOND_RELAY_PORT = 1080;
23
22
  export function relayUrlInside(port, platform = process.platform) {
24
23
  return platform === "linux" ? `http://127.0.0.1:${LINUX_SECOND_RELAY_PORT}` : `http://127.0.0.1:${port}`;
25
24
  }
26
- export const FLEXIBLE_RELAY_CREDENTIAL = Object.freeze({ name: "flexible-claude-relay", file: Object.freeze(["flexible", "claude-relay.json"]) });
27
- const CALL_WORDS = Object.freeze({
25
+ export const RELAY_CALL_ANSWERS = Object.freeze({
28
26
  "threads-off": { status: 403, type: "permission_error", message: "Interactive agent threads were turned off in Toolroll, so nothing was sent to the model." },
29
- unsettled: { status: 503, type: "api_error", message: "An earlier model call in this turn couldn't be charged yet, so nothing more is sent until it is." },
30
- "check-failed": { status: 503, type: "api_error", message: "Toolroll couldn't check this call's authority, so nothing was sent." },
27
+ unsettled: { status: 403, type: "permission_error", message: "Toolroll couldn't record an earlier model call in this turn yet, so it sent nothing more. Send your message again in a moment." },
28
+ "check-failed": { status: 403, type: "permission_error", message: "Toolroll couldn't check whether this thread may still use Claude, so nothing was sent. Send your message again; if this keeps happening, restart Toolroll." },
31
29
  "credential-header": { status: 400, type: "invalid_request_error", message: "Toolroll's sign-in relay chooses the credential itself: a call can't carry its own key, sign-in or service override." },
32
30
  header: { status: 400, type: "invalid_request_error", message: "A request header isn't in a form Toolroll's sign-in relay accepts." },
33
31
  beta: { status: 400, type: "invalid_request_error", message: "That anthropic-beta feature isn't one Toolroll's sign-in relay allows." },
34
32
  route: { status: 404, type: "not_found_error", message: "Toolroll's sign-in relay only forwards messages and token counts." },
35
33
  "too-many": { status: 429, type: "rate_limit_error", message: "This thread has too many model calls running at once. Try again when one finishes." },
36
34
  "no-turn": { status: 409, type: "invalid_request_error", message: "This thread has no turn running, so nothing was sent to the model." },
37
- "billing-mismatch": { status: 403, type: "permission_error", message: "This turn was admitted for a different kind of Claude sign-in than the one Toolroll holds, so nothing was sent." },
38
- "no-credential": { status: 503, type: "api_error", message: "Toolroll has no Claude sign-in for Flexible threads yet, so nothing was sent." },
35
+ "billing-mismatch": { status: 403, type: "permission_error", message: "This turn was admitted for a different kind of Claude sign-in than the one saved, so nothing was sent." },
36
+ "no-sign-in": { status: 403, type: "permission_error", message: "The person who started this thread has no Claude sign-in for threads that counts now (none saved, removed, or their account changed), so nothing was sent. Save one in Settings → General, or with `toolroll config set flexible-sign-in`." },
37
+ "sign-in-refused": { status: 403, type: "permission_error", message: "Claude didn't accept this Claude sign-in for threads earlier, so nothing was sent. Save a new one in Settings → General, or with `toolroll config set flexible-sign-in`." },
39
38
  "body-too-large": { status: 413, type: "request_too_large", message: "That request is larger than Toolroll's sign-in relay forwards." },
40
39
  body: { status: 400, type: "invalid_request_error", message: "That request isn't JSON Toolroll's sign-in relay can read." },
41
40
  model: { status: 400, type: "invalid_request_error", message: "That model isn't one this turn may use." },
@@ -45,44 +44,6 @@ const CALL_WORDS = Object.freeze({
45
44
  });
46
45
  const UNAUTHORIZED = "This relay token isn't authorized (it was never issued, its launch ended, or its thread was stopped).";
47
46
  const errorBody = (type, message) => JSON.stringify({ type: "error", error: { type, message } });
48
- function credentialOf(state, upstream) {
49
- let text;
50
- try {
51
- text = readHeldSecret(state, FLEXIBLE_RELAY_CREDENTIAL.name, FLEXIBLE_RELAY_CREDENTIAL.file);
52
- }
53
- catch {
54
- return null;
55
- }
56
- if (text === null)
57
- return null;
58
- try {
59
- const parsed = JSON.parse(text);
60
- const kind = parsed.kind === "setup-token" || parsed.kind === "api-key" ? parsed.kind : null;
61
- if (kind === null || typeof parsed.value !== "string" || !upstream.auth[kind].shape.test(parsed.value))
62
- return null;
63
- return { kind, value: parsed.value };
64
- }
65
- catch {
66
- return null;
67
- }
68
- }
69
- export function flexibleRelayBilling(store) {
70
- const file = store.databaseFile();
71
- let state;
72
- try {
73
- if (file === null || file === "" || file === ":memory:")
74
- return refuse("no-state-folder");
75
- state = dirname(realpathSync(file));
76
- }
77
- catch {
78
- return refuse("no-state-folder");
79
- }
80
- const upstream = FLEXIBLE_RELAY_UPSTREAMS.claude;
81
- const credential = credentialOf(state, upstream);
82
- if (credential === null)
83
- return refuse("no-credential");
84
- return { ok: true, billing: upstream.auth[credential.kind].billing };
85
- }
86
47
  const KEY_SHAPE = /sk-ant-[A-Za-z0-9_-]{6,}/g;
87
48
  const REDACTED = "[redacted]";
88
49
  function redact(text, secrets = []) {
@@ -162,10 +123,11 @@ function grantOf(store, token) {
162
123
  }
163
124
  const grantStillLive = (store, digest) => store.handle.prepare(`SELECT 1 AS ok FROM flexible_relay_grant g JOIN flexible_thread_launch l ON l.id = g.launch AND l.thread = g.thread
164
125
  WHERE g.token_digest = ? AND g.revoked_at IS NULL AND l.state = 'live'`).get(digest) !== undefined;
165
- function authorizedNow(store, digest, turn) {
126
+ function authorizedNow(store, digest, turn, person, epoch) {
166
127
  try {
167
128
  return store.handle.prepare(`SELECT 1 AS ok FROM flexible_relay_grant g JOIN flexible_thread_launch l ON l.id = g.launch AND l.thread = g.thread
168
- JOIN thread_turn t ON t.id = ? AND t.thread = g.thread AND t.status = 'running' WHERE g.token_digest = ? AND g.revoked_at IS NULL AND l.state = 'live'`).get(turn, digest) !== undefined;
129
+ JOIN thread_turn t ON t.id = ? AND t.thread = g.thread AND t.status = 'running' WHERE g.token_digest = ? AND g.revoked_at IS NULL AND l.state = 'live'`).get(turn, digest) !== undefined
130
+ && signInHoldsFor(store, { turn, person, epoch });
169
131
  }
170
132
  catch {
171
133
  return false;
@@ -177,7 +139,8 @@ function currentTurn(store, thread, grant, provider) {
177
139
  if (rows.length !== 1)
178
140
  return null;
179
141
  const turn = flexibleTurn(store, String(rows[0]["id"]));
180
- return turn !== null && turn.status === "running" && turn.provider === provider && turn.holder === grant.holder ? turn : null;
142
+ const starter = store.handle.prepare("SELECT created_by FROM flexible_thread WHERE id = ?").get(thread)?.["created_by"];
143
+ return turn !== null && turn.status === "running" && turn.provider === provider && turn.holder === grant.holder && typeof starter === "string" && turn.owner === starter ? turn : null;
181
144
  }
182
145
  const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
183
146
  const PARSE_LIMIT = 16 * 1024 * 1024;
@@ -455,8 +418,12 @@ export async function startFlexibleRelay(store, input) {
455
418
  }
456
419
  }
457
420
  const refused = record.status === "refused";
458
- store.handle.prepare(`INSERT INTO thread_relay_call (thread, turn, launch, upstream, at, ended_at, route, model, streamed, status, reason, http_status, tokens_in, tokens_out, cache_read, cache_write, cost_microusd, cost_basis, detail)
459
- VALUES (?, ?, ?, 'claude', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(thread, record.turn, grant.launch, record.at, new Date().toISOString(), record.route, record.model !== null && record.model.length <= 200 ? record.model : null, record.streamed ? 1 : 0, record.status, record.reason, record.httpStatus, refused ? 0 : record.usage.input, refused ? 0 : record.usage.output, refused ? 0 : record.usage.cacheRead, refused ? 0 : record.usage.cacheWrite, cost, basis, detail === null ? null : redact(detail, secrets).slice(0, 500));
421
+ const signIn = record.signIn ?? null, signInRefused = signIn !== null && record.signInRefused === true && record.status === "upstream-error";
422
+ store.handle.prepare(`INSERT INTO thread_relay_call (thread, turn, launch, upstream, at, ended_at, route, model, streamed, status, reason, http_status, tokens_in, tokens_out, cache_read, cache_write, cost_microusd, cost_basis, detail,
423
+ sign_in_person, sign_in_generation, sign_in_refused, sign_in_epoch)
424
+ VALUES (?, ?, ?, 'claude', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(thread, record.turn, grant.launch, record.at, new Date().toISOString(), record.route, record.model !== null && record.model.length <= 200 ? record.model : null, record.streamed ? 1 : 0, record.status, record.reason, record.httpStatus, refused ? 0 : record.usage.input, refused ? 0 : record.usage.output, refused ? 0 : record.usage.cacheRead, refused ? 0 : record.usage.cacheWrite, cost, basis, detail === null ? null : redact(detail, secrets).slice(0, 500), signIn?.person ?? null, signIn?.generation ?? null, signInRefused ? 1 : null, signIn?.epoch ?? null);
425
+ if (signInRefused && record.turn !== null && record.httpStatus !== null)
426
+ interruptFlexibleTurnSignIn(store, { turn: record.turn, detail: signInRefusedWords(record.httpStatus) });
460
427
  written = true;
461
428
  });
462
429
  }
@@ -476,14 +443,14 @@ export async function startFlexibleRelay(store, input) {
476
443
  if (!charged.ok)
477
444
  throw new Error(`its reservation couldn't be reconciled: ${charged.reason}`);
478
445
  const now = new Date().toISOString();
479
- store.handle.prepare(`INSERT INTO thread_relay_call (thread, turn, launch, upstream, at, ended_at, route, model, streamed, status, reason, http_status, cost_microusd, cost_basis, detail)
480
- VALUES (?, ?, ?, 'claude', ?, ?, ?, NULL, 0, 'incomplete', NULL, NULL, 0, ?, ?)`).run(thread, turnId, String(row["launch"]), String(row["reserved_at"]), now, free ? "count-tokens" : "messages", charged.basis, free ? "a token count whose record was lost; it costs nothing" : "its charge was never recorded, so it counts as unknown");
446
+ store.handle.prepare(`INSERT INTO thread_relay_call (thread, turn, launch, upstream, at, ended_at, route, model, streamed, status, reason, http_status, cost_microusd, cost_basis, detail, sign_in_person, sign_in_generation, sign_in_epoch)
447
+ VALUES (?, ?, ?, 'claude', ?, ?, ?, NULL, 0, 'incomplete', NULL, NULL, 0, ?, ?, ?, ?, ?)`).run(thread, turnId, String(row["launch"]), String(row["reserved_at"]), now, free ? "count-tokens" : "messages", charged.basis, free ? "a token count whose record was lost; it costs nothing" : "its charge was never recorded, so it counts as unknown", row["sign_in_person"] ?? null, row["sign_in_generation"] ?? null, row["sign_in_epoch"] ?? null);
481
448
  unsettled.delete(id);
482
449
  };
483
450
  const sweep = () => {
484
451
  let rows;
485
452
  try {
486
- rows = store.handle.prepare("SELECT id, turn, launch, relay, route, reserved_at FROM thread_relay_pending WHERE thread = ? ORDER BY id").all(thread);
453
+ rows = store.handle.prepare("SELECT id, turn, launch, relay, route, reserved_at, sign_in_person, sign_in_generation, sign_in_epoch FROM thread_relay_pending WHERE thread = ? ORDER BY id").all(thread);
487
454
  }
488
455
  catch {
489
456
  return;
@@ -523,7 +490,7 @@ export async function startFlexibleRelay(store, input) {
523
490
  const xkey = request.headers["x-api-key"] === undefined ? undefined : String(request.headers["x-api-key"]);
524
491
  if (bearer !== undefined && xkey !== undefined) {
525
492
  request.resume();
526
- reply(400, "invalid_request_error", CALL_WORDS["credential-header"].message);
493
+ reply(400, "invalid_request_error", RELAY_CALL_ANSWERS["credential-header"].message);
527
494
  return;
528
495
  }
529
496
  const tokenHeader = bearer !== undefined ? "authorization" : xkey !== undefined ? "x-api-key" : null;
@@ -545,7 +512,7 @@ export async function startFlexibleRelay(store, input) {
545
512
  let route = null;
546
513
  let model = null, streamed = false, turn = null;
547
514
  const refused = (reason, detail = null, extra = {}) => {
548
- const words = CALL_WORDS[reason];
515
+ const words = RELAY_CALL_ANSWERS[reason];
549
516
  request.resume();
550
517
  reply(words.status, words.type, words.message, extra);
551
518
  settle(authed, { turn: turn?.id ?? null, at, route: route?.kind ?? "other", model, streamed, status: "refused", reason, httpStatus: words.status,
@@ -682,18 +649,21 @@ export async function startFlexibleRelay(store, input) {
682
649
  refused("server-fetch", fetched);
683
650
  return;
684
651
  }
685
- const credential = credentialOf(state, upstream);
686
- if (credential === null) {
687
- refused("no-credential");
652
+ const found = signInForTurn(store, state, turn);
653
+ if (!found.ok) {
654
+ refused(found.reason);
688
655
  return;
689
656
  }
657
+ const credential = found.signIn;
690
658
  const auth = upstream.auth[credential.kind];
691
659
  if (auth.billing !== turn.billing) {
692
660
  refused("billing-mismatch");
693
661
  return;
694
662
  }
695
663
  const secrets = [credential.value];
664
+ const signIn = { person: credential.person, generation: credential.generation };
696
665
  let reservation = null;
666
+ let epoch = -1;
697
667
  let blocked = null;
698
668
  try {
699
669
  store.transact(() => {
@@ -710,7 +680,13 @@ export async function startFlexibleRelay(store, input) {
710
680
  blocked = "no-turn";
711
681
  return;
712
682
  }
713
- for (const row of store.handle.prepare("SELECT id, turn, launch, relay, route, reserved_at FROM thread_relay_pending WHERE thread = ? ORDER BY id").all(thread)) {
683
+ const stands = signInStandsAt(store, { thread, turn: now.id, person: signIn.person, generation: signIn.generation });
684
+ if (stands !== null) {
685
+ blocked = stands;
686
+ return;
687
+ }
688
+ epoch = signInEpochOf(store, signIn.person);
689
+ for (const row of store.handle.prepare("SELECT id, turn, launch, relay, route, reserved_at, sign_in_person, sign_in_generation, sign_in_epoch FROM thread_relay_pending WHERE thread = ? ORDER BY id").all(thread)) {
714
690
  if (ours.has(Number(row["id"])))
715
691
  continue;
716
692
  if (row["relay"] === instance && flexibleTurn(store, String(row["turn"]))?.status === "running") {
@@ -719,8 +695,8 @@ export async function startFlexibleRelay(store, input) {
719
695
  }
720
696
  reconcile(row);
721
697
  }
722
- reservation = Number(store.handle.prepare("INSERT INTO thread_relay_pending (thread, turn, launch, holder, relay, route, reserved_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
723
- .run(thread, turn.id, authed.launch, authed.holder, instance, route.kind, new Date().toISOString()).lastInsertRowid);
698
+ reservation = Number(store.handle.prepare("INSERT INTO thread_relay_pending (thread, turn, launch, holder, relay, route, reserved_at, sign_in_person, sign_in_generation, sign_in_epoch) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
699
+ .run(thread, turn.id, authed.launch, authed.holder, instance, route.kind, new Date().toISOString(), signIn.person, signIn.generation, epoch).lastInsertRowid);
724
700
  });
725
701
  }
726
702
  catch {
@@ -752,9 +728,9 @@ export async function startFlexibleRelay(store, input) {
752
728
  headers[auth.header] = `${auth.prefix}${credential.value}`;
753
729
  const routeKind = route.kind;
754
730
  const turnId = turn.id;
755
- const live = await forward(target, headers, sent, response, routeKind, streamed, upstream, secrets, one => { release(); calls.add(one); }, authed, turnId, result => {
731
+ const live = await forward(target, headers, sent, response, routeKind, streamed, upstream, secrets, one => { release(); calls.add(one); }, authed, turnId, signIn.person, epoch, result => {
756
732
  const record = { turn: turnId, at, route: routeKind, model, streamed: result.streamed, status: result.status, reason: null, httpStatus: result.httpStatus,
757
- usage: result.usage, charge: result.charge, detail: result.detail };
733
+ usage: result.usage, charge: result.charge, detail: result.detail, signIn: { ...signIn, epoch }, signInRefused: result.signInRefused };
758
734
  if (!settle(authed, record, secrets, reserved))
759
735
  unsettled.set(reserved, () => settle(authed, record, secrets, reserved));
760
736
  ours.delete(reserved);
@@ -765,14 +741,14 @@ export async function startFlexibleRelay(store, input) {
765
741
  release();
766
742
  }
767
743
  };
768
- const forward = (target, headers, body, response, route, streamedAsked, upstream, secrets, started, grant, turn, ended) => new Promise(resolve => {
744
+ const forward = (target, headers, body, response, route, streamedAsked, upstream, secrets, started, grant, turn, person, epoch, ended) => new Promise(resolve => {
769
745
  const free = route === "count-tokens";
770
746
  let sent = false, settled = false, streamed = streamedAsked;
771
747
  let meter = null;
772
748
  const send = target.protocol === "https:" ? httpsRequest : httpRequest;
773
749
  const outgoing = send({ protocol: target.protocol, hostname: target.hostname, port: target.port === "" ? undefined : Number(target.port), method: "POST",
774
750
  path: `${target.pathname}${target.search}`, headers, agent: false, timeout: UPSTREAM_IDLE_MS, ...(target.protocol === "https:" ? { servername: target.hostname } : {}) });
775
- const finish = (status, httpStatus, detail, complete, answer = () => { }) => {
751
+ const finish = (status, httpStatus, detail, complete, answer = () => { }, signInRefused = false) => {
776
752
  if (settled)
777
753
  return;
778
754
  settled = true;
@@ -780,7 +756,7 @@ export async function startFlexibleRelay(store, input) {
780
756
  const charge = free || (!sent && !complete) || status === "upstream-error" || status === "redirect-refused" ? { costUsd: 0, incomplete: false }
781
757
  : complete ? { costUsd: null, incomplete: false } : { costUsd: null, incomplete: true };
782
758
  try {
783
- ended({ status, httpStatus, usage, charge, detail, streamed });
759
+ ended({ status, httpStatus, usage, charge, detail, streamed, signInRefused });
784
760
  }
785
761
  finally {
786
762
  try {
@@ -790,7 +766,7 @@ export async function startFlexibleRelay(store, input) {
790
766
  resolve(live);
791
767
  }
792
768
  };
793
- const live = { digest: grant.digest, launch: grant.launch, turn, cut: false, abort: why => {
769
+ const live = { digest: grant.digest, launch: grant.launch, turn, person, epoch, cut: false, abort: why => {
794
770
  live.cut = true;
795
771
  outgoing.destroy();
796
772
  finish("aborted", null, why, false, () => {
@@ -855,6 +831,14 @@ export async function startFlexibleRelay(store, input) {
855
831
  kind = value.error.type;
856
832
  }
857
833
  catch { }
834
+ if (signInRefusedBy(status, kind)) {
835
+ const words = errorBody("permission_error", signInRefusedWords(status));
836
+ finish("upstream-error", status, `Claude didn't accept the sign-in (HTTP ${status})`, false, () => {
837
+ if (!response.headersSent)
838
+ response.writeHead(403, { "content-type": "application/json", "cache-control": "no-store" }).end(words);
839
+ }, true);
840
+ return;
841
+ }
858
842
  finish("upstream-error", status, `the model service said ${kind}`, false, () => { if (!response.headersSent)
859
843
  response.writeHead(status, pass).end(out); });
860
844
  });
@@ -909,7 +893,7 @@ export async function startFlexibleRelay(store, input) {
909
893
  }
910
894
  if (out === "")
911
895
  return;
912
- if (!authorizedNow(store, grant.digest, turn)) {
896
+ if (!authorizedNow(store, grant.digest, turn, person, epoch)) {
913
897
  lapsed();
914
898
  return;
915
899
  }
@@ -924,7 +908,7 @@ export async function startFlexibleRelay(store, input) {
924
908
  events += rest;
925
909
  const out = streamed ? takeEvents(true) ?? "" : sanitizeWhole(held + rest, secrets);
926
910
  const read = meter.finish();
927
- if (!authorizedNow(store, grant.digest, turn)) {
911
+ if (!authorizedNow(store, grant.digest, turn, person, epoch)) {
928
912
  lapsed();
929
913
  return;
930
914
  }
@@ -954,6 +938,8 @@ export async function startFlexibleRelay(store, input) {
954
938
  cut(call, "this thread's agent was stopped");
955
939
  else if (cancel.digest !== undefined && cancel.digest === call.digest)
956
940
  cut(call, "its relay token was revoked");
941
+ else if (cancel.person !== undefined && cancel.person === call.person)
942
+ cut(call, "its Claude sign-in for threads was removed or ended");
957
943
  }
958
944
  if (turnEnded !== undefined)
959
945
  queueMicrotask(sweep);
@@ -969,6 +955,8 @@ export async function startFlexibleRelay(store, input) {
969
955
  why = "this thread's agent was stopped";
970
956
  else if (flexibleTurn(store, call.turn)?.status !== "running")
971
957
  why = "the turn ended";
958
+ else if (!signInHoldsFor(store, { turn: call.turn, person: call.person, epoch: call.epoch }))
959
+ why = "its Claude sign-in for threads ended";
972
960
  }
973
961
  catch {
974
962
  why = "Toolroll couldn't check its authority";
@@ -6,7 +6,8 @@ import { lowerFlexibleThreadLevel, recoverFlexibleLaunchesOf, startFlexibleTurn
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
12
  import { admitFlexibleTurn, finishFlexibleTurn, flexibleTurn, interruptFlexibleThreadTurns, interruptFlexibleTurnsOf, withdrawFlexibleTurn } from "./flexible-turns.js";
12
13
  import { userFrame } from "./live-input.js";
@@ -626,11 +627,13 @@ export async function startFlexibleThread(store, sessions, input) {
626
627
  }
627
628
  if (!flexibleAvailable(store))
628
629
  return refuse("not-available");
629
- const billing = flexibleRelayBilling(store);
630
+ const billing = flexibleSignInBilling(store, input.by);
630
631
  if (!billing.ok)
631
- 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." };
632
635
  if (billing.billing !== input.billing)
633
- 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." };
634
637
  const admitted = admitFlexibleTurn(store, { thread: id, starter: input.by, digest: input.digest, level: "full", freshProof: input.freshProof === true, provider: "claude", model: input.model,
635
638
  billing: input.billing, requestKey, holder: sessions.holder, clock, opening: true });
636
639
  if (!admitted.ok)
@@ -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
+ }