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
package/dist/serve.js CHANGED
@@ -1975,6 +1975,7 @@ export function createDecisionServer(options) {
1975
1975
  get browserKeys() { return browserKeys; },
1976
1976
  get outsideAdmissions() { return outsideAdmissions; },
1977
1977
  get localAgents() { return localAgents; },
1978
+ get heldApprovalNonce() { return heldApprovalNonce; },
1978
1979
  };
1979
1980
  const tasksHandlers = createTasksHandlers(handlerRuntime);
1980
1981
  const pagesHandlers = createPagesHandlers(handlerRuntime, { listFor: tasksHandlers.workListFor, showOrder: tasksHandlers.showOrder });
@@ -2072,6 +2073,14 @@ export function createDecisionServer(options) {
2072
2073
  return null;
2073
2074
  return holdSignInLink({ kind: "local-owner", ...binding, expires: Date.now() + SIGN_IN_LINK_MS });
2074
2075
  }
2076
+ function heldApprovalNonce(name, taskId, digest) {
2077
+ const now = Date.now();
2078
+ for (const [nonce, held] of approvalNonces) {
2079
+ if (held.expiresAt >= now && held.name === name && held.taskId === taskId && held.digest === digest)
2080
+ return nonce;
2081
+ }
2082
+ return mintApprovalNonce(name, taskId, digest);
2083
+ }
2075
2084
  return Object.assign(server, { mintSignInLink, mintLocalLink, keyEpoch, closeCoding });
2076
2085
  }
2077
2086
  export { PAGE_CSS, pinnedTheme, SENSITIVE_INPUT } from "./server/chrome.js";
@@ -3,12 +3,16 @@ import { randomBytes } from "node:crypto";
3
3
  import { boardRunOf } from "../agent-board.js";
4
4
  import { checkEngineResponse, DIFF_CONTEXT_MAX, ENGINE_API_VERSION, ENGINE_RESPONSES, engineContractDigest, linkRedemptionRequestSchema } from "../contracts/engine-api.js";
5
5
  import { CONSOLE_FORMS, readForm } from "../contracts/console-api.js";
6
- import { FLEXIBLE_AVAILABLE } from "../flexible-available.js";
6
+ import { realpathSync } from "node:fs";
7
+ import { dirname } from "node:path";
8
+ import { flexibleAvailable } from "../flexible-available.js";
9
+ import { threadsStatusNote, tidyFlexibleSignIns } from "../flexible-sign-in.js";
7
10
  import { FLEXIBLE_UNAVAILABLE } from "../flexible.js";
8
- import { admitFlexibleThreadOwner, answerFlexibleRequest, closeFlexibleSessions, flexibleThreadChangeOf, flexibleThreadLiveOf, flexibleThreadsOf, FLEXIBLE_WAIT_MS, openFlexibleSessions, recoverFlexibleHolders, startFlexibleThread, tickFlexibleSessions, waitFlexibleThreadChange } from "../flexible-session.js";
11
+ import { admitFlexibleThreadOwner, answerFlexibleRequest, closeFlexibleSessions, flexibleThreadChangeOf, flexibleThreadLiveOf, flexibleThreadsOf, FLEXIBLE_WAIT_MS, flexibleThreadsExist, flexibleWorkOpen, openFlexibleSessions, recoverFlexibleHolders, startFlexibleThread, settleFlexibleStops, tickFlexibleSessions, waitFlexibleThreadChange } from "../flexible-session.js";
9
12
  import { createFlexibleLauncher } from "../flexible-launcher.js";
10
- import { flexibleStartCard } from "../flexible-start.js";
13
+ import { FLEXIBLE_NEXT_WORDS, flexibleReadiness, flexibleStartCard } from "../flexible-start.js";
11
14
  import { summaryLines } from "../approval-summary.js";
15
+ import { termsOfLines } from "../fast-terms.js";
12
16
  import { localActNow } from "../local-owner.js";
13
17
  import { authenticateApprover } from "../scope.js";
14
18
  import { defaultChainOf, installModeNow } from "../install-mode.js";
@@ -72,7 +76,7 @@ export function createEngineHandlers(runtime) {
72
76
  if ([...url.searchParams.keys()].length > 0)
73
77
  return refusal(response, 400, "request");
74
78
  const view = agentInventoryOf(who, store);
75
- return sendChecked(response, 200, "agents", agentsReadOf(runtime.localAgents, view === "full" ? "full" : "summary", view === "full" ? process.env["HOME"] ?? homedir() : null));
79
+ return sendChecked(response, 200, "agents", agentsReadOf(runtime.localAgents, view === "full" ? "full" : "summary", view === "full" ? process.env["HOME"] ?? homedir() : null, threadsStatusNote(store, who.name)));
76
80
  }
