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/dist/operate.js CHANGED
@@ -268,6 +268,7 @@ import { installMethod } from "./install-method.js";
268
268
  import { PACKAGE_VERSION } from "./version.js";
269
269
  import { machineActing } from "./scope.js";
270
270
  import { flexibleAvailable, flexibleSetting, setFlexibleSetting } from "./flexible-available.js";
271
+ import { flexibleSignInStatus, looksLikeClaudeCredential, recheckFlexibleSignIn, removeFlexibleSignIn, saveFlexibleSignIn, setupTokenFromPaste, signInCheckWords, statusCheck, tidyFlexibleSignIns } from "./flexible-sign-in.js";
271
272
  import { enableFlexible, FLEXIBLE_LAPSE_WORDS, FLEXIBLE_LEVEL_WORDS, FLEXIBLE_UNAVAILABLE, flexibleStanding, flexibleTermsWords, isFlexibleLevel, lowerFlexible, proposedFlexibleTerms, turnFlexibleOff } from "./flexible.js";
272
273
  import { reevaluateResultRecords } from "./route-results.js";
273
274
  import { holdRuleOff, routeRulesPass, taskEvidenceWords } from "./route-rules.js";
@@ -591,6 +592,10 @@ Agents — which provider and model each phase runs on
591
592
  interactive agent threads (beta), off by default: T in the workbench
592
593
  starts a Claude Code thread inside Toolroll's sandbox, with your Claude
593
594
  sign-in relayed (config show flexible says which)
