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
@@ -0,0 +1,470 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { request as httpRequest } from "node:http";
3
+ import { request as httpsRequest } from "node:https";
4
+ import { flexibleAvailable } from "./flexible-available.js";
5
+ import { CLAUDE_EXACT } from "./model-catalog.js";
6
+ import { FLEXIBLE_RELAY_UPSTREAMS } from "./flexible-relay-upstreams.js";
7
+ import { credentialProof, freshFacts, proveCredential } from "./scope.js";
8
+ import { createSignInSecret, readSignInSecret, removeSignInSecret, withSignInLockAsync } from "./tool-secret-store.js";
9
+ import { relayCancel } from "./flexible-relay-cancel.js";
10
+ export const SIGN_IN_ACTION = "claude sign-in for threads";
11
+ export const SIGN_IN_STAGE_MS = 15 * 60_000;
12
+ const SETUP_TOKEN = FLEXIBLE_RELAY_UPSTREAMS.claude.auth["setup-token"];
13
+ const API_KEY = FLEXIBLE_RELAY_UPSTREAMS.claude.auth["api-key"];
14
+ const GENERATION = /^[0-9a-f]{32}$/;
15
+ const PERSON = (value) => typeof value === "string" && value.length >= 1 && value.length <= 200;
16
+ const WORDS = Object.freeze({
17
+ "not-available": "Interactive agent threads are off: Settings → General, or `toolroll config set flexible on`. Nothing was saved.",
18
+ "invalid-request": "That isn't a sign-in Toolroll can save. Nothing was saved.",
19
+ "not-proved": "Saving your Claude sign-in needs your Toolroll password, typed now. Nothing was saved.",
20
+ shape: "That doesn't look like a token from `claude setup-token`. Run it again and paste the whole token it prints. Nothing was saved.",
21
+ "api-key": "That's an API key. Threads need your `claude setup-token` sign-in. Nothing was saved.",
22
+ "save-ended": "This save didn't finish: your sign-in was removed, your account changed, or the save took too long. Nothing was saved; try again.",
23
+ "not-saved": "Toolroll couldn't keep your sign-in in its folder for secrets. Nothing was saved; your earlier sign-in, if any, still works.",
24
+ "check-refused": "Claude didn't accept this sign-in. Run `claude setup-token` again and paste the new token. Nothing was saved; your earlier sign-in, if any, still works.",
25
+ });
26
+ const refuse = (reason) => ({ ok: false, reason, message: WORDS[reason] });
27
+ export function setupTokenFromPaste(paste) {
28
+ if (typeof paste !== "string")
29
+ return refuse("invalid-request");
30
+ const token = paste.replace(/\s+/g, "");
31
+ if (SETUP_TOKEN.shape.test(token))
32
+ return { ok: true, token };
33
+ if (API_KEY.shape.test(token) || /^sk-ant-api/.test(token))
34
+ return refuse("api-key");
35
+ return refuse("shape");
36
+ }
37
+ export const looksLikeClaudeCredential = (text) => /sk-ant-[A-Za-z0-9_-]{6,}/.test(text.replace(/\s+/g, ""));
38
+ const readRow = (row) => row === undefined ? null : {
39
+ person: String(row["person"]), accountGeneration: Number(row["account_generation"]), generation: String(row["generation"]), kind: "setup-token",
40
+ state: String(row["state"]), saveOp: row["save_op"] == null ? null : String(row["save_op"]), proof: String(row["proof"]),
41
+ stagedAt: String(row["staged_at"]), retireAfter: row["retire_after"] == null ? null : String(row["retire_after"]), activatedAt: row["activated_at"] == null ? null : String(row["activated_at"]),
42
+ retiredAt: row["retired_at"] == null ? null : String(row["retired_at"]), checkOutcome: String(row["check_outcome"]), checkStatus: row["check_status"] == null ? null : Number(row["check_status"]), checkedAt: row["checked_at"] == null ? null : String(row["checked_at"])
43
+ };
44
+ const rowOf = (store, person, generation) => readRow(store.handle.prepare("SELECT * FROM flexible_sign_in WHERE person = ? AND generation = ?").get(person, generation));
45
+ const activeRowOf = (store, person) => readRow(store.handle.prepare("SELECT * FROM flexible_sign_in WHERE person = ? AND state = 'active'").get(person));
46
+ const refusedOnce = (store, person, generation) => store.handle.prepare("SELECT 1 AS refused FROM thread_relay_call WHERE sign_in_person = ? AND sign_in_generation = ? AND sign_in_refused = 1 LIMIT 1").get(person, generation) !== undefined;
47
+ function standingAccount(store, person, generation) {
48
+ const account = store.accountOf(person);
49
+ return account !== null && account.revokedAt === null && account.role === "approver" && account.generation === generation;
50
+ }
51
+ const CAPABILITY = /^[0-9a-f]{64}$/;
52
+ const opDigest = (op) => createHash("sha256").update(`toolroll:flexible-sign-in:save:${op}`, "utf8").digest("hex").slice(0, 32);
53
+ const mintedBy = new WeakMap();
54
+ export function stageFlexibleSignIn(store, input) {
55
+ if (!flexibleAvailable(store))
56
+ return refuse("not-available");
57
+ if (!PERSON(input?.person) || typeof input.password !== "string" || !(input.now instanceof Date))
58
+ return refuse("invalid-request");
59
+ return store.transact(() => {
60
+ if (!flexibleAvailable(store))
61
+ return refuse("not-available");
62
+ const proved = proveCredential(store, input.person, input.password);
63
+ if (!proved.ok || !credentialProof(proved.method))
64
+ return refuse("not-proved");
65
+ const account = store.accountOf(input.person);
66
+ if (account === null || !standingAccount(store, input.person, account.generation))
67
+ return refuse("not-proved");
68
+ const generation = randomBytes(16).toString("hex"), op = randomBytes(32).toString("hex");
69
+ const proof = proved.method;
70
+ store.handle.prepare(`INSERT INTO flexible_sign_in (person, account_generation, generation, kind, state, save_op, proof, staged_at, retire_after)
71
+ VALUES (?, ?, ?, 'setup-token', 'staged', ?, ?, ?, ?)`).run(input.person, account.generation, generation, opDigest(op), proof, input.now.toISOString(), new Date(input.now.getTime() + SIGN_IN_STAGE_MS).toISOString());
72
+ const facts = freshFacts.getStore();
73
+ if (proof === "sso-now" && facts != null) {
74
+ const set = mintedBy.get(facts) ?? new Set();
75
+ set.add(opDigest(op));
76
+ mintedBy.set(facts, set);
77
+ }
78
+ return { ok: true, staged: { person: input.person, generation, op, accountGeneration: account.generation, proof } };
79
+ });
80
+ }
81
+ export function placeFlexibleSignIn(state, staged, token) {
82
+ const secret = { person: staged.person, generation: staged.generation, kind: "setup-token", value: token };
83
+ return createSignInSecret(state, secret);
84
+ }
85
+ export function activateFlexibleSignIn(store, input) {
86
+ const staged = input?.staged;
87
+ if (staged === undefined || !PERSON(staged.person) || typeof staged.generation !== "string" || !GENERATION.test(staged.generation) || typeof staged.op !== "string" || !CAPABILITY.test(staged.op)
88
+ || typeof input.password !== "string" || !(input.now instanceof Date))
89
+ return refuse("invalid-request");
90
+ return store.transact(() => {
91
+ const now = input.now.toISOString();
92
+ const row = rowOf(store, staged.person, staged.generation);
93
+ const digest = opDigest(staged.op);
94
+ if (row === null || row.state !== "staged" || row.saveOp !== digest || row.retireAfter === null || row.retireAfter <= now || row.accountGeneration !== staged.accountGeneration)
95
+ return refuse("save-ended");
96
+ if (!standingAccount(store, row.person, row.accountGeneration))
97
+ return refuse("save-ended");
98
+ if (row.proof === "password-now") {
99
+ const again = proveCredential(store, row.person, input.password);
100
+ if (!again.ok || again.method !== "password-now")
101
+ return refuse("not-proved");
102
+ }
103
+ else if (row.proof === "sso-now") {
104
+ const facts = freshFacts.getStore();
105
+ if (input.password !== "" || facts == null || facts.actor !== row.person || mintedBy.get(facts)?.has(digest) !== true || !facts.live())
106
+ return refuse("not-proved");
107
+ }
108
+ else
109
+ return refuse("not-proved");
110
+ const replaced = Number(store.handle.prepare("UPDATE flexible_sign_in SET state = 'retiring', retired_at = ? WHERE person = ? AND state = 'active'").run(now, row.person).changes) > 0;
111
+ const consumed = Number(store.handle.prepare(`UPDATE flexible_sign_in SET state = 'active', save_op = NULL, retire_after = NULL, activated_at = ?
112
+ WHERE person = ? AND generation = ? AND state = 'staged' AND save_op = ? AND account_generation = ?`).run(now, row.person, row.generation, digest, row.accountGeneration).changes);
113
+ if (consumed !== 1)
114
+ throw new Error("a sign-in's staged save changed during its own activation");
115
+ const check = input.check ?? null;
116
+ if (check !== null)
117
+ recordCheck(store, row.person, row.generation, check, now);
118
+ store.recordAction({ at: now, actor: row.person, repo: null, taskId: null, runId: null, action: SIGN_IN_ACTION, outcome: replaced ? "replaced" : "saved", source: "policy",
119
+ detail: `setup-token, ${check === null ? "not checked" : checkOutcomeOf(check)}` });
120
+ return { ok: true, replaced };
121
+ });
122
+ }
123
+ function abandonStaged(store, staged, now) {
124
+ try {
125
+ store.handle.prepare("UPDATE flexible_sign_in SET state = 'retiring', save_op = NULL, retire_after = NULL, retired_at = ? WHERE person = ? AND generation = ? AND state = 'staged'")
126
+ .run(now.toISOString(), staged.person, staged.generation);
127
+ }
128
+ catch { }
129
+ }
130
+ export async function saveFlexibleSignIn(store, input) {
131
+ const clock = input.clock ?? (() => new Date());
132
+ const paste = setupTokenFromPaste(input.token);
133
+ if (!paste.ok)
134
+ return paste;
135
+ const staged = stageFlexibleSignIn(store, { person: input.person, password: input.password, now: clock() });
136
+ if (!staged.ok)
137
+ return staged;
138
+ await input.seams?.afterStage?.(staged.staged);
139
+ let saved;
140
+ try {
141
+ saved = await withSignInLockAsync(input.state, input.person, async () => {
142
+ let placed;
143
+ try {
144
+ placed = placeFlexibleSignIn(input.state, staged.staged, paste.token);
145
+ }
146
+ catch {
147
+ placed = "exists";
148
+ }
149
+ if (placed !== "ok") {
150
+ abandonStaged(store, staged.staged, clock());
151
+ return refuse("not-saved");
152
+ }
153
+ await input.seams?.afterPlace?.(staged.staged);
154
+ const check = input.check === true ? await checkSignInToken(paste.token) : null;
155
+ if (check !== null && check.outcome === "refused") {
156
+ abandonStaged(store, staged.staged, clock());
157
+ return refuse("check-refused");
158
+ }
159
+ let active;
160
+ try {
161
+ active = activateFlexibleSignIn(store, { staged: staged.staged, password: input.password, now: clock(), check });
162
+ }
163
+ catch {
164
+ active = refuse("save-ended");
165
+ }
166
+ if (!active.ok) {
167
+ abandonStaged(store, staged.staged, clock());
168
+ return active;
169
+ }
170
+ return { ok: true, replaced: active.replaced, generation: staged.staged.generation, check };
171
+ });
172
+ }
173
+ catch {
174
+ abandonStaged(store, staged.staged, clock());
175
+ saved = refuse("not-saved");
176
+ }
177
+ try {
178
+ await tidyFlexibleSignIns(store, input.state, { now: clock(), person: input.person });
179
+ }
180
+ catch { }
181
+ return saved;
182
+ }
183
+ export function removeFlexibleSignIn(store, input) {
184
+ return store.transact(() => {
185
+ const at = input.now.toISOString();
186
+ const removed = Number(store.handle.prepare("UPDATE flexible_sign_in SET state = 'retiring', save_op = NULL, retire_after = NULL, retired_at = ? WHERE person = ? AND state IN ('staged', 'active')")
187
+ .run(at, input.person).changes) > 0;
188
+ store.recordAction({ at, actor: input.by, repo: null, taskId: null, runId: null, action: SIGN_IN_ACTION, outcome: removed ? "removed" : "none to remove", source: "policy",
189
+ detail: input.by === input.person ? null : `${input.person}'s` });
190
+ raiseSignInEpoch(store, input.person);
191
+ if (removed)
192
+ relayCancel({ person: input.person });
193
+ return { removed };
194
+ });
195
+ }
196
+ export function resetFlexibleSignInsForRestore(store, input) {
197
+ const at = input.now.toISOString();
198
+ const reset = Number(store.handle.prepare("UPDATE flexible_sign_in SET state = 'retiring', save_op = NULL, retire_after = NULL, retired_at = ? WHERE state IN ('staged', 'active')").run(at).changes);
199
+ for (const row of store.handle.prepare("SELECT DISTINCT person FROM flexible_sign_in UNION SELECT person FROM flexible_sign_in_epoch").all())
200
+ raiseSignInEpoch(store, String(row["person"]));
201
+ for (const one of input.carried)
202
+ if (PERSON(one.person))
203
+ raiseSignInEpoch(store, one.person);
204
+ for (const one of input.carried) {
205
+ if (!PERSON(one.person) || !GENERATION.test(one.generation) || !Number.isSafeInteger(one.accountGeneration) || one.accountGeneration < 0)
206
+ continue;
207
+ store.handle.prepare(`INSERT INTO flexible_sign_in (person, account_generation, generation, kind, state, save_op, proof, staged_at, retired_at)
208
+ VALUES (?, ?, ?, 'setup-token', 'retiring', NULL, 'restored', ?, ?) ON CONFLICT (person, generation) DO NOTHING`).run(one.person, one.accountGeneration, one.generation, at, at);
209
+ }
210
+ store.recordAction({ at, actor: "command line", repo: null, taskId: null, runId: null, action: SIGN_IN_ACTION, outcome: "reset by restore", source: "policy",
211
+ detail: "Everyone's Claude sign-in for threads needs saving again." });
212
+ return { reset };
213
+ }
214
+ export async function tidyFlexibleSignIns(store, state, input) {
215
+ const at = input.now.toISOString();
216
+ store.transact(() => {
217
+ store.handle.prepare("UPDATE flexible_sign_in SET state = 'retiring', save_op = NULL, retire_after = NULL, retired_at = ? WHERE state = 'staged' AND retire_after <= ?").run(at, at);
218
+ for (const row of store.handle.prepare("SELECT person, generation, account_generation FROM flexible_sign_in WHERE state IN ('staged', 'active')").all()) {
219
+ if (standingAccount(store, String(row["person"]), Number(row["account_generation"])))
220
+ continue;
221
+ store.handle.prepare("UPDATE flexible_sign_in SET state = 'retiring', save_op = NULL, retire_after = NULL, retired_at = ? WHERE person = ? AND generation = ? AND state IN ('staged', 'active')")
222
+ .run(at, String(row["person"]), String(row["generation"]));
223
+ }
224
+ });
225
+ const people = (input.person === undefined
226
+ ? store.handle.prepare("SELECT DISTINCT person FROM flexible_sign_in WHERE state = 'retiring'").all()
227
+ : store.handle.prepare("SELECT DISTINCT person FROM flexible_sign_in WHERE state = 'retiring' AND person = ?").all(input.person)).map(row => String(row["person"]));
228
+ let deleted = 0, left = 0;
229
+ for (const person of people) {
230
+ try {
231
+ await withSignInLockAsync(state, person, async () => {
232
+ for (const row of store.handle.prepare("SELECT generation FROM flexible_sign_in WHERE person = ? AND state = 'retiring'").all(person)) {
233
+ const generation = String(row["generation"]);
234
+ const again = rowOf(store, person, generation);
235
+ if (again === null || again.state !== "retiring")
236
+ continue;
237
+ try {
238
+ removeSignInSecret(state, person, generation);
239
+ }
240
+ catch {
241
+ left++;
242
+ continue;
243
+ }
244
+ store.transact(() => {
245
+ if (Number(store.handle.prepare("DELETE FROM flexible_sign_in WHERE person = ? AND generation = ? AND state = 'retiring'").run(person, generation).changes) === 1) {
246
+ store.recordAction({ at, actor: "upkeep", repo: null, taskId: null, runId: null, action: SIGN_IN_ACTION, outcome: "retired", source: "policy", detail: `${person}'s` });
247
+ deleted++;
248
+ }
249
+ });
250
+ }
251
+ }, { waitMs: input.waitMs ?? 2_000 });
252
+ }
253
+ catch {
254
+ left++;
255
+ }
256
+ }
257
+ return { deleted, left };
258
+ }
259
+ export function flexibleSignInStatus(store, person) {
260
+ const account = store.accountOf(person);
261
+ const row = activeRowOf(store, person);
262
+ if (row === null || account === null || !standingAccount(store, person, row.accountGeneration))
263
+ return { state: "none" };
264
+ return { state: refusedOnce(store, person, row.generation) ? "refused" : "active", savedAt: row.activatedAt ?? row.stagedAt, checkOutcome: row.checkOutcome,
265
+ checkStatus: row.checkStatus, checkedAt: row.checkedAt, generation: row.generation };
266
+ }
267
+ export function flexibleSignInBilling(store, by) {
268
+ if (!PERSON(by?.name) || !Number.isSafeInteger(by.generation))
269
+ return { ok: false, reason: "no-sign-in" };
270
+ const row = activeRowOf(store, by.name);
271
+ if (row === null || row.accountGeneration !== by.generation || !standingAccount(store, by.name, by.generation))
272
+ return { ok: false, reason: "no-sign-in" };
273
+ if (refusedOnce(store, by.name, row.generation))
274
+ return { ok: false, reason: "sign-in-refused" };
275
+ return { ok: true, billing: FLEXIBLE_RELAY_UPSTREAMS.claude.auth[row.kind].billing };
276
+ }
277
+ export function signInForTurn(store, state, turn) {
278
+ const billing = flexibleSignInBilling(store, { name: turn.owner, generation: turn.ownerGeneration });
279
+ if (!billing.ok)
280
+ return billing;
281
+ const row = activeRowOf(store, turn.owner);
282
+ if (row === null)
283
+ return { ok: false, reason: "no-sign-in" };
284
+ let secret;
285
+ try {
286
+ secret = readSignInSecret(state, row.person, row.generation);
287
+ }
288
+ catch {
289
+ return { ok: false, reason: "no-sign-in" };
290
+ }
291
+ if (secret === null || secret.person !== turn.owner || secret.generation !== row.generation || !SETUP_TOKEN.shape.test(secret.value))
292
+ return { ok: false, reason: "no-sign-in" };
293
+ return { ok: true, signIn: { person: row.person, generation: row.generation, kind: row.kind, value: secret.value } };
294
+ }
295
+ export function signInStandsAt(store, input) {
296
+ const thread = store.handle.prepare("SELECT created_by FROM flexible_thread WHERE id = ?").get(input.thread);
297
+ const turn = store.handle.prepare("SELECT thread, owner, owner_generation, billing, status FROM thread_turn WHERE id = ?").get(input.turn);
298
+ if (thread === undefined || turn === undefined || turn["thread"] !== input.thread || turn["status"] !== "running")
299
+ return "no-sign-in";
300
+ const owner = String(turn["owner"]), ownerGeneration = Number(turn["owner_generation"]);
301
+ if (thread["created_by"] !== owner || owner !== input.person)
302
+ return "no-sign-in";
303
+ const row = rowOf(store, input.person, input.generation);
304
+ if (row === null || row.state !== "active" || row.accountGeneration !== ownerGeneration || !standingAccount(store, input.person, ownerGeneration))
305
+ return "no-sign-in";
306
+ if (FLEXIBLE_RELAY_UPSTREAMS.claude.auth[row.kind].billing !== turn["billing"])
307
+ return "no-sign-in";
308
+ if (refusedOnce(store, input.person, input.generation))
309
+ return "sign-in-refused";
310
+ return null;
311
+ }
312
+ export const signInRefusedBy = (status, errorType) => status === 401 || (status === 403 && errorType === "authentication_error");
313
+ export const signInRefusedWords = (status) => `Toolroll couldn't use your Claude sign-in for threads: Claude answered ${status}. Replace it in Settings → General, or with \`toolroll config set flexible-sign-in\`.`;
314
+ export const SIGN_IN_CHECK_LIMITS = Object.freeze({ connectMs: 5_000, totalMs: 10_000, bodyBytes: 4 * 1024 });
315
+ const CHECK_MODEL = CLAUDE_EXACT.find(one => one.value.startsWith("claude-haiku-"))?.value ?? "claude-haiku-4-5";
316
+ const checkOutcomeOf = (check) => check.outcome === "accepted" ? "token-count check accepted" : `check ${check.outcome}${check.status === null ? "" : ` (HTTP ${check.status})`}`;
317
+ export function statusCheck(status) {
318
+ if (status.state === "none")
319
+ return { outcome: "not-checked" };
320
+ const outcome = status.checkOutcome;
321
+ if (outcome === "accepted")
322
+ return { outcome, status: 200 };
323
+ if ((outcome === "refused" || outcome === "inconclusive") && status.checkStatus !== null)
324
+ return { outcome, status: status.checkStatus };
325
+ if (outcome === "unreachable")
326
+ return { outcome, status: null };
327
+ return { outcome: "not-checked" };
328
+ }
329
+ export function signInCheckWords(check) {
330
+ switch (check.outcome) {
331
+ case "not-checked": return "Not checked.";
332
+ case "accepted": return "Token-count check accepted.";
333
+ case "refused": return `Claude didn't accept this sign-in (HTTP ${check.status}).`;
334
+ case "inconclusive": return check.status >= 300 && check.status < 400 ? "Check inconclusive (redirect refused)." : `Check inconclusive (HTTP ${check.status}).`;
335
+ case "unreachable": return "Couldn't reach Claude to check.";
336
+ }
337
+ }
338
+ export function checkSignInToken(token, limits = SIGN_IN_CHECK_LIMITS) {
339
+ const upstream = FLEXIBLE_RELAY_UPSTREAMS.claude, auth = upstream.auth["setup-token"];
340
+ if (!auth.shape.test(token))
341
+ return Promise.resolve({ outcome: "unreachable", status: null });
342
+ const route = upstream.routes.find(one => one.kind === "count-tokens");
343
+ const target = new URL(route.path, upstream.origin);
344
+ const body = Buffer.from(JSON.stringify({ model: CHECK_MODEL, messages: [{ role: "user", content: "hi" }] }), "utf8");
345
+ return new Promise(resolve => {
346
+ let done = false;
347
+ const finish = (check) => { if (done)
348
+ return; done = true; clearTimeout(total); clearTimeout(connect); try {
349
+ outgoing.destroy();
350
+ }
351
+ catch { } resolve(check); };
352
+ const send = target.protocol === "https:" ? httpsRequest : httpRequest;
353
+ const outgoing = send({ protocol: target.protocol, hostname: target.hostname, port: target.port === "" ? undefined : Number(target.port), method: "POST", path: target.pathname, agent: false,
354
+ ...(target.protocol === "https:" ? { servername: target.hostname } : {}),
355
+ headers: { host: target.host, "content-type": "application/json", "content-length": String(body.length), "accept-encoding": "identity", "anthropic-version": "2023-06-01",
356
+ "anthropic-beta": auth.betas.join(","), [auth.header]: `${auth.prefix}${token}` } });
357
+ const total = setTimeout(() => finish({ outcome: "unreachable", status: null }), limits.totalMs);
358
+ const connect = setTimeout(() => finish({ outcome: "unreachable", status: null }), limits.connectMs);
359
+ outgoing.on("socket", socket => {
360
+ const connected = () => clearTimeout(connect);
361
+ if (!socket.connecting)
362
+ connected();
363
+ else
364
+ socket.once(target.protocol === "https:" ? "secureConnect" : "connect", connected);
365
+ });
366
+ outgoing.on("error", () => finish({ outcome: "unreachable", status: null }));
367
+ outgoing.on("response", (answer) => {
368
+ const status = answer.statusCode ?? 0;
369
+ if (status < 100 || status > 599) {
370
+ finish({ outcome: "inconclusive", status: 502 });
371
+ return;
372
+ }
373
+ if (status >= 300 && status < 400) {
374
+ finish({ outcome: "inconclusive", status });
375
+ return;
376
+ }
377
+ const parts = [];
378
+ let size = 0;
379
+ const decide = () => {
380
+ const text = Buffer.concat(parts).subarray(0, limits.bodyBytes).toString("utf8");
381
+ let parsed = null;
382
+ try {
383
+ parsed = JSON.parse(text);
384
+ }
385
+ catch {
386
+ parsed = null;
387
+ }
388
+ const object = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
389
+ if (status === 200) {
390
+ const tokens = object?.["input_tokens"];
391
+ finish(typeof tokens === "number" && Number.isSafeInteger(tokens) && tokens >= 0 ? { outcome: "accepted", status: 200 } : { outcome: "inconclusive", status: 200 });
392
+ return;
393
+ }
394
+ const error = object?.["error"];
395
+ const type = error !== null && typeof error === "object" ? error["type"] : undefined;
396
+ finish(signInRefusedBy(status, typeof type === "string" ? type : null) ? { outcome: "refused", status } : { outcome: "inconclusive", status });
397
+ };
398
+ answer.on("data", (chunk) => {
399
+ if (size < limits.bodyBytes)
400
+ parts.push(chunk);
401
+ size += chunk.length;
402
+ if (size >= limits.bodyBytes)
403
+ decide();
404
+ });
405
+ answer.on("end", decide);
406
+ answer.on("error", () => finish({ outcome: "unreachable", status: null }));
407
+ });
408
+ outgoing.end(body);
409
+ });
410
+ }
411
+ function recordCheck(store, person, generation, check, at) {
412
+ store.handle.prepare("UPDATE flexible_sign_in SET check_outcome = ?, check_status = ?, checked_at = ? WHERE person = ? AND generation = ?")
413
+ .run(check.outcome, check.status, at, person, generation);
414
+ }
415
+ export async function recheckFlexibleSignIn(store, state, input) {
416
+ const clock = input.clock ?? (() => new Date());
417
+ return withSignInLockAsync(state, input.person, async () => {
418
+ const account = store.accountOf(input.person);
419
+ if (account === null)
420
+ return { ok: false, reason: "no-sign-in" };
421
+ const found = signInForTurn(store, state, { owner: input.person, ownerGeneration: account.generation });
422
+ const row = activeRowOf(store, input.person);
423
+ let value = found.ok ? found.signIn.value : null;
424
+ if (!found.ok && found.reason === "sign-in-refused" && row !== null) {
425
+ try {
426
+ value = readSignInSecret(state, row.person, row.generation)?.value ?? null;
427
+ }
428
+ catch {
429
+ value = null;
430
+ }
431
+ }
432
+ if (value === null || row === null)
433
+ return { ok: false, reason: "no-sign-in" };
434
+ const check = await checkSignInToken(value);
435
+ store.transact(() => {
436
+ if (activeRowOf(store, input.person)?.generation !== row.generation)
437
+ return;
438
+ recordCheck(store, row.person, row.generation, check, clock().toISOString());
439
+ store.recordAction({ at: clock().toISOString(), actor: input.person, repo: null, taskId: null, runId: null, action: SIGN_IN_ACTION, outcome: "checked", source: "policy", detail: checkOutcomeOf(check) });
440
+ });
441
+ return { ok: true, check };
442
+ }, { waitMs: 15_000 });
443
+ }
444
+ export function threadsStatusNote(store, person) {
445
+ if (!flexibleAvailable(store))
446
+ return "Threads are off for now. An instance operator turns them on in Settings → General.";
447
+ const status = flexibleSignInStatus(store, person);
448
+ if (status.state === "none")
449
+ return "Threads use your own Claude sign-in: run `claude setup-token`, then `toolroll config set flexible-sign-in`.";
450
+ if (status.state === "refused")
451
+ return "Claude didn't accept your sign-in for threads. Run `claude setup-token` again and save the new token.";
452
+ return `Threads use the Claude sign-in you saved on ${status.savedAt.slice(0, 10)}. ${signInCheckWords(statusCheck(status))}`;
453
+ }
454
+ export function signInHoldsFor(store, input) {
455
+ const turn = store.handle.prepare("SELECT owner, owner_generation FROM thread_turn WHERE id = ?").get(input.turn);
456
+ if (turn === undefined || turn["owner"] !== input.person)
457
+ return false;
458
+ if (signInEpochOf(store, input.person) !== input.epoch)
459
+ return false;
460
+ const generation = Number(turn["owner_generation"]);
461
+ const row = activeRowOf(store, input.person);
462
+ return row !== null && row.accountGeneration === generation && standingAccount(store, input.person, generation);
463
+ }
464
+ export function signInEpochOf(store, person) {
465
+ const row = store.handle.prepare("SELECT epoch FROM flexible_sign_in_epoch WHERE person = ?").get(person);
466
+ return row === undefined ? 0 : Number(row["epoch"]);
467
+ }
468
+ function raiseSignInEpoch(store, person) {
469
+ store.handle.prepare("INSERT INTO flexible_sign_in_epoch (person, epoch) VALUES (?, 1) ON CONFLICT (person) DO UPDATE SET epoch = epoch + 1").run(person);
470
+ }
@@ -1,8 +1,8 @@
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
- import { flexibleRelayBilling } from "./flexible-relay.js";
5
+ import { flexibleSignInBilling, flexibleSignInStatus } from "./flexible-sign-in.js";
6
6
  import { networkWords } from "./egress.js";