77
81
  async function agentsCheck(ctx) {
78
82
  const { who, response } = ctx;
@@ -84,7 +88,7 @@ export function createEngineHandlers(runtime) {
84
88
  await Promise.race([runtime.checkLocalAgents(true), new Promise(done => { timer = setTimeout(done, 8_000); timer.unref?.(); })]).finally(() => clearTimeout(timer));
85
89
  }
86
90
  const view = agentInventoryOf(who, store);
87
- return sendChecked(response, 200, "agents", agentsReadOf(runtime.localAgents, view === "full" ? "full" : "summary", view === "full" ? process.env["HOME"] ?? homedir() : null));
91
+ return sendChecked(response, 200, "agents", agentsReadOf(runtime.localAgents, view === "full" ? "full" : "summary", view === "full" ? process.env["HOME"] ?? homedir() : null, threadsStatusNote(store, who.name)));
88
92
  }
89
93
  async function liveRun(ctx) {
90
94
  const { url, who, request, response } = ctx;
@@ -111,34 +115,40 @@ export function createEngineHandlers(runtime) {
111
115
  };
112
116
  return sendChecked(response, 200, "liveSessionWindow", body);
113
117
  }
114
- const flexible = (() => {
115
- if (!FLEXIBLE_AVAILABLE)
116
- return null;
118
+ let flexible = null;
119
+ let launcher = null;
120
+ const openHost = () => {
121
+ if (flexible !== null)
122
+ return flexible;
117
123
  const opened = openFlexibleSessions(store);
118
124
  if (!opened.ok)
119
125
  return null;
126
+ flexible = opened.sessions;
120
127
  void recoverFlexibleHolders(store, opened.sessions).catch(() => { });
121
- return opened.sessions;
122
- })();
123
- const launcher = (() => {
124
- if (!FLEXIBLE_AVAILABLE || flexible === null)
125
- return null;
126
128
  const made = createFlexibleLauncher(store);
127
- return "prepare" in made ? made : null;
128
- })();
129
+ launcher = "prepare" in made ? made : null;
130
+ return flexible;
131
+ };
132
+ if (flexibleAvailable(store) || flexibleWorkOpen(store))
133
+ openHost();
134
+ const threadsOn = () => flexibleAvailable(store) ? openHost() : null;
135
+ const threadsRead = () => flexible ?? (flexibleAvailable(store) || flexibleThreadsExist(store) ? openHost() : null);
136
+ let stopping = false;
137
+ let tidying = false;
129
138
  const ownedThread = (request, who, sessions, thread) => {
130
139
  if (rereadBrowser(runtime, request, who) === null)
131
140
  return null;
132
141
  const admitted = admitFlexibleThreadOwner(store, sessions, { thread, viewer: { name: who.name }, canAccess: repo => store.accountCanAccess(who.name, repo) });
133
142
  return admitted.ok ? admitted.repo : null;
134
143
  };