595
+ toolroll config set|clear|show flexible-sign-in [--as <you>]
596
+ your own Claude sign-in for threads: run \`claude setup-token\`, then
597
+ paste its token at the hidden prompt (never as an argument). Each
598
+ person brings their own; a password reset ends it
594
599
  toolroll chat --as <you> [--repo <path>…] [--say "…"] [--end]
595
600
  [--ceiling-usd <n>] [--json] (password at the prompt;
596
601
  --token <t> only for scripts — it lands in shell history)
@@ -777,6 +782,7 @@ export const OPERATE_BOOLEAN_FLAGS = new Set([
777
782
  "password-stdin",
778
783
  "now",
779
784
  "preview", "apply",
785
+ "no-check", "check",
780
786
  ]);
781
787
  const PROJECT_NETWORK_VALUE_FLAGS = new Set(["remove", "local"]);
782
788
  export function parseOperateArgs(argv, ownValues = new Set()) {
@@ -4237,6 +4243,8 @@ async function configCommand(positional, flags, context) {
4237
4243
  return taskSizingConfig(action ?? "show", positional[2], repoGiven !== undefined, flags, context);
4238
4244
  if (phase === "flexible")
4239
4245
  return flexibleConfig(action ?? "show", positional[2], repoGiven !== undefined, flags, context);
4246
+ if (phase === "flexible-sign-in")
4247
+ return flexibleSignInConfig(action ?? "show", positional.slice(2), repoGiven !== undefined, flags, context);
4240
4248
  if (action === undefined || action === "show") {
4241
4249
  const installation = store.listPhaseConfig(INSTALLATION_SCOPE);
4242
4250
  const project = scope === INSTALLATION_SCOPE ? [] : store.listPhaseConfig(scope);
@@ -12747,3 +12755,105 @@ async function flexibleConfig(action, value, repoGiven, flags, context) {
12747
12755
  ];
12748
12756
  return succeed(write, json, command, { ...shown.payload, stopped: report.stopped, survivors: report.survivors }, () => lines);
12749
12757
  }
12758
+ async function flexibleSignInConfig(action, extra, repoGiven, flags, context) {
12759
+ const { store, write, json, clock } = context;
12760
+ const command = `config ${action} flexible-sign-in`;
12761
+ const given = [...extra, ...[...flags.values()].filter((value) => typeof value === "string")];
12762
+ if (given.some(value => looksLikeClaudeCredential(value)))
12763
+ return fail(write, json, command, "argument", "Toolroll never takes your Claude sign-in as an argument: it is now in your shell history. Run `claude setup-token` again, then `toolroll config set flexible-sign-in` and paste the new token when asked. Nothing was saved.", EXIT.usage);
12764
+ if (extra.length > 0)
12765
+ return fail(write, json, command, "usage", "`toolroll config set flexible-sign-in` takes no value: it asks for the token at a hidden prompt.", EXIT.usage);
12766
+ if (repoGiven)
12767
+ return fail(write, json, command, "usage", "your Claude sign-in is yours, not a project's: no --repo", EXIT.usage);
12768
+ if (flags.has("no-check") && action !== "set")
12769
+ return fail(write, json, command, "usage", "--no-check is only for `config set flexible-sign-in`", EXIT.usage);
12770
+ if (flags.has("check") && action !== "show")
12771
+ return fail(write, json, command, "usage", "--check is only for `config show flexible-sign-in --check`", EXIT.usage);
12772
+ const personOnly = "Only you, as a person with your Toolroll password, change your own Claude sign-in for threads; never a token, the lead, a chat app or a machine.";
12773
+ if (machineActing() || process.env["TOOLROLL_LEAD_TOKEN"] !== undefined || process.env["TOOLROLL_REMOTE_TOKEN"] !== undefined)
12774
+ return fail(write, json, command, "person-only", personOnly, EXIT.refused);
12775
+ if (passwordFreeOwner(store))
12776
+ return fail(write, json, command, "local-owner", "You haven't set a password yet, and this needs one. Set it first with `toolroll password set`, then run this again.", EXIT.refused);
12777
+ if (action !== "show" && action !== "set" && action !== "clear")
12778
+ return fail(write, json, command, "usage", "`toolroll config set|clear|show flexible-sign-in`", EXIT.usage);
12779
+ let acting;
12780
+ if (action === "set") {
12781
+ if (flags.has("token"))
12782
+ return fail(write, json, command, "usage", "Saving your Claude sign-in asks for your Toolroll password at a hidden prompt, typed for this command: never --token or a saved sign-in.", EXIT.usage);
12783
+ const typed = context.easySeams?.askHidden ?? (interactive() && !json ? askHidden : null);
12784
+ const named = context.easySeams?.ask ?? (interactive() && !json ? ask : null);
12785
+ if (typed === null)
12786
+ return fail(write, json, command, "usage", "Run this in your own terminal: it asks for your Toolroll password and the token from `claude setup-token` at hidden prompts.", EXIT.usage);
12787
+ const name = text(flags, "as") ?? (named === null ? undefined : await named("username: "));
12788
+ const password = await typed("password: ");
12789
+ acting = name === undefined || name.length === 0 || password.length === 0 ? null : { name, token: password };
12790
+ }
12791
+ else
12792
+ acting = await askCredentials(flags, context);
12793
+ if (acting === null)
12794
+ return fail(write, json, command, "usage", "This needs your name and password: run it in your own terminal to be asked.", EXIT.usage);
12795
+ const statusWords = (status) => status.state === "none"
12796
+ ? "Your Claude sign-in for threads: none. Run `claude setup-token`, then `toolroll config set flexible-sign-in`."
12797
+ : status.state === "refused"
12798
+ ? "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`."
12799
+ : `Your Claude sign-in for threads: saved ${status.savedAt.slice(0, 10)}. ${signInCheckWords(statusCheck(status))} It powers only threads you start.`;
12800
+ const statusData = (status) => status.state === "none" ? { state: "none" } : { state: status.state, savedAt: status.savedAt, check: status.checkOutcome, checkStatus: status.checkStatus };
12801
+ if (action === "show") {
12802
+ const shown = store.transact(() => {
12803
+ const proved = authenticateApprover(store, acting.name, acting.token);
12804
+ return proved.ok && personProof(proved.method) ? flexibleSignInStatus(store, acting.name) : null;
12805
+ });
12806
+ if (shown === null)
12807
+ return fail(write, json, command, "unauthenticated", personOnly, EXIT.refused);
12808
+ if (!flags.has("check"))
12809
+ return succeed(write, json, command, { signIn: statusData(shown) }, () => [statusWords(shown)]);
12810
+ let state;
12811
+ try {
12812
+ state = dirname(realpathSync(context.databaseFile));
12813
+ }
12814
+ catch {
12815
+ return fail(write, json, command, "no-sign-in", "Toolroll's state folder can't be found.", EXIT.refused);
12816
+ }
12817
+ const again = await recheckFlexibleSignIn(store, state, { person: acting.name, clock });
12818
+ if (!again.ok)
12819
+ return fail(write, json, command, "no-sign-in", statusWords({ state: "none" }), EXIT.refused);
12820
+ const now = flexibleSignInStatus(store, acting.name);
12821
+ return succeed(write, json, command, { signIn: statusData(now), check: again.check.outcome }, () => [signInCheckWords(again.check), statusWords(now)]);
12822
+ }
12823
+ if (action === "clear") {
12824
+ const removed = store.transact(() => {
12825
+ const proved = authenticateApprover(store, acting.name, acting.token);
12826
+ if (!proved.ok || !personProof(proved.method))
12827
+ return null;
12828
+ return removeFlexibleSignIn(store, { person: acting.name, by: acting.name, now: clock() });
12829
+ });
12830
+ if (removed === null)
12831
+ return fail(write, json, command, "unauthenticated", personOnly, EXIT.refused);
12832
+ try {
12833
+ await tidyFlexibleSignIns(store, dirname(realpathSync(context.databaseFile)), { now: clock(), person: acting.name });
12834
+ }
12835
+ catch { }
12836
+ return succeed(write, json, command, { removed: removed.removed }, () => [removed.removed
12837
+ ? "Removed. 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."
12838
+ : "You had no Claude sign-in for threads saved. Nothing changed."]);
12839
+ }
12840
+ const typeHidden = context.easySeams?.askHidden ?? (interactive() && !json ? askHidden : null);
12841
+ if (typeHidden === null)
12842
+ return fail(write, json, command, "usage", "Run this in your own terminal: it asks for the token from `claude setup-token` at a hidden prompt.", EXIT.usage);
12843
+ const pasted = await typeHidden("Paste the token from `claude setup-token`: ");
12844
+ const shaped = setupTokenFromPaste(pasted);
12845
+ if (!shaped.ok)
12846
+ return fail(write, json, command, shaped.reason, shaped.message, EXIT.refused);
12847
+ let state;
12848
+ try {
12849
+ state = dirname(realpathSync(context.databaseFile));
12850
+ }
12851
+ catch {
12852
+ return fail(write, json, command, "not-saved", "Toolroll's state folder can't be found. Nothing was saved.", EXIT.refused);
12853
+ }
12854
+ const saved = await saveFlexibleSignIn(store, { state, person: acting.name, password: acting.token, token: shaped.token, check: !flags.has("no-check"), clock });
12855
+ if (!saved.ok)
12856
+ return fail(write, json, command, saved.reason, saved.message, EXIT.refused);
12857
+ const checked = saved.check === null ? { outcome: "not-checked" } : saved.check;
12858
+ return succeed(write, json, command, { saved: true, replaced: saved.replaced, check: checked.outcome, signIn: statusData(flexibleSignInStatus(store, acting.name)) }, () => [`${saved.replaced ? "Replaced" : "Saved"}. ${signInCheckWords(checked)} It powers only threads you start; a password reset ends it.`]);
12859
+ }
@@ -3,11 +3,14 @@ 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 { realpathSync } from "node:fs";
7
+ import { dirname } from "node:path";
6
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
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";
12
15
  import { termsOfLines } from "../fast-terms.js";