7
7
  import { agentModelName } from "./model-names.js";
8
8
  import { CLAUDE_EXACT } from "./model-catalog.js";
@@ -14,7 +14,8 @@ const WORDS = Object.freeze({
14
14
  "not-flexible": "This project isn't Flexible, so threads can't start in it. Nothing was started.",
15
15
  "terms-unreadable": "This project's Flexible terms can't be read, so they allow nothing. Nothing was started.",
16
16
  "not-a-starter": "These terms don't let you start threads in this project. Nothing was started.",
17
- "no-sign-in": "Toolroll holds no Claude sign-in for Flexible threads yet, so no thread can start. Nothing was started.",
17
+ "no-sign-in": "Threads use your own Claude sign-in, and you haven't saved one. Run `claude setup-token`, then `toolroll config set flexible-sign-in`. Nothing was started.",
18
+ "sign-in-refused": "Claude didn't accept your sign-in for threads. Run `claude setup-token` again and save the new token with `toolroll config set flexible-sign-in`. Nothing was started.",
18
19
  });
19
20
  const refuse = (reason) => ({ ok: false, reason, message: WORDS[reason] });
20
21
  const money = (micro) => `$${(micro / 1_000_000).toFixed(2)}`;
@@ -23,7 +24,7 @@ const lowerFirst = (text) => text.charAt(0).toLowerCase() + text.slice(1);
23
24
  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