135
- const acted = (response, status, outcome, words) => json(response, status, { outcome, words });
144
+ const acted = (response, status, outcome, words, next) => json(response, status, next === undefined ? { outcome, words } : { outcome, words, next });
136
145
  async function liveThread(ctx) {
137
146
  const { url, who, request, response } = ctx;
138
147
  if (who.via !== "cookie")
139
148
  return refusal(response, 403, "session");
140
- if (!FLEXIBLE_AVAILABLE || flexible === null)
141
- return refusal(response, 404, "not-available");
149
+ const flexible = threadsRead();
150
+ if (flexible === null)
151
+ return refusal(response, 404, "thread");
142
152
  const known = url.searchParams.get("known"), wait = url.searchParams.get("wait");
143
153
  const plain = new URL(url.href);
144
154
  plain.searchParams.delete("known");
@@ -174,22 +184,25 @@ export function createEngineHandlers(runtime) {
174
184
  const { url, who, request, response } = ctx;
175
185
  if (who.via !== "cookie")
176
186
  return refusal(response, 403, "session");
177
- if (!FLEXIBLE_AVAILABLE || flexible === null)
178
- return refusal(response, 404, "not-available");
179
187
  if ([...url.searchParams.keys()].length > 0)
180
188
  return refusal(response, 400, "request");
181
189
  if (rereadBrowser(runtime, request, who) === null)
182
190
  return refusal(response, 403, "session");
191
+ const on = flexibleAvailable(store);
192
+ const flexible = threadsRead();
193
+ if (flexible === null)
194
+ return sendChecked(response, 200, "liveThreads", { version: ENGINE_API_VERSION, on, threads: [] });
183
195
  const read = flexibleThreadsOf(store, flexible, { owner: who.name });
184
196
  if (!read.ok)
185
- return refusal(response, 404, "not-available");
186
- const body = { version: ENGINE_API_VERSION, threads: read.threads.filter(one => store.accountCanAccess(who.name, one.repo))
197
+ return refusal(response, 404, "thread");
198
+ const body = { version: ENGINE_API_VERSION, on, threads: read.threads.filter(one => store.accountCanAccess(who.name, one.repo))
187
199
  .map(one => ({ id: one.id, title: one.title, project: one.project, level: one.level, live: one.live, waiting: one.waiting, costUsd: one.turn?.costUsd ?? null })) };
188
200
  return sendChecked(response, 200, "liveThreads", body);
189
201
  }
190
202
  async function threadAnswer(ctx) {
191
203
  const { url, who, request, response, posted } = ctx;
192
- if (!FLEXIBLE_AVAILABLE || flexible === null)
204
+ const flexible = threadsOn();
205
+ if (flexible === null)
193
206
  return acted(response, 404, "refused", FLEXIBLE_UNAVAILABLE);
194
207
  if (who.via !== "cookie")
195
208
  return acted(response, 403, "refused", "Only a person signed in here can answer an agent.");
@@ -219,17 +232,24 @@ export function createEngineHandlers(runtime) {
219
232
  }
220
233
  async function threadStart(ctx) {
221
234
  const { who, request, response, posted } = ctx;
222
- if (!FLEXIBLE_AVAILABLE || flexible === null)
223
- return acted(response, 404, "refused", FLEXIBLE_UNAVAILABLE);
235
+ const flexible = threadsOn();
236
+ if (flexible === null)
237
+ return acted(response, 404, "refused", FLEXIBLE_UNAVAILABLE, store.isInstanceOperator(who.name) ? "turn-on" : "ask-operator");
224
238
  if (who.via !== "cookie" || rereadBrowser(runtime, request, who) === null)
225
239
  return acted(response, 403, "refused", "Only a person signed in here can start a thread.");
226
240
  if (launcher === null)
227
241
  return acted(response, 409, "refused", "This console can't give a thread its network, so no thread was started.");
228
242
  const body = readForm(posted, CONSOLE_FORMS.threadStart);
243
+ const agent = body.get("agent");
244
+ if (agent !== null && agent !== "claude")
245
+ return acted(response, 409, "refused", FLEXIBLE_CLAUDE_ONLY);
229
246
  const repo = body.get("repo") ?? "", message = body.get("message") ?? "";
230
247
  if (!store.accountCanAccess(who.name, repo))
231
248
  return acted(response, 403, "refused", "That project is outside your access.");
232
249
  const by = { name: who.name, generation: who.session.generation };
250
+ const next = flexibleReadiness(store, by, repo);
251
+ if (next !== null)
252
+ return acted(response, 409, "refused", FLEXIBLE_NEXT_WORDS[next], next);
233
253
  const made = flexibleStartCard(store, { repo, by, model: body.get("model"), message });
234
254
  if (!made.ok)
235
255
  return acted(response, 409, "refused", made.message);
@@ -266,6 +286,30 @@ export function createEngineHandlers(runtime) {
266
286
  return refusal(response, 404, "task");
267
287
  return sendChecked(response, 200, "stepCards", stepCardsOf({ store, family, now: clock(), access: runtime.workAccess(), evidenceRoot, viewer: who.name }));
268
288
  }
289
+ async function taskApproval(ctx) {
290
+ const { url, response, who, request } = ctx;
291
+ if (who.via !== "cookie")
292
+ return refusal(response, 403, "session");
293
+ if (!runtime.browserKeys.terminalKeyed(who, request))
294
+ return refusal(response, 403, "key");
295
+ if ([...url.searchParams.keys()].length > 0)
296
+ return refusal(response, 400, "request");
297
+ const family = familyAt(url, "approval");
298
+ if (family === null)
299
+ return refusal(response, 404, "task");
300
+ const taskId = family.current.id;
301
+ const none = (problem) => sendChecked(response, 200, "approvalCard", { version: ENGINE_API_VERSION, task: taskId, key: null, digest: null, nonce: null, terms: [], problem });
302
+ const waits = (view) => view.nonce !== "" && view.approvalDigest != null && view.approvalSummary != null;
303
+ const view = runtime.taskViewData(taskId, who, null, { mintNonce: false });
304
+ if (view === null)
305
+ return refusal(response, 404, "task");
306
+ if (!waits(view))
307
+ return none(NOTHING_TO_APPROVE);
308
+ if (view.approvalLocal?.eligible !== true)
309
+ return none(`${view.approvalLocal?.eligible === false ? `${view.approvalLocal.message} ` : "This approval needs your password. "}${APPROVE_IN_BROWSER}`);
310
+ return sendChecked(response, 200, "approvalCard", { version: ENGINE_API_VERSION, task: taskId, key: view.approvalSummary.key, digest: view.approvalDigest,
311
+ nonce: runtime.heldApprovalNonce(who.name, taskId, view.approvalDigest), terms: approvalTermsOf(view.approvalSummary, view.planContract ?? null, view.revision ?? null), problem: null });
312
+ }
269
313
  async function taskDiff(ctx) {
270
314
  const { url, response } = ctx;
271
315
  const params = url.searchParams, runParam = params.get("run"), fileParam = params.get("file"), fromParam = params.get("from"), countParam = params.get("count");
@@ -334,29 +378,47 @@ export function createEngineHandlers(runtime) {
334
378
  return sendChecked(response, 200, "linkRedemption", body);
335
379
  }
336
380
  return {
337
- upkeep: () => { if (flexible !== null) {
381
+ upkeep: () => {
382
+ if (!tidying) {
383
+ tidying = true;
384
+ void (async () => {
385
+ const file = store.databaseFile();
386
+ if (file === null || file === "" || file === ":memory:")
387
+ return;
388
+ await tidyFlexibleSignIns(store, dirname(realpathSync(file)), { now: new Date() });
389
+ })().catch(() => { }).finally(() => { tidying = false; });
390
+ }
391
+ const host = flexible;
392
+ if (host === null)
393
+ return;
338
394
  try {
339
- tickFlexibleSessions(store, flexible);
395
+ tickFlexibleSessions(store, host);
340
396
  }
341
397
  catch { }
342
- } },
398
+ if (stopping)
399
+ return;
400
+ stopping = true;
401
+ void settleFlexibleStops(store, host).catch(() => { }).finally(() => { stopping = false; });
402
+ },
343
403
  close: async () => {
404
+ const host = flexible, made = launcher;
344
405
  try {
345
- if (flexible !== null)
346
- await closeFlexibleSessions(store, flexible);
406
+ if (host !== null)
407
+ await closeFlexibleSessions(store, host);
347
408
  }
348
409
  finally {
349
- await launcher?.close();
410
+ await made?.close();
350
411
  }
351
412
  },
352
413
  registrations: [
353
414
  ...handlersOf("pages", { "engine.hello": hello, "engine.agents": agents, "engine.agents-check": agentsCheck, "agents.live.run": liveRun, "agents.live.thread": liveThread, "agents.live.threads": liveThreads,
354
415
  "agents.live.thread.answer": threadAnswer, "agents.live.thread.start": threadStart }),
355
- ...handlersOf("tasks", { "task.steps": taskSteps, "task.diff": taskDiff }),
416
+ ...handlersOf("tasks", { "task.steps": taskSteps, "task.approval": taskApproval, "task.diff": taskDiff }),
356
417
  ...handlersOf("people", {}, { "edge.login-link-json": redeemLink }),
357
418
  ],
358
419
  };
359
420
  }
421
+ export const FLEXIBLE_CLAUDE_ONLY = "Interactive agent threads run Claude Code only for now. Codex threads come later. Nothing was started.";
360
422
  const START_PROOFS = new Set(["password-now", "sso-now", "fresh-password", "fresh-sso", "session", "local-owner"]);
361
423
  const FRESH_PROOFS = new Set(["password-now", "sso-now", "fresh-password", "fresh-sso", "local-owner"]);
362
424
  function bodyOf(request, cap) {
@@ -376,3 +438,21 @@ function bodyOf(request, cap) {
376
438
  request.on("error", () => resolve(null));
377
439
  });
378
440
  }
441
+ export const NOTHING_TO_APPROVE = "Nothing on this task is waiting for your approval.";
442
+ export const APPROVE_IN_BROWSER = "Press w to open it in your browser.";
443
+ export function approvalTermsOf(summary, contract, revision) {
444
+ const terms = termsOfLines(summaryLines(summary));
445
+ if (contract !== null && "problem" in contract)
446
+ terms.push({ label: "Plan record", words: contract.problem });
447
+ else if (contract !== null && (contract.filed || contract.revision === true) && contract.changes.length > 0) {
448
+ const count = `${contract.changes.length} change${contract.changes.length === 1 ? "" : "s"}`;
449
+ terms.push({ label: "Plan changes", words: [contract.revision === true ? `The plan makes ${count} from your notes:` : `The plan makes ${count} to what you filed:`,
450
+ ...contract.changeWords, ...(contract.amendment === null ? [] : [`Why: ${contract.amendment}`])].join("\n") });
451
+ }
452
+ if (revision !== null && "problem" in revision)
453
+ terms.push({ label: "Sent back", words: revision.problem });
454
+ else if (revision !== null && revision.comments.length > 0) {
455
+ terms.push({ label: "Sent back", words: revision.comments.map(one => `${one.path === null ? "" : `${one.path}${one.line === null ? "" : `:${one.line}`} — `}${one.note} (${one.author})`).join("\n") });
456
+ }
457
+ return terms;
458
+ }
@@ -83,6 +83,12 @@ export function createBrowserKeys(deps) {
83
83
  return null;
84
84
  },
85
85
  stale,
86
+ terminalKeyed(who, request) {
87
+ if (!deps.enabled || who.via !== "cookie" || !terminalSession(who.session) || stale(who) !== null)
88
+ return false;
89
+ const presented = presentedKey(request, null);
90
+ return presented !== null && keyMatches(presented, who.session.keyHash);
91
+ },
86
92
  issue(session, request) {
87
93
  const canonical = canonicalHost();
88
94
  if (canonical === null || request.headers.host !== canonical)
@@ -1,3 +1,4 @@
1
+ import { flexibleSignInStatus } from "../flexible-sign-in.js";
1
2
  import { handlersOf } from './handler-registry.js';
2
3
  import { adapterPolicy } from "./route-policy.js";
3
4
  import { mintApiToken, TOKEN_DAYS } from "../api-tokens.js";
@@ -31,6 +32,11 @@ import { FULL_SESSION, SESSION_COOKIE, SIGN_IN_LINK_PATH } from "./session.js";
31
32
  import { admitLink, saveLinkSession, spendLink } from "./link-redemption.js";
32
33
  import { setupCodeMatches, signupCookie, signupFromHere } from "./signup-gate.js";
33
34
  const AUTH_TIME_SKEW_MS = 60_000;
35
+ const LINK_LANDINGS = Object.freeze({
36
+ flexible: "/settings/general?section=flexible",
37
+ "flexible-sign-in": "/settings/change/flexible-sign-in",
38
+ project: "/settings/project",
39
+ });
34
40
  export function sameVisitCheck(authTime, startedAt, now) {
35
41
  if (authTime === null || !Number.isFinite(authTime))
36
42
  return null;
@@ -91,6 +97,7 @@ export function createPeopleHandlers(runtime) {
91
97
  seen: seen === null ? `Joined ${one.addedAt.slice(0, 10)}` : now.getTime() - seen < 5 * 60_000 ? "Signed in now" : `Active ${new Date(seen).toISOString().slice(11, 16)} UTC`,
92
98
  joined: one.addedAt.slice(0, 10), activity: personHref(one.name),
93
99
  acts: store.recentActsOf(one.name).map(act => `${act.kind} ${act.subject} ${act.at.slice(0, 16).replace("T", " ")}`),
100
+ threadSignIn: approverView && flexibleSignInStatus(store, one.name).state !== "none",
94
101
  };
95
102
  });
96
103
  const invites = approverView ? store.openInvites(now) : [];
@@ -261,7 +268,9 @@ export function createPeopleHandlers(runtime) {
261
268
  ? html `That sign-in link has been used or has expired. Run <code>toolroll</code> again to open Toolroll.`
262
269
  : html `That sign-in link has been used or has expired. Sign in with your password, or run <code>toolroll</code> again.`, "/chat", ssoOffer()));
263
270
  }
264
- return signedInTo(response, keyed.key, "/chat", [`${SESSION_COOKIE}=${id}; HttpOnly; SameSite=Strict; Path=/${cookieSecure}`]);
271
+ const then = url.searchParams.getAll("then");
272
+ const landing = then.length === 1 && Object.hasOwn(LINK_LANDINGS, then[0]) ? LINK_LANDINGS[then[0]] : "/chat";
273
+ return signedInTo(response, keyed.key, landing, [`${SESSION_COOKIE}=${id}; HttpOnly; SameSite=Strict; Path=/${cookieSecure}`]);
265
274
  }