13
16
  import { localActNow } from "../local-owner.js";
@@ -73,7 +76,7 @@ export function createEngineHandlers(runtime) {
73
76
  if ([...url.searchParams.keys()].length > 0)
74
77
  return refusal(response, 400, "request");
75
78
  const view = agentInventoryOf(who, store);
76
- 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)));
77
80
  }
78
81
  async function agentsCheck(ctx) {
79
82
  const { who, response } = ctx;
@@ -85,7 +88,7 @@ export function createEngineHandlers(runtime) {
85
88
  await Promise.race([runtime.checkLocalAgents(true), new Promise(done => { timer = setTimeout(done, 8_000); timer.unref?.(); })]).finally(() => clearTimeout(timer));
86
89
  }
87
90
  const view = agentInventoryOf(who, store);
88
- 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)));
89
92
  }
90
93
  async function liveRun(ctx) {
91
94
  const { url, who, request, response } = ctx;
@@ -131,13 +134,14 @@ export function createEngineHandlers(runtime) {
131
134
  const threadsOn = () => flexibleAvailable(store) ? openHost() : null;
132
135
  const threadsRead = () => flexible ?? (flexibleAvailable(store) || flexibleThreadsExist(store) ? openHost() : null);
133
136
  let stopping = false;
137
+ let tidying = false;
134
138
  const ownedThread = (request, who, sessions, thread) => {
135
139
  if (rereadBrowser(runtime, request, who) === null)
136
140
  return null;
137
141
  const admitted = admitFlexibleThreadOwner(store, sessions, { thread, viewer: { name: who.name }, canAccess: repo => store.accountCanAccess(who.name, repo) });
138
142
  return admitted.ok ? admitted.repo : null;
139
143
  };
140
- 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 });
141
145
  async function liveThread(ctx) {
142
146
  const { url, who, request, response } = ctx;
143
147
  if (who.via !== "cookie")
@@ -230,7 +234,7 @@ export function createEngineHandlers(runtime) {
230
234
  const { who, request, response, posted } = ctx;
231
235
  const flexible = threadsOn();
232
236
  if (flexible === null)
233
- return acted(response, 404, "refused", FLEXIBLE_UNAVAILABLE);
237
+ return acted(response, 404, "refused", FLEXIBLE_UNAVAILABLE, store.isInstanceOperator(who.name) ? "turn-on" : "ask-operator");
234
238
  if (who.via !== "cookie" || rereadBrowser(runtime, request, who) === null)
235
239
  return acted(response, 403, "refused", "Only a person signed in here can start a thread.");
236
240
  if (launcher === null)
@@ -243,6 +247,9 @@ export function createEngineHandlers(runtime) {
243
247
  if (!store.accountCanAccess(who.name, repo))
244
248
  return acted(response, 403, "refused", "That project is outside your access.");
245
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);
246
253
  const made = flexibleStartCard(store, { repo, by, model: body.get("model"), message });
247
254
  if (!made.ok)
248
255
  return acted(response, 409, "refused", made.message);
@@ -372,6 +379,15 @@ export function createEngineHandlers(runtime) {
372
379
  }
373
380
  return {
374
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
+ }
375
391
  const host = flexible;
376
392
  if (host === null)
377
393
  return;
@@ -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;
@@ -421,6 +421,9 @@ post("settings", "settings.passwordless-send", "/settings/passwordless", { calle
421
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") });
422
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
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" });
424
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") });
425
428
  post("settings", "settings.release-approval-send", "/settings/release-approval", { callers: ["cookie"], ...approver("An approver sets how releases are approved.", "/settings/approval") });
426
429
  post("pages", "ledger.checkpoint", "/ledger/checkpoint", operator("An instance operator makes ledger checkpoints.", "/ledger"));
@@ -23,6 +23,10 @@ export const SETTINGS_SECTIONS = Object.freeze([
23
23
  { id: "flexible", area: "general", title: "Interactive agent threads (beta)", pinnedFrom: "settings.group-general", policy: GROUP_PAGE,
24
24
  read: ["installation"], scope: {}, act: { switch: ["cookie-session", "operator"] }, changes: [{ id: "flexible", act: "switch", proof: "flexible-switch" }],
25
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: [] },
26
30
  { id: "advanced", area: "general", title: "Show advanced features", pinnedFrom: "settings.group-advanced", policy: GROUP_PAGE,
27
31
  read: [], scope: { "operator-pages": ["operator"] }, act: { switch: ["cookie-session"] }, changes: [], opens: true, scripts: [], oldIds: ["show-advanced"] },
28
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";
@@ -316,6 +317,8 @@ function flexibleSection(deps) {
316
317
  const home = sectionHref(declaration);
317
318
  const on = summary?.on === true;
318
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>` };
319
322
  const words = joinHtml([
320
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>`,
321
324
  problem === null ? "" : notice(problem),
@@ -326,6 +329,65 @@ function flexibleSection(deps) {
326
329
  },
327
330
  };
328
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
+ }
329
391
  export function generalSections(deps) {
330
392
  return {
331
393
  appearance: appearanceSection(),
@@ -335,6 +397,7 @@ export function generalSections(deps) {
335
397
  "install-mode": installModeSection(deps),
336
398
  "task-sizing": taskSizingSection(deps),
337
399
  flexible: flexibleSection(deps),
400
+ "flexible-sign-in": flexibleSignInSection(deps),
338
401
  advanced: advancedSection(),
339
402
  "local-mode": localModeSection(deps),
340
403
  };
@@ -59,6 +59,9 @@ import { parseProtectedPaths } from "../approval-policy.js";
59
59
  import { approvalRulesHtml, releaseApprovalHtml } from "../approval-rules-ui.js";
60
60
  import { releaseApprovalSetting, setReleaseApproval } from "../release-auto.js";
61
61
  import { flexibleAvailable, flexibleSetting, setFlexibleSetting } from "../flexible-available.js";
62
+ import { flexibleSignInStatus, recheckFlexibleSignIn, removeFlexibleSignIn, saveFlexibleSignIn, setupTokenFromPaste, signInCheckWords, tidyFlexibleSignIns } from "../flexible-sign-in.js";
63
+ import { passwordFreeOwner } from "../task-outcome-cli.js";
64
+ import { realpathSync } from "node:fs";
62
65
  import { enableFlexible, FLEXIBLE_LEVEL_WORDS, FLEXIBLE_UNAVAILABLE, flexibleSettingsView, isFlexibleLevel, lowerFlexible, turnFlexibleOff } from "../flexible.js";
63
66
  import { backupHtml } from "../backup-ui.js";
64
67
  import { BACKUP_EVERY_HOURS, backupFolderOf, backupNow, checkBackupFolder, defaultBackupFolder, MAX_KEEP } from "../backup.js";
@@ -2767,6 +2770,9 @@ ${postForm("/settings/chat-approval/save", html `\
2767
2770
  "settings.lead-quick": leadQuick,
2768
2771
  "settings.task-sizing": taskSizingAct,
2769
2772
  "settings.flexible": flexibleSwitchAct,
2773
+ "settings.flexible-sign-in": flexibleSignInAct,
2774
+ "settings.flexible-sign-in-check": flexibleSignInCheckAct,
2775
+ "settings.flexible-sign-in-clear": flexibleSignInClearAct,
2770
2776
  "settings.lead-promise-cancel": leadPromiseCancel,
2771
2777
  "settings.lead-on": leadOn,
2772
2778
  "settings.code-map": codeMapAct("switch"),
@@ -3050,7 +3056,9 @@ ${postForm("/settings/chat-approval/save", html `\
3050
3056
  });
3051
3057
  if (!saved)
3052
3058
  return back("problem", wanted === "on" ? "Turning interactive agent threads on needs your Toolroll password, typed now." : "Enter your Toolroll password to change interactive agent threads.");
3053
- return done("said", wanted === "on" ? "Interactive agent threads are on. Press T in the workbench to start one with Claude Code." : "Interactive agent threads are off. Any thread still running is stopped.");
3059
+ if (wanted === "on")
3060
+ return sayTo(response, "/settings/general?section=flexible-sign-in")("said", "Threads are on. Next, add your Claude sign-in.");
3061
+ return done("said", "Interactive agent threads are off. Any thread still running is stopped.");
3054
3062
  }
3055
3063
  async function justMe(ctx) {
3056
3064
  const { response, now, posted } = ctx;
@@ -3232,6 +3240,8 @@ ${postForm("/settings/chat-approval/save", html `\
3232
3240
  installMode: () => installModeNow(store),
3233
3241
  taskSizing: () => taskSizingSetting(store),
3234
3242
  flexible: () => flexibleSetting(store),
3243
+ flexibleSignIn: name => flexibleSignInStatus(store, name),
3244
+ passwordFree: () => passwordFreeOwner(store),
3235
3245
  });
3236
3246
  const computersDeps = {
3237
3247
  computers: (now, manage) => computersOf(store, now, visible, manage),
@@ -3321,5 +3331,82 @@ ${postForm("/settings/chat-approval/save", html `\
3321
3331
  return sendScreen(response, 200, screen(answer.title, answer.body, { chrome: chromeFor(project, "settings"), forceSensitive: true }));
3322
3332
  };
3323
3333
  }
3334
+ const signInState = () => {
3335
+ const file = store.databaseFile();
3336
+ if (file === null || file === "" || file === ":memory:")
3337
+ return null;
3338
+ try {
3339
+ return dirname(realpathSync(file));
3340
+ }
3341
+ catch {
3342
+ return null;
3343
+ }
3344
+ };
3345
+ async function flexibleSignInAct(ctx) {
3346
+ const { response, now, posted } = ctx;
3347
+ const who = browserCaller(ctx.who);
3348
+ const body = readForm(posted, CONSOLE_FORMS.flexibleSignIn);
3349
+ const done = sayTo(response, "/settings/general?section=flexible-sign-in");
3350
+ const back = sayTo(response, "/settings/change/flexible-sign-in");
3351
+ if (["token", "password"].some(field => body.sent.getAll(field).length > 1))
3352
+ return back("problem", "That form was sent twice over. Nothing was saved.");
3353
+ if (body.sent.has("person"))
3354
+ return back("problem", "Your Claude sign-in is always your own. Nothing was saved.");
3355
+ if (who.authority !== "full")
3356
+ return back("problem", "Saving your Claude sign-in needs your Toolroll password, typed now. Nothing was saved.");
3357
+ const paste = setupTokenFromPaste(body.get("token") ?? "");
3358
+ if (!paste.ok)
3359
+ return back("problem", paste.message);
3360
+ const state = signInState();
3361
+ if (state === null)
3362
+ return back("problem", "Toolroll's state folder can't be found. Nothing was saved.");
3363
+ const saved = await saveFlexibleSignIn(store, { state, person: who.name, password: body.get("password") ?? "", token: paste.token, check: true, clock: () => now });
3364
+ if (!saved.ok)
3365
+ return back("problem", saved.message);
3366
+ return done("said", `${saved.replaced ? "Replaced" : "Saved"}. ${signInCheckWords(saved.check ?? { outcome: "not-checked" })}`);
3367
+ }
3368
+ async function flexibleSignInCheckAct(ctx) {
3369
+ const { response, now, posted } = ctx;
3370
+ const who = browserCaller(ctx.who);
3371
+ const body = readForm(posted, CONSOLE_FORMS.flexibleSignInCheck);
3372
+ const done = sayTo(response, "/settings/general?section=flexible-sign-in");
3373
+ const back = sayTo(response, "/settings/change/flexible-sign-in-check");
3374
+ if (body.sent.getAll("password").length > 1)
3375
+ return back("problem", "That form was sent twice over. Nothing was checked.");
3376
+ const proved = store.transact(() => authenticateApprover(who, body.get("password") ?? "").ok);
3377
+ if (!proved)
3378
+ return back("problem", "Enter your Toolroll password to check your Claude sign-in.");
3379
+ const state = signInState();
3380
+ const again = state === null ? null : await recheckFlexibleSignIn(store, state, { person: who.name, clock: () => now });
3381
+ if (again === null || !again.ok)
3382
+ return back("problem", "You have no Claude sign-in for threads saved. Add one first.");
3383
+ return done("said", signInCheckWords(again.check));
3384
+ }
3385
+ async function flexibleSignInClearAct(ctx) {
3386
+ const { response, now, posted } = ctx;
3387
+ const who = browserCaller(ctx.who);
3388
+ const body = readForm(posted, CONSOLE_FORMS.flexibleSignInClear);
3389
+ const person = (body.get("person") ?? "").trim() || who.name;
3390
+ const self = person === who.name;
3391
+ const done = sayTo(response, self ? "/settings/general?section=flexible-sign-in" : "/people");
3392
+ const back = sayTo(response, self ? "/settings/change/flexible-sign-in-clear" : "/people");
3393
+ if (["person", "password"].some(field => body.sent.getAll(field).length > 1))
3394
+ return back("problem", "That form was sent twice over. Nothing changed.");
3395
+ const removed = store.transact(() => {
3396
+ if (!self && !store.isInstanceOperator(who.name))
3397
+ return null;
3398
+ if (!authenticateApprover(who, body.get("password") ?? "").ok)
3399
+ return null;
3400
+ return removeFlexibleSignIn(store, { person, by: who.name, now });
3401
+ });
3402
+ if (removed === null)
3403
+ return back("problem", self ? "Enter your Toolroll password to remove your Claude sign-in." : "An instance operator removes someone's Claude sign-in for threads, with their password.");
3404
+ const state = signInState();
3405
+ if (state !== null)
3406
+ void tidyFlexibleSignIns(store, state, { now, person }).catch(() => { });
3407
+ return done("said", !removed.removed ? (self ? "You had no Claude sign-in for threads saved." : `${person} had no Claude sign-in for threads saved.`)
3408
+ : self ? "Removed. 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."
3409
+ : `Removed ${person}'s Claude sign-in for threads. Their threads can't reach Claude until they add one again.`);
3410
+ }
3324
3411
  return { registrations, modelsView };
3325
3412
  }
@@ -483,6 +483,9 @@ export function peopleHtml(view) {
483
483
  confirm: `Change ${one.name}’s projects`, body: joinHtml([accessFields(`${slug}-access`, view.projects, one.projects), note("Changing access signs this person out and ends their sessions and modes. Work they approved stays recorded.")]) }),
484
484
  one.you ? "" : kitSectionForm({ proof: "people-close", action: "/people/revoke", id: `${slug}-remove`, hidden: { name: one.name }, save: { label: `Remove ${one.name}`, variant: "danger" },
485
485
  confirm: `Remove ${one.name}’s sign-in`, body: note("Ends their access and everything it signed. History stays.") }),
486
+ !one.threadSignIn ? "" : kitSectionForm({ proof: "flexible-sign-in-clear", action: "/settings/flexible-sign-in-clear", id: `${slug}-thread-sign-in`, hidden: { person: one.name },
487
+ save: { label: "Remove their Claude sign-in for threads", variant: "outline" }, confirm: `Remove ${one.name}’s Claude sign-in for threads`,
488
+ body: note("Their threads can't reach Claude until they add one again. Toolroll never shows or sets anyone's sign-in.") }),
486
489
  ]);
487
490
  const recent = one.acts.length === 0 ? note("No recorded acts yet.") : note(`Recent: ${one.acts.slice(0, 3).join(" · ")}`);
488
491
  return settingsRecord({
@@ -57,6 +57,9 @@ export const PROOF_INVENTORY = [
57
57
  { id: "install-solo", action: "Say it's just you", routes: ["/settings/install-mode/solo"], form: "justMe", field: "password", proof: "credential", ...CREDENTIAL, role: "operator", handlerRole: "a full session (never the local owner)", secrets: [], terms: [] },
58
58
  { id: "flexible-switch", action: "Turn interactive agent threads off", routes: ["/settings/flexible"], form: "flexibleSwitch", field: "password", proof: "step-up", ...ACCEPT, role: "operator", secrets: [], terms: ["enabled"] },
59
59
  { id: "flexible-switch-on", action: "Turn interactive agent threads on", routes: ["/settings/flexible"], select: { field: "enabled", value: "on" }, form: "flexibleSwitch", field: "password", proof: "credential", ...CREDENTIAL, role: "operator", handlerRole: "a full session (never the local owner)", secrets: [], terms: ["enabled"] },
60
+ { id: "flexible-sign-in", action: "Save your Claude sign-in for threads", routes: ["/settings/flexible-sign-in"], form: "flexibleSignIn", field: "password", proof: "credential", ...CREDENTIAL, role: "approver", handlerRole: "a full session, for themselves only", secrets: ["token"], notProof: ["token"], terms: [] },
61
+ { id: "flexible-sign-in-check", action: "Check your Claude sign-in for threads again", routes: ["/settings/flexible-sign-in-check"], form: "flexibleSignInCheck", field: "password", proof: "step-up", ...ACCEPT, role: "approver", secrets: [], terms: [] },
62
+ { id: "flexible-sign-in-clear", action: "Remove a Claude sign-in for threads", routes: ["/settings/flexible-sign-in-clear"], form: "flexibleSignInClear", field: "password", proof: "step-up", ...ACCEPT, role: "any", handlerRole: "that person, or an instance operator", secrets: [], terms: ["person"] },
60
63
  { id: "task-sizing", action: "Turn task sizing by a quick model call on or off", routes: ["/settings/task-sizing"], form: "taskSizing", field: "password", proof: "step-up", ...ACCEPT, role: "operator", secrets: [], terms: ["enabled", "sizer"] },
61
64
  { id: "provider-key", action: "Save an AI provider key", routes: ["/settings/provider-key"], form: "providerKey", field: "password", proof: "credential", ...CREDENTIAL, role: "any", secrets: ["value"], terms: [] },
62
65
  { id: "telegram-token", action: "Save the Telegram bot token", routes: ["/settings/telegram-token"], form: "telegramToken", field: "password", proof: "credential", ...CREDENTIAL, role: "any", secrets: ["token"], notProof: ["token"], terms: [] },