25
  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
26
  export function flexibleStartCard(store, input) {
26
- if (!FLEXIBLE_AVAILABLE)
27
+ if (!flexibleAvailable(store))
27
28
  return refuse("not-available");
28
29
  const model = input.model === null || input.model === "" ? FLEXIBLE_DEFAULT_MODEL : input.model;
29
30
  if (typeof input.repo !== "string" || input.repo === "" || typeof model !== "string" || !RELAY_MODEL.test(model) || typeof input.message !== "string"
@@ -42,18 +43,20 @@ export function flexibleStartCard(store, input) {
42
43
  const network = flexibleThreadNetwork(store, input.repo);
43
44
  if ("ok" in network)
44
45
  return refuse("not-available");
45
- const credential = flexibleRelayBilling(store);
46
+ const credential = flexibleSignInBilling(store, input.by);
46
47
  if (!credential.ok)
47
- return refuse("no-sign-in");
48
+ return refuse(credential.reason);
48
49
  const billing = credential.billing;
50
+ const signedIn = flexibleSignInStatus(store, input.by.name);
51
+ const savedOn = signedIn.state === "none" ? null : signedIn.savedAt.slice(0, 10);
49
52
  const open = network.mode === "open";
50
53
  const project = store.handle.prepare("SELECT name FROM project WHERE path = ?").get(input.repo)?.["name"];
51
54
  const caps = terms.caps;
52
55
  const decisions = [
53
56
  { label: "Project", words: typeof project === "string" ? project : input.repo, lines: typeof project === "string" ? [input.repo] : [], fields: ["flexible.repo"] },
54
57
  { label: "Level", words: `${FLEXIBLE_LEVEL_WORDS.full}: no permission prompts inside the sandbox`, lines: [FULL_ACCESS_WORDS], fields: ["flexible.level"], risky: true },
55
- { label: "Agent", words: `${agentModelName("claude", model)}, signed in through Toolroll's relay`, lines: ["Your Claude login stays with Toolroll and never enters the agent; each call is checked and counted.",
56
- billing === "subscription" ? "Billed to your Claude plan (Toolroll's setup-token sign-in)." : "Billed per call to Toolroll's Claude API key."], fields: ["flexible.agent", "flexible.billing"] },
58
+ { label: "Agent", words: `${agentModelName("claude", model)}, signed in through Toolroll's relay`, lines: ["Your Claude sign-in stays with Toolroll and never enters the agent; each call is checked and counted.",
59
+ billing === "subscription" ? `Your Claude plan (the sign-in you saved${savedOn === null ? "" : ` on ${savedOn}`}). It powers only threads you start.` : "Billed per call to your own Claude API key. It powers only threads you start."], fields: ["flexible.agent", "flexible.billing"] },
57
60
  { label: "Works in", words: "its own copy of this repository, on its own branch", lines: ["Your repository changes only when you Ship."], fields: ["flexible.repository"] },
58
61
  { label: "Network", words: open ? "open: any website, through the thread's own proxy" : lowerFirst(networkWords(network, "claude").replace(/^Network: /, "")),
59
62
  lines: ["Nothing on this computer is reachable (no local services, keychain, SSH agent or saved sign-ins)."], fields: ["flexible.network"], ...(open ? { risky: true } : {}) },
@@ -78,3 +81,19 @@ export function flexibleStartCard(store, input) {
78
81
  const summary = { revision: null, revisionNotes: [], revisionChanges: [], decisions, why: null, differs: [], warnings, usual: [], usualLabel: "Other settings", usualSummary: "", key };
79
82
  return { ok: true, card: { summary, digest: standing.digest, network: networkDigest, model, level: "full", billing, terms } };
80
83
  }
84
+ export const FLEXIBLE_NEXT_WORDS = Object.freeze({
85
+ "turn-on": "Threads are off. Turn them on in Settings → General, or with `toolroll config set flexible on`. Nothing was started.",
86
+ "ask-operator": "Threads are off. Ask an instance operator to turn them on. Nothing was started.",
87
+ "sign-in": "Threads use your own Claude sign-in. Run `claude setup-token`, then `toolroll config set flexible-sign-in`, or add it in Settings → General. Nothing was started.",
88
+ "sign-in-refused": "Claude didn't accept your sign-in for threads. Run `claude setup-token` again and save the new token with `toolroll config set flexible-sign-in`. Nothing was started.",
89
+ "project-terms": "This project isn't set up for threads yet: turn on its Flexible terms in the project's settings, or with `toolroll project flexible enable`. Nothing was started.",
90
+ });
91
+ export function flexibleReadiness(store, by, repo) {
92
+ if (!flexibleAvailable(store))
93
+ return store.isInstanceOperator(by.name) ? "turn-on" : "ask-operator";
94
+ const signIn = flexibleSignInBilling(store, by);
95
+ if (!signIn.ok)
96
+ return signIn.reason === "no-sign-in" ? "sign-in" : "sign-in-refused";
97
+ const standing = flexibleStanding(store, repo);
98
+ return standing.state === "secure" ? "project-terms" : null;
99
+ }