266
275
  async function ssoStart(ctx) {
267
276
  const { url, who, request, response } = ctx;
@@ -88,6 +88,7 @@ const LOCAL_POSTS = Object.freeze({
88
88
  "settings.knowledge-tidy": "memory-review",
89
89
  "settings.advanced": "view-preference",
90
90
  "settings.task-sizing": "task-sizing-switch",
91
+ "settings.flexible": "flexible-switch",
91
92
  "agents.seen": "mark-seen",
92
93
  "agents.watch": "watch-agent",
93
94
  });
@@ -267,6 +268,7 @@ get("tasks", "task.page", `^\\/t\\/${TASK}$`, { project: "task", limited: "resou
267
268
  get("tasks", "task.evidence", `^\\/t\\/${TASK}\\/evidence$`, { project: "task", limited: "resource", ...free, sample: "/t/one/evidence" });
268
269
  get("tasks", "task.steps", `^\\/t\\/${TASK}\\/steps$`, { project: "task", limited: "resource", ...free, sample: "/t/one/steps" });
269
270
  get("tasks", "task.diff", `^\\/t\\/${TASK}\\/diff$`, { project: "task", limited: "resource", ...free, sample: "/t/one/diff" });
271
+ get("tasks", "task.approval", `^\\/t\\/${TASK}\\/approval$`, { project: "task", limited: "resource", callers: ["cookie"], ...free, sample: "/t/one/approval" });
270
272
  get("tasks", "task.release", `^\\/t\\/${TASK}\\/release$`, { project: "task", limited: "resource", ...free, sample: "/t/one/release" });
271
273
  get("tasks", "release.locate", `^\\/approve\\/${ID}$`, { project: "task-ref", limited: "resource", ...free, sample: "/approve/1" });
272
274
  get("pages", "ledger.export", "/ledger/export", { limited: "unscoped", ...free });
@@ -418,6 +420,10 @@ get("settings", "settings.passwordless", "/settings/passwordless", { ...free, ..
418
420
  post("settings", "settings.passwordless-send", "/settings/passwordless", { callers: ["cookie"], ...operator("An instance operator sets Passwordless.", "/settings") });
419
421
  post("settings", "settings.local-mode-off", "/settings/local-mode/off", { callers: ["cookie"], scope: "step-up", ...operator("An instance operator turns off local mode.", "/settings/general?section=local-mode") });
420
422
  post("settings", "settings.task-sizing", "/settings/task-sizing", { scope: "step-up", limited: "deny", ...operator("An instance operator chooses how tasks are sized.", "/settings/general?section=task-sizing") });
423
+ post("settings", "settings.flexible", "/settings/flexible", { callers: ["cookie"], scope: "step-up", limited: "deny", ...operator("An instance operator turns interactive agent threads on or off.", "/settings/general?section=flexible") });
424
+ post("settings", "settings.flexible-sign-in", "/settings/flexible-sign-in", { callers: ["cookie"], scope: "step-up", limited: "self", ...approver("An approver saves their own Claude sign-in for threads.", "/settings/general?section=flexible-sign-in") });
425
+ post("settings", "settings.flexible-sign-in-check", "/settings/flexible-sign-in-check", { callers: ["cookie"], scope: "step-up", limited: "self", ...approver("An approver checks their own Claude sign-in for threads.", "/settings/general?section=flexible-sign-in") });
426
+ post("settings", "settings.flexible-sign-in-clear", "/settings/flexible-sign-in-clear", { callers: ["cookie"], scope: "step-up", limited: "self" });
421
427
  post("settings", "settings.just-me", "/settings/install-mode/solo", { callers: ["cookie"], scope: "step-up", ...operator("An instance operator says it's just them.", "/settings/general?section=install-mode") });
422
428
  post("settings", "settings.release-approval-send", "/settings/release-approval", { callers: ["cookie"], ...approver("An approver sets how releases are approved.", "/settings/approval") });
423
429
  post("pages", "ledger.checkpoint", "/ledger/checkpoint", operator("An instance operator makes ledger checkpoints.", "/ledger"));
@@ -20,6 +20,13 @@ export const SETTINGS_SECTIONS = Object.freeze([
20
20
  { id: "task-sizing", area: "general", title: "Size tasks with a quick model call (Claude Haiku, on your plan)", pinnedFrom: "settings.group-general", policy: GROUP_PAGE,
21
21
  read: ["installation"], scope: {}, act: { switch: ["cookie-session", "operator"] }, changes: [{ id: "task-sizing", act: "switch", proof: "task-sizing" }],
22
22
  opens: false, scripts: [], oldIds: [] },
23
+ { id: "flexible", area: "general", title: "Interactive agent threads (beta)", pinnedFrom: "settings.group-general", policy: GROUP_PAGE,
24
+ read: ["installation"], scope: {}, act: { switch: ["cookie-session", "operator"] }, changes: [{ id: "flexible", act: "switch", proof: "flexible-switch" }],
25
+ opens: false, scripts: [], oldIds: [] },
26
+ { id: "flexible-sign-in", area: "general", title: "Your Claude sign-in for threads", pinnedFrom: "settings.group-general", policy: GROUP_PAGE,
27
+ read: ["approver"], scope: {}, act: { save: ["cookie-session", "approver"], check: ["cookie-session", "approver"], remove: ["cookie-session"] },
28
+ changes: [{ id: "flexible-sign-in", act: "save", proof: "flexible-sign-in" }, { id: "flexible-sign-in-check", act: "check", proof: "flexible-sign-in-check" }, { id: "flexible-sign-in-clear", act: "remove", proof: "flexible-sign-in-clear" }],
29
+ opens: false, scripts: [], oldIds: [] },
23
30
  { id: "advanced", area: "general", title: "Show advanced features", pinnedFrom: "settings.group-advanced", policy: GROUP_PAGE,
24
31
  read: [], scope: { "operator-pages": ["operator"] }, act: { switch: ["cookie-session"] }, changes: [], opens: true, scripts: [], oldIds: ["show-advanced"] },
25
32
  { id: "local-mode", area: "general", title: "Local mode", pinnedFrom: "settings.group-access", policy: GROUP_PAGE,
@@ -2,7 +2,8 @@ import { ADVANCED_PAGES } from "../advanced-view.js";
2
2
  import { accentNote, ACCENT_PRESETS } from "../accent-colors.js";
3
3
  import { installModeLine, justMeAllowed, TEAM_FACT_WORDS } from "../install-mode.js";
4
4
  import { html, joinHtml, postForm } from "../html.js";
5
- import { kitSectionForm } from "../settings-kit.js";
5
+ import { kitSectionForm, secretInput } from "../settings-kit.js";
6
+ import { signInCheckWords, statusCheck } from "../flexible-sign-in.js";
6
7
  import { evaluateRoutePolicy, holdsRole } from "./route-policy.js";
7
8
  import { btn, codeLine, disclose, doc, docHeader, formRow, infoLine, input, notice, phoneHeader, select, settingsLink, settingsSection } from "./kit.js";
8
9
  import { changeDocumentOf, changeHref, sectionHref, SETTINGS_SECTIONS } from "./settings-section-table.js";
@@ -304,6 +305,89 @@ function taskSizingSection(deps) {
304
305
  },
305
306
  };
306
307
  }
308
+ export const FLEXIBLE_SETTING_WORDS = "Claude Code only for now. Runs inside Toolroll's sandbox with your Claude sign-in relayed; Toolroll never gives the agent your key.";
309
+ function flexibleSection(deps) {
310
+ return {
311
+ loadSummary: ctx => ({ on: deps.flexible().on, canSwitch: ctx.can["switch"] === true }),
312
+ render: ({ summary, attrs }) => settingsSection({ id: "flexible", title: "Interactive agent threads (beta)", state: summary.on ? " · on" : " · off", attrs,
313
+ lead: `${summary.on ? "On" : "Off"}. ${FLEXIBLE_SETTING_WORDS}`,
314
+ ...(summary.canSwitch ? { right: btn(summary.on ? "Turn off" : "Turn on", { sm: true, href: "/settings/change/flexible" }) } : {}), body: html `` }),
315
+ refusal: "An instance operator turns interactive agent threads on or off.",
316
+ renderChange: ({ declaration, summary, problem }) => {
317
+ const home = sectionHref(declaration);
318
+ const on = summary?.on === true;
319
+ const title = "Interactive agent threads (beta)";
320
+ if (!on && deps.passwordFree())
321
+ return { title, body: html `<div data-kit-page>${phoneHeader(title, { back: home })}${doc(docHeader({ title, back: [home, "General"], same: true }), passwordFirst(home))}</div>` };
322
+ const words = joinHtml([
323
+ html `<p>${on ? "Turn them off. No new thread or turn starts, and any thread running now is stopped." : `Turn them on. Press T in the workbench to work with Claude Code in a thread. ${FLEXIBLE_SETTING_WORDS} Each project still needs its own Flexible terms, and each thread shows its terms before it starts.`}</p>`,
324
+ problem === null ? "" : notice(problem),
325
+ kitSectionForm({ proof: on ? "flexible-switch" : "flexible-switch-on", action: "/settings/flexible", id: "flexible-form", native: true, save: { label: on ? "Turn off" : "Turn on" }, confirm: on ? "Turn off interactive agent threads" : "Turn on interactive agent threads", hidden: { enabled: on ? "off" : "on" }, body: html `` }),
326
+ html `<div class="k-acts">${btn("Cancel", { variant: "ghost", href: home })}</div>`,
327
+ ]);
328
+ return { title, body: html `<div data-kit-page>${phoneHeader(title, { back: home })}${doc(docHeader({ title, back: [home, "General"], same: true }), words)}</div>` };
329
+ },
330
+ };
331
+ }
332
+ function passwordFirst(home) {
333
+ return joinHtml([
334
+ html `<p>This needs a Toolroll password, and you haven't set one. Run <code class="k-mono">toolroll password set</code> in a terminal, then sign in here with it.</p>`,
335
+ html `<div class="k-acts">${btn("Back", { variant: "ghost", href: home })}</div>`,
336
+ ]);
337
+ }
338
+ function flexibleSignInSection(deps) {
339
+ const title = "Your Claude sign-in for threads";
340
+ return {
341
+ loadSummary: ctx => ({ status: deps.flexibleSignIn(ctx.person.name), threadsOn: deps.flexible().on, canSave: ctx.can["save"] === true, canCheck: ctx.can["check"] === true,
342
+ canRemove: ctx.can["remove"] === true, passwordFree: deps.passwordFree() }),
343
+ render: ({ summary, attrs }) => {
344
+ const status = summary.status;
345
+ const lead = status.state === "none" ? "None. Threads use your own Claude sign-in: run claude setup-token in a terminal, then add the token here. It powers only threads you start."
346
+ : status.state === "refused" ? `Claude didn't accept it. Run claude setup-token again and replace it.`
347
+ : `Saved ${status.savedAt.slice(0, 10)}. ${signInCheckWords(statusCheck(status))} It powers only threads you start; a password reset ends it.`;
348
+ const acts = status.state === "none" ? "" : html `<div class="k-acts">${summary.canCheck ? btn("Check again", { sm: true, variant: "ghost", href: "/settings/change/flexible-sign-in-check" }) : ""}${summary.canRemove ? btn("Remove", { sm: true, variant: "ghost", href: "/settings/change/flexible-sign-in-clear" }) : ""}</div>`;
349
+ return settingsSection({ id: "flexible-sign-in", title, state: status.state === "none" ? " · none" : status.state === "refused" ? " · not accepted" : " · saved", attrs, lead,
350
+ ...(summary.canSave ? { right: btn(status.state === "none" ? "Add" : "Replace", { sm: true, href: "/settings/change/flexible-sign-in" }) } : {}),
351
+ body: joinHtml([summary.threadsOn ? "" : infoLine("Interactive agent threads are off. An instance operator turns them on above."), acts]) });
352
+ },
353
+ refusal: "Only you change your own Claude sign-in for threads.",
354
+ renderChange: ({ declaration, summary, problem, document }) => {
355
+ const home = `${sectionHref(declaration)}`;
356
+ const page = (heading, words) => ({ title: heading, body: html `<div data-kit-page>${phoneHeader(heading, { back: home })}${doc(docHeader({ title: heading, back: [home, "General"], same: true }), words)}</div>` });
357
+ const status = summary?.status ?? { state: "none" };
358
+ if (document === "flexible-sign-in-clear") {
359
+ if (status.state === "none")
360
+ return page("Remove your Claude sign-in", html `<p>You have no Claude sign-in for threads saved.</p>`);
361
+ return page("Remove your Claude sign-in", joinHtml([
362
+ html `<p>Your threads can't reach Claude until you add one again. The token still works at Claude until you revoke it in your Claude account.</p>`,
363
+ problem === null ? "" : notice(problem),
364
+ kitSectionForm({ proof: "flexible-sign-in-clear", action: "/settings/flexible-sign-in-clear", id: "flexible-sign-in-clear-form", native: true, save: { label: "Remove", variant: "danger" }, confirm: "Remove your Claude sign-in for threads", body: html `` }),
365
+ html `<div class="k-acts">${btn("Cancel", { variant: "ghost", href: home })}</div>`,
366
+ ]));
367
+ }
368
+ if (document === "flexible-sign-in-check") {
369
+ if (status.state === "none")
370
+ return page("Check your Claude sign-in", html `<p>You have no Claude sign-in for threads saved.</p>`);
371
+ return page("Check your Claude sign-in", joinHtml([
372
+ html `<p>Toolroll asks Claude to count the tokens of one word with your sign-in. It's only a check: it changes nothing, and it never clears a sign-in Claude didn't accept.</p>`,
373
+ problem === null ? "" : notice(problem),
374
+ kitSectionForm({ proof: "flexible-sign-in-check", action: "/settings/flexible-sign-in-check", id: "flexible-sign-in-check-form", native: true, save: { label: "Check again" }, confirm: "Check your Claude sign-in for threads", body: html `` }),
375
+ html `<div class="k-acts">${btn("Cancel", { variant: "ghost", href: home })}</div>`,
376
+ ]));
377
+ }
378
+ const heading = status.state === "none" ? "Add your Claude sign-in" : "Replace your Claude sign-in";
379
+ if (summary?.passwordFree === true)
380
+ return page(heading, passwordFirst(home));
381
+ return page(heading, joinHtml([
382
+ html `<p>Threads you start run on your own Claude plan, through this sign-in. Toolroll keeps it for you alone and never shows it again.</p>`,
383
+ problem === null ? "" : notice(problem),
384
+ kitSectionForm({ proof: "flexible-sign-in", action: "/settings/flexible-sign-in", id: "flexible-sign-in-form", native: true, save: { label: "Save" }, confirm: heading,
385
+ body: secretInput({ id: "flexible-sign-in-token", name: "token", label: "Your Claude sign-in", required: true, hint: "In a terminal, run claude setup-token, finish signing in, and paste the token it prints." }) }),
386
+ html `<div class="k-acts">${btn("Cancel", { variant: "ghost", href: home })}</div>`,
387
+ ]));
388
+ },
389
+ };
390
+ }
307
391
  export function generalSections(deps) {
308
392
  return {
309
393
  appearance: appearanceSection(),
@@ -312,6 +396,8 @@ export function generalSections(deps) {
312
396
  version: versionSection(deps),
313
397
  "install-mode": installModeSection(deps),
314
398
  "task-sizing": taskSizingSection(deps),
399
+ flexible: flexibleSection(deps),
400
+ "flexible-sign-in": flexibleSignInSection(deps),
315
401
  advanced: advancedSection(),
316
402
  "local-mode": localModeSection(deps),
317
403
  };