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
@@ -3,7 +3,7 @@ import { createHash, randomBytes } from "node:crypto";
3
3
  import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
6
- import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
6
+ import { flexibleAvailable } from "./flexible-available.js";
7
7
  import { FLEXIBLE_UNAVAILABLE } from "./flexible.js";
8
8
  import { buildCacheEnv, fenceFor, FLEXIBLE_THREADS_DIR, grantFolder, PROTECTED_DIRS, PROTECTED_FILES, runFolders, srtTermsOf } from "./agent-fence.js";
9
9
  import { ACP_AGENTS, ACP_PROVIDER_IDS } from "./acp-agents.js";
@@ -13,9 +13,10 @@ import { hardenedGit, lazyFetchSetting, recordedCommonDir } from "./teardown-git
13
13
  import { withCheckoutLock } from "./git-views.js";
14
14
  import { processMayBeAlive } from "./process-liveness.js";
15
15
  import { startIdentityOf } from "./flexible-custody.js";
16
- import { defaultCustodyIO, holdLaunch, recordGateShut, recordLaunchOpened, recordLive, recordNeverStarted, recordSpawning, settleLaunch, unsettledLaunch } from "./flexible-launch.js";
16
+ import { defaultCustodyIO, holdLaunch, recordGateShut, recordLive, reserveLaunchOpen, recordNeverStarted, recordSpawning, settleLaunch, unsettledLaunch } from "./flexible-launch.js";
17
17
  import { readProjectRefs, saveRefSnapshot } from "./flexible-refs.js";
18
18
  import { projectRowKnown } from "./store.js";
19
+ import { readProjectRegistryNow } from "./repos.js";
19
20
  import { poolRootOf } from "./worktree.js";
20
21
  export const FLEXIBLE_THREAD_ID = /^[0-9a-f]{32}$/;
21
22
  export const flexibleKeepRef = (id) => `refs/toolroll/threads/${id}/base`;
@@ -167,12 +168,12 @@ function reserveProtectedNames(repo) {
167
168
  writeFileSync(join(repo, ".git", "info", "exclude"), ["# Toolroll: placeholders that hold protected names (flexible-thread.ts)", ...reserved, ""].join("\n"), { mode: 0o644, flag: "wx" });
168
169
  }
169
170
  export async function prepareFlexibleThread(store, input) {
170
- if (!FLEXIBLE_AVAILABLE)
171
+ if (!flexibleAvailable(store))
171
172
  return refuse("not-available");
172
173
  const state = stateFolderOf(store);
173
174
  if (state === null)
174
175
  return refuse("no-state-folder");
175
- if (!projectRowKnown(store, input.repo))
176
+ if (!flexibleProjectKnown(store, input.repo))
176
177
  return refuse("not-a-project");
177
178
  if (!BASE_NAME.test(input.base) || input.base.includes(".."))
178
179
  return refuse("base-unknown");
@@ -260,8 +261,6 @@ export async function prepareFlexibleThread(store, input) {
260
261
  }
261
262
  }
262
263
  export async function removeFlexibleThread(store, input) {
263
- if (!FLEXIBLE_AVAILABLE)
264
- return refuse("not-available");
265
264
  if (!FLEXIBLE_THREAD_ID.test(input.id))
266
265
  return refuse("thread-unknown");
267
266
  return withThreadLock(input.id, () => removeLocked(store, input));
@@ -383,7 +382,7 @@ function threadReadOnly(paths) {
383
382
  ...TOP_PROTECTED.map(one => join(paths.repo, one.name))].sort();
384
383
  }
385
384
  export function flexibleThreadFence(store, input) {
386
- if (!FLEXIBLE_AVAILABLE)
385
+ if (!flexibleAvailable(store))
387
386
  return refuse("not-available");
388
387
  const network = input.network;
389
388
  if (!Number.isSafeInteger(network.proxyPort) || network.proxyPort < 1 || network.proxyPort > 65_535 || typeof network.token !== "string" || network.token === "")
@@ -399,7 +398,7 @@ export function flexibleThreadFence(store, input) {
399
398
  return refuse("thread-unknown");
400
399
  if (thread.state !== "ready")
401
400
  return refuse("thread-not-ready");
402
- if (!projectRowKnown(store, thread.repo))
401
+ if (!flexibleProjectKnown(store, thread.repo))
403
402
  return refuse("not-a-project");
404
403
  let project, objects;
405
404
  try {
@@ -513,8 +512,6 @@ function withThreadLock(id, work, timeoutMs) {
513
512
  return withCheckoutLock(real(homedir()), `flexible-thread:${id}`, work, timeoutMs);
514
513
  }
515
514
  export async function withFlexibleThreadLock(id, work, timeoutMs) {
516
- if (!FLEXIBLE_AVAILABLE)
517
- return refuse("not-available");
518
515
  if (!FLEXIBLE_THREAD_ID.test(id))
519
516
  return refuse("thread-unknown");
520
517
  return withThreadLock(id, work, timeoutMs);
@@ -538,7 +535,7 @@ function stopUnopenedLaunch(child) {
538
535
  }
539
536
  }
540
537
  export async function flexibleThreadSpawn(store, input, file, args, platform = process.platform, seams = {}) {
541
- if (!FLEXIBLE_AVAILABLE)
538
+ if (!flexibleAvailable(store))
542
539
  return refuse("not-available");
543
540
  if (!FLEXIBLE_THREAD_ID.test(input.id))
544
541
  return refuse("thread-unknown");
@@ -622,7 +619,9 @@ async function spawnLocked(store, input, file, args, platform, seams) {
622
619
  }
623
620
  let shut;
624
621
  try {
625
- shut = input.beforeOpen?.() ?? null;
622
+ if (typeof input.beforeOpen !== "function")
623
+ throw new Error("the start has no last re-check");
624
+ shut = reserveLaunchOpen(store, { launch: record.id, thread: input.id, turn: input.launch.turn, check: input.beforeOpen });
626
625
  }
627
626
  catch (error) {
628
627
  shut = error instanceof Error ? error.message : "the start couldn't be re-checked";
@@ -636,24 +635,10 @@ async function spawnLocked(store, input, file, args, platform, seams) {
636
635
  recordGateShut(store, { launch: record.id, thread: input.id, pid: pid, detail: `stopped before it ran: ${shut}` });
637
636
  return refuse("thread-not-ready", shut);
638
637
  }
639
- try {
640
- recordLaunchOpened(store, { launch: record.id, thread: input.id, turn: input.launch.turn });
641
- }
642
- catch {
643
- try {
644
- child.stdin?.destroy();
645
- }
646
- catch { }
647
- stopUnopenedLaunch(child);
648
- recordGateShut(store, { launch: record.id, thread: input.id, pid: pid, detail: "stopped before it ran: its launch couldn't be recorded" });
649
- return refuse("thread-not-ready", "its launch couldn't be recorded");
650
- }
651
638
  child.stdin.write("start\n");
652
639
  return { ok: true, pid: pid, launchId: record.id, launch, fenceDigest, child };
653
640
  }
654
641
  export async function stopFlexibleThreadAgent(store, input) {
655
- if (!FLEXIBLE_AVAILABLE)
656
- return refuse("not-available");
657
642
  if (!FLEXIBLE_THREAD_ID.test(input.id))
658
643
  return refuse("thread-unknown");
659
644
  return withThreadLock(input.id, async () => {
@@ -668,9 +653,18 @@ export async function stopFlexibleThreadAgent(store, input) {
668
653
  });
669
654
  }
670
655
  export function flexibleThreadCodexProfile(store, input) {
671
- if (!FLEXIBLE_AVAILABLE)
656
+ if (!flexibleAvailable(store))
672
657
  return refuse("not-available");
673
658
  void store;
674
659
  void input;
675
660
  return refuse("codex-unsupported");
676
661
  }
662
+ export function flexibleProjectKnown(store, repo) {
663
+ if (projectRowKnown(store, repo))
664
+ return true;
665
+ const file = store.databaseFile();
666
+ if (file === null || file === "" || file === ":memory:")
667
+ return false;
668
+ const registry = readProjectRegistryNow(join(dirname(file), "repos.json"));
669
+ return !("error" in registry) && registry.repos.includes(repo);
670
+ }
@@ -1,5 +1,5 @@
1
1
  import { randomBytes } from "node:crypto";
2
- import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
2
+ import { flexibleAvailable } from "./flexible-available.js";
3
3
  import { threadLevelAllowed } from "./flexible-levels.js";
4
4
  import { flexibleDelegationAtUse, FLEXIBLE_LEVEL_WORDS, FLEXIBLE_LEVELS, FLEXIBLE_UNAVAILABLE, isFlexibleLevel } from "./flexible.js";
5
5
  import { budgetHoldWords, budgetLabel, budgetStates, canPrice, countsToward, monthOf, priceWork, spendItems } from "./spend.js";
@@ -150,7 +150,7 @@ function validRequest(input) {
150
150
  && (input.opening === undefined || typeof input.opening === "boolean") && clockOk(input.clock);
151
151
  }
152
152
  export function admitFlexibleTurn(store, input) {
153
- if (!FLEXIBLE_AVAILABLE)
153
+ if (!flexibleAvailable(store))
154
154
  return refuse("not-available");
155
155
  if (!validRequest(input))
156
156
  return refuse("invalid-request");
@@ -277,7 +277,7 @@ function spendRefusal(store, repo, owner, provider, billing, terms, now, modeRea
277
277
  return budgetRefusal(store, repo, owner, provider, now);
278
278
  }
279
279
  export function beginFlexibleTurn(store, input) {
280
- if (!FLEXIBLE_AVAILABLE)
280
+ if (!flexibleAvailable(store))
281
281
  return refuse("not-available");
282
282
  if (!clockOk(input.clock))
283
283
  return refuse("invalid-request");
@@ -327,8 +327,6 @@ function priced(store, turn, usage, model) {
327
327
  return { microusd: Math.max(0, price.microusd), basis: price.source === "reported" ? "measured" : "estimated" };
328
328
  }
329
329
  export function chargeFlexibleTurn(store, input) {
330
- if (!FLEXIBLE_AVAILABLE)
331
- return refuse("not-available");
332
330
  if (!validUsage(input.usage) || (input.model !== undefined && (typeof input.model !== "string" || !MODEL.test(input.model)))
333
331
  || (input.incomplete !== undefined && typeof input.incomplete !== "boolean"))
334
332
  return refuse("invalid-request");
@@ -347,8 +345,6 @@ export function chargeFlexibleTurn(store, input) {
347
345
  });
348
346
  }
349
347
  export function finishFlexibleTurn(store, input) {
350
- if (!FLEXIBLE_AVAILABLE)
351
- return refuse("not-available");
352
348
  if ((input.outcome !== "finished" && input.outcome !== "unknown") || (input.usage !== null && !validUsage(input.usage)) || !clockOk(input.clock))
353
349
  return refuse("invalid-request");
354
350
  return store.transact(() => {
@@ -377,8 +373,6 @@ export function finishFlexibleTurn(store, input) {
377
373
  });
378
374
  }
379
375
  export function interruptFlexibleTurnsOf(store, input) {
380
- if (!FLEXIBLE_AVAILABLE)
381
- return refuse("not-available");
382
376
  if (typeof input.holder !== "string" || !KEY.test(input.holder) || !clockOk(input.clock))
383
377
  return refuse("invalid-request");
384
378
  return store.transact(() => {
@@ -407,8 +401,6 @@ export function interruptFlexibleTurnsOf(store, input) {
407
401
  const INSTALLATION_LIMITS = { liveThreads: 1000, turnsPerDay: 1_000_000, measuredMicrousdPerDay: 100_000_000 * 1_000_000 };
408
402
  const limitOk = (value, max) => value === null || (typeof value === "number" && Number.isSafeInteger(value) && value >= 1 && value <= max);
409
403
  export function setFlexibleInstallationCaps(store, input) {
410
- if (!FLEXIBLE_AVAILABLE)
411
- return refuse("not-available");
412
404
  const caps = input.caps;
413
405
  if (typeof caps !== "object" || caps === null || !limitOk(caps.liveThreads, INSTALLATION_LIMITS.liveThreads) || !limitOk(caps.turnsPerDay, INSTALLATION_LIMITS.turnsPerDay)
414
406
  || !limitOk(caps.measuredMicrousdPerDay, INSTALLATION_LIMITS.measuredMicrousdPerDay) || !clockOk(input.clock))
@@ -418,6 +410,10 @@ export function setFlexibleInstallationCaps(store, input) {
418
410
  if (account === null || account.revokedAt !== null || !store.isInstanceOperator(input.by))
419
411
  return refuse("not-an-operator");
420
412
  const before = flexibleInstallationCaps(store);
413
+ const tighter = (now, was) => now !== null && (was === null || now <= was);
414
+ if (!flexibleAvailable(store) && !(tighter(caps.liveThreads, before.liveThreads) && tighter(caps.turnsPerDay, before.turnsPerDay)
415
+ && tighter(caps.measuredMicrousdPerDay, before.measuredMicrousdPerDay)))
416
+ return refuse("not-available");
421
417
  const at = timeOf(input.clock).toISOString();
422
418
  store.handle.prepare(`INSERT INTO flexible_installation_caps (id, live_threads, turns_per_day, measured_microusd_per_day, updated_by, updated_at) VALUES (1, ?, ?, ?, ?, ?)
423
419
  ON CONFLICT (id) DO UPDATE SET live_threads = excluded.live_threads, turns_per_day = excluded.turns_per_day, measured_microusd_per_day = excluded.measured_microusd_per_day,
@@ -428,8 +424,6 @@ export function setFlexibleInstallationCaps(store, input) {
428
424
  });
429
425
  }
430
426
  export function withdrawFlexibleTurn(store, input) {
431
- if (!FLEXIBLE_AVAILABLE)
432
- return refuse("not-available");
433
427
  if (typeof input.detail !== "string" || !clockOk(input.clock))
434
428
  return refuse("invalid-request");
435
429
  return store.transact(() => {
@@ -446,8 +440,6 @@ export function withdrawFlexibleTurn(store, input) {
446
440
  });
447
441
  }
448
442
  export function interruptFlexibleThreadTurns(store, input) {
449
- if (!FLEXIBLE_AVAILABLE)
450
- return refuse("not-available");
451
443
  if (typeof input.thread !== "string" || typeof input.detail !== "string" || !clockOk(input.clock))
452
444
  return refuse("invalid-request");
453
445
  return store.transact(() => {
@@ -471,8 +463,6 @@ export function interruptFlexibleThreadTurns(store, input) {
471
463
  });
472
464
  }
473
465
  export function withdrawFlexibleTurnsAbove(store, input) {
474
- if (!FLEXIBLE_AVAILABLE)
475
- return refuse("not-available");
476
466
  if (typeof input.thread !== "string" || !isFlexibleLevel(input.level) || typeof input.detail !== "string" || !clockOk(input.clock))
477
467
  return refuse("invalid-request");
478
468
  return store.transact(() => {
@@ -488,3 +478,18 @@ export function withdrawFlexibleTurnsAbove(store, input) {
488
478
  return { ok: true, withdrawn };
489
479
  });
490
480
  }
481
+ export function interruptFlexibleTurnSignIn(store, input) {
482
+ if (typeof input.turn !== "string" || typeof input.detail !== "string" || !clockOk(input.clock))
483
+ return refuse("invalid-request");
484
+ return store.transact(() => {
485
+ const turn = flexibleTurn(store, input.turn);
486
+ if (turn === null || turn.status !== "running")
487
+ return { ok: true, interrupted: false };
488
+ const basis = turn.billing === "subscription" ? turn.costBasis ?? "unknown" : "unknown";
489
+ const done = Number(store.handle.prepare("UPDATE thread_turn SET status = 'interrupted', ended_at = ?, end_detail = ?, cost_basis = ? WHERE id = ? AND status = 'running'")
490
+ .run(timeOf(input.clock).toISOString(), input.detail.slice(0, 2000), basis, turn.id).changes) === 1;
491
+ if (done)
492
+ relayCancel({ turn: turn.id });
493
+ return { ok: true, interrupted: done };
494
+ });
495
+ }
package/dist/flexible.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { canonicalJson } from "./canonical-json.js";
3
- import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
3
+ import { flexibleAvailable } from "./flexible-available.js";
4
4
  export const FLEXIBLE_LEVELS = ["supervised", "auto", "full"];
5
5
  export const FLEXIBLE_TERMS_VERSION = 1;
6
6
  export const FLEXIBLE_DEFAULT_CAPS = Object.freeze({ liveThreads: 3, turnsPerDayProject: 300, turnsPerDayPerson: 150, measuredMicrousdPerDay: null });
@@ -170,7 +170,7 @@ export function flexibleStanding(store, repo) {
170
170
  const lapse = lapseOf(store, read.terms);
171
171
  return lapse === null ? { state: "on", ...read } : { state: "lapsed", reason: lapse, ...read };
172
172
  }
173
- export const FLEXIBLE_UNAVAILABLE = "Flexible projects aren't available in this version. Nothing changed.";
173
+ export const FLEXIBLE_UNAVAILABLE = "Interactive agent threads are off: Settings → General, or `toolroll config set flexible on`.";
174
174
  const WORDS = Object.freeze({
175
175
  "not-available": FLEXIBLE_UNAVAILABLE,
176
176
  "not-an-approver": "Only an approver for this project can do that. Nothing changed.",
@@ -231,7 +231,7 @@ function insertRow(store, row, now) {
231
231
  return Number(written.lastInsertRowid);
232
232
  }
233
233
  export function enableFlexible(store, input) {
234
- if (!FLEXIBLE_AVAILABLE)
234
+ if (!flexibleAvailable(store))
235
235
  return refuse("not-available");
236
236
  if (input.proof !== "password-now" && input.proof !== "sso-now")
237
237
  return refuse("proof-required");
@@ -255,8 +255,6 @@ export function enableFlexible(store, input) {
255
255
  });
256
256
  }
257
257
  export function lowerFlexible(store, input) {
258
- if (!FLEXIBLE_AVAILABLE)
259
- return refuse("not-available");
260
258
  if (!isFlexibleLevel(input.max))
261
259
  return refuse("invalid-choice");
262
260
  return store.transact(() => {
@@ -286,8 +284,6 @@ export function lowerFlexible(store, input) {
286
284
  });
287
285
  }
288
286
  export function turnFlexibleOff(store, input) {
289
- if (!FLEXIBLE_AVAILABLE)
290
- return refuse("not-available");
291
287
  return store.transact(() => {
292
288
  if (approverHere(store, input.by, input.repo) === null)
293
289
  return refuse("not-an-approver");
@@ -328,7 +324,7 @@ export function endLapsedFlexible(store, which, by, now) {
328
324
  }
329
325
  }
330
326
  export function flexibleDelegationAtUse(store, input) {
331
- if (!FLEXIBLE_AVAILABLE)
327
+ if (!flexibleAvailable(store))
332
328
  return refuse("not-available");
333
329
  return store.transact(() => {
334
330
  const standing = flexibleStanding(store, input.repo);
@@ -360,9 +356,11 @@ export function flexibleDelegationAtUse(store, input) {
360
356
  });
361
357
  }
362
358
  export function flexibleSettingsView(store, repo, viewer) {
363
- if (!FLEXIBLE_AVAILABLE)
359
+ const standing = flexibleStanding(store, repo);
360
+ const on = flexibleAvailable(store);
361
+ if (!on && standing.state === "secure")
364
362
  return undefined;
365
- const proposed = viewer.canChange ? proposedFlexibleTerms(store, repo, viewer.name) : refuse("not-an-approver");
366
- return { repo, standing: flexibleStanding(store, repo), canChange: viewer.canChange,
363
+ const proposed = !on ? refuse("not-available") : viewer.canChange ? proposedFlexibleTerms(store, repo, viewer.name) : refuse("not-an-approver");
364
+ return { repo, standing, canChange: viewer.canChange,
367
365
  proposal: proposed.ok ? { terms: proposed.terms, digest: proposed.digest } : { problem: proposed.message.replace(/ Nothing changed\.$/, "") } };
368
366
  }
@@ -804,7 +804,10 @@ async function checkTrigger(store, trigger, config, now, io) {
804
804
  const more = fetched.more ?? fresh.length > CARDS_PER_CHECK;
805
805
  const cursor = fetched.more !== undefined ? fetched.cursor ?? trigger.cursor : more ? due.at(-1)?.at ?? trigger.cursor : fetched.cursor ?? trigger.cursor;
806
806
  const said = results.length === 0 && fetched.said !== undefined ? fetched.said : outcomeWords(results, more);
807
- store.updateFlowTrigger(trigger.id, { failures: 0, cursor, lastAt: now.toISOString(), lastOutcome: said, nextAt: new Date(now.getTime() + POLL_EVERY_MS).toISOString() }, now);
807
+ store.transact(() => {
808
+ const moved = store.getFlowTrigger(trigger.id)?.cursor !== trigger.cursor;
809
+ store.updateFlowTrigger(trigger.id, { failures: 0, ...(moved ? {} : { cursor }), lastAt: now.toISOString(), lastOutcome: said, nextAt: new Date(now.getTime() + POLL_EVERY_MS).toISOString() }, now);
810
+ });
808
811
  return { ok: true, said, added: results.filter(one => one.made === "added").length };
809
812
  }
810
813
  async function fetchMail(store, config, trigger, io, now) {
@@ -30,6 +30,17 @@ export function pendingInputOf(pty) {
30
30
  }
31
31
  return bytes;
32
32
  }
33
+ export function dropPendingInput(pty) {
34
+ const stream = pty?._writeStream;
35
+ if (stream === undefined || !Array.isArray(stream._writeQueue))
36
+ return false;
37
+ stream._writeQueue.length = 0;
38
+ if (stream._writeImmediate !== undefined) {
39
+ clearImmediate(stream._writeImmediate);
40
+ stream._writeImmediate = undefined;
41
+ }
42
+ return true;
43
+ }
33
44
  export function loadPtySpawn() {
34
45
  try {
35
46
  const pty = createRequire(import.meta.url)("@lydell/node-pty");
@@ -46,6 +57,7 @@ export function loadPtySpawn() {
46
57
  kill: signal => native.kill(signal),
47
58
  pause: () => native.pause(),
48
59
  resume: () => native.resume(),
60
+ dropInput: () => { dropPendingInput(native); },
49
61
  };
50
62
  };
51
63
  }
@@ -311,6 +323,10 @@ export class TerminalHost {
311
323
  this.flow(session);
312
324
  });
313
325
  pty.onExit(({ exitCode, signal }) => {
326
+ try {
327
+ pty.dropInput?.();
328
+ }
329
+ catch { }
314
330
  session.pty = null;
315
331
  if (session.flowTimer !== null) {
316
332
  clearInterval(session.flowTimer);
@@ -452,6 +468,10 @@ export class TerminalHost {
452
468
  this.flow(session);
453
469
  });
454
470
  pty.onExit(({ exitCode, signal }) => {
471
+ try {
472
+ pty.dropInput?.();
473
+ }
474
+ catch { }
455
475
  session.pty = null;
456
476
  if (session.flowTimer !== null) {
457
477
  clearInterval(session.flowTimer);
@@ -731,6 +751,10 @@ export class TerminalHost {
731
751
  return found;
732
752
  };
733
753
  const signal = (found, name) => {
754
+ try {
755
+ session.pty?.dropInput?.();
756
+ }
757
+ catch { }
734
758
  const table = this.processes();
735
759
  if (table === null)
736
760
  readable = false;
@@ -764,6 +788,10 @@ export class TerminalHost {
764
788
  let cleanup = "uncertain";
765
789
  try {
766
790
  if (process.platform === "win32") {
791
+ try {
792
+ session.pty?.dropInput?.();
793
+ }
794
+ catch { }
767
795
  try {
768
796
  session.pty?.kill();
769
797
  }
@@ -37,6 +37,7 @@ export const LOCAL_OWNER_ACTS = Object.freeze([
37
37
  "agent-install",
38
38
  "change-models",
39
39
  "task-sizing-switch",
40
+ "flexible-switch",
40
41
  ]);
41
42
  const ACT_SET = new Set(LOCAL_OWNER_ACTS);
42
43
  export function localOwnerAct(value) {
package/dist/operate.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { FLEXIBLE_CANDIDATE_FIXED, FLEXIBLE_FILED_PREFIX, flexibleMergeRefusal } from "./flexible-merge-guard.js";
2
2
  import { flexibleArmedPass } from "./flexible-ship.js";
3
+ import { stopFlexibleThreadsEverywhere } from "./flexible-session.js";
3
4
  import { runCardCommand } from "./card-cli.js";
4
5
  import { mintSecret } from "./secret-mint.js";
5
6
  import { ACP_AGENTS, ACP_PROVIDER_IDS, isAcpProvider, isKeyedProvider } from "./acp-agents.js";
@@ -266,7 +267,8 @@ import { latestRelease, newerRelease, notifySecurityRelease, notifyVersionLive,
266
267
  import { installMethod } from "./install-method.js";
267
268
  import { PACKAGE_VERSION } from "./version.js";
268
269
  import { machineActing } from "./scope.js";
269
- import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
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";
270
272
  import { enableFlexible, FLEXIBLE_LAPSE_WORDS, FLEXIBLE_LEVEL_WORDS, FLEXIBLE_UNAVAILABLE, flexibleStanding, flexibleTermsWords, isFlexibleLevel, lowerFlexible, proposedFlexibleTerms, turnFlexibleOff } from "./flexible.js";
271
273
  import { reevaluateResultRecords } from "./route-results.js";
272
274
  import { holdRuleOff, routeRulesPass, taskEvidenceWords } from "./route-rules.js";
@@ -586,6 +588,14 @@ Agents — which provider and model each phase runs on
586
588
  size each new task with a quick model call (Claude Haiku, on your
587
589
  plan) before you approve; off, the default, sizes from the words alone
588
590
  and plans anything uncertain (config show task-sizing says which)
591
+ toolroll config set flexible on|off --as <you> --token <t>
592
+ interactive agent threads (beta), off by default: T in the workbench
593
+ starts a Claude Code thread inside Toolroll's sandbox, with your Claude
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
589
599
  toolroll chat --as <you> [--repo <path>…] [--say "…"] [--end]
590
600
  [--ceiling-usd <n>] [--json] (password at the prompt;
591
601
  --token <t> only for scripts — it lands in shell history)
@@ -772,6 +782,7 @@ export const OPERATE_BOOLEAN_FLAGS = new Set([
772
782
  "password-stdin",
773
783
  "now",
774
784
  "preview", "apply",
785
+ "no-check", "check",
775
786
  ]);
776
787
  const PROJECT_NETWORK_VALUE_FLAGS = new Set(["remove", "local"]);
777
788
  export function parseOperateArgs(argv, ownValues = new Set()) {
@@ -4230,6 +4241,10 @@ async function configCommand(positional, flags, context) {
4230
4241
  return quickAnswersConfig(action ?? "show", repoGiven !== undefined, flags, context);
4231
4242
  if (phase === "task-sizing")
4232
4243
  return taskSizingConfig(action ?? "show", positional[2], repoGiven !== undefined, flags, context);
4244
+ if (phase === "flexible")
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);
4233
4248
  if (action === undefined || action === "show") {
4234
4249
  const installation = store.listPhaseConfig(INSTALLATION_SCOPE);
4235
4250
  const project = scope === INSTALLATION_SCOPE ? [] : store.listPhaseConfig(scope);
@@ -8059,7 +8074,7 @@ function showTask(positional, context) {
8059
8074
  `${task.id} ${task.state}${ref.deliverable === "report" ? " (scout — delivers a report)" : ""}`,
8060
8075
  ` ${task.title}`,
8061
8076
  ...(detail.work === null ? [] : [
8062
- ` status: ${shared?.headline ?? detail.work.status.label}${shared === null ? "" : ` — ${shared.sentence}`}`,
8077
+ ` status: ${shared?.headline ?? detail.work.status.label}${shared === null ? "" : `${shared.headline === "On hold" ? " · " : " — "}${shared.sentence}`}`,
8063
8078
  ...(primaryAction === null ? [] : [` next: ${primaryAction.label}${primaryAction.target.decisionId === null ? "" : ` — decision #${primaryAction.target.decisionId}`}`]),
8064
8079
  ]),
8065
8080
  ...(task.state !== "done" || detail.proofVerdict === null
@@ -12575,8 +12590,6 @@ async function projectFlexibleCommand(positional, flags, context) {
12575
12590
  const action = positional[1] ?? "show";
12576
12591
  const command = `project flexible ${action}`;
12577
12592
  const { write, json } = context;
12578
- if (!FLEXIBLE_AVAILABLE)
12579
- return fail(write, json, command, "not-available", FLEXIBLE_UNAVAILABLE, EXIT.refused);
12580
12593
  const options = { show: [], enable: ["max", "default", "digest"], lower: ["max"], off: [] };
12581
12594
  const own = options[action];
12582
12595
  if (own === undefined || positional.length > 2)
@@ -12618,6 +12631,8 @@ async function projectFlexibleCommand(positional, flags, context) {
12618
12631
  if (acting === null)
12619
12632
  return refused(`${action === "enable" ? "Turning on Flexible needs your password" : "This needs your sign-in"}: pass --as and --token.`);
12620
12633
  if (action === "enable") {
12634
+ if (!flexibleAvailable(store))
12635
+ return fail(write, json, command, "not-available", FLEXIBLE_UNAVAILABLE, EXIT.refused);
12621
12636
  const proved = credentialApprover(store, acting.name, acting.token, repo);
12622
12637
  if (!proved.ok)
12623
12638
  return refused("Only an approver of this project, with their password typed now, turns on Flexible.");
@@ -12691,3 +12706,154 @@ async function taskSizingConfig(action, value, repoGiven, flags, context) {
12691
12706
  const shown = said();
12692
12707
  return succeed(write, json, command, shown.payload, shown.lines);
12693
12708
  }
12709
+ async function flexibleConfig(action, value, repoGiven, flags, context) {
12710
+ const { store, write, json, clock } = context;
12711
+ const command = `config ${action}`;
12712
+ if (repoGiven)
12713
+ return fail(write, json, command, "usage", "interactive agent threads are installation-wide: no --repo", EXIT.usage);
12714
+ const said = () => {
12715
+ const read = flexibleSetting(store);
12716
+ return { payload: { flexible: { on: read.on, by: read.by, at: read.at } }, lines: () => [read.on
12717
+ ? "Interactive agent threads (beta) are on: T in the workbench starts a Claude Code thread. Claude Code only for now; it runs inside Toolroll's sandbox with your Claude sign-in relayed, and Toolroll never gives the agent your key."
12718
+ : "Interactive agent threads (beta) are off. Turn them on with `toolroll config set flexible on`."] };
12719
+ };
12720
+ if (action === "show") {
12721
+ const shown = said();
12722
+ return succeed(write, json, command, shown.payload, shown.lines);
12723
+ }
12724
+ if (action !== "set" || (value !== "on" && value !== "off"))
12725
+ return fail(write, json, command, "usage", "`toolroll config set flexible on|off --as <you> --token <t>`", EXIT.usage);
12726
+ const personOnly = value === "on"
12727
+ ? "Only an instance operator, with their password typed for this command, turns interactive agent threads on; never a remembered sign-in, a token, the lead or a chat app."
12728
+ : "Only an instance operator, as a person with their password, turns interactive agent threads off; never a token, the lead or a chat app.";
12729
+ if (machineActing() || process.env["TOOLROLL_LEAD_TOKEN"] !== undefined || process.env["TOOLROLL_REMOTE_TOKEN"] !== undefined)
12730
+ return fail(write, json, command, "person-only", personOnly, EXIT.refused);
12731
+ if (passwordFreeOwner(store))
12732
+ 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);
12733
+ const acting = await askCredentials(flags, context);
12734
+ if (acting === null)
12735
+ return fail(write, json, command, "usage", "This needs your name and password: run it in your own terminal to be asked, or add `--as <your Toolroll name> --token <your password>`.", EXIT.usage);
12736
+ const saved = store.transact(() => {
12737
+ const verified = value === "on" ? credentialApprover(store, acting.name, acting.token) : authenticateApprover(store, acting.name, acting.token);
12738
+ if (!verified.ok || !personProof(verified.method) || !store.isInstanceOperator(acting.name))
12739
+ return false;
12740
+ setFlexibleSetting(store, value === "on", acting.name, clock());
12741
+ return true;
12742
+ });
12743
+ if (!saved)
12744
+ return fail(write, json, command, "unauthenticated", personOnly, EXIT.refused);
12745
+ const shown = said();
12746
+ if (value === "on")
12747
+ return succeed(write, json, command, shown.payload, shown.lines);
12748
+ const report = await stopFlexibleThreadsEverywhere(store, { reason: "interactive agent threads were turned off", clock });
12749
+ const short = (thread) => thread.slice(0, 8);
12750
+ const lines = [
12751
+ ...shown.lines(),
12752
+ ...(report.stopped.length === 0 ? [] : [`Stopped ${report.stopped.length === 1 ? "1 running thread" : `${report.stopped.length} running threads`}: every process of ${report.stopped.length === 1 ? "its agent" : "their agents"} is gone and ${report.stopped.length === 1 ? "its turn" : "their turns"} ended (${report.stopped.map(one => short(one.thread)).join(", ")}).`]),
12753
+ ...(report.stopped.some(one => one.network) ? ["The console that started them closes their network on its next check, within a few seconds."] : []),
12754
+ ...report.survivors.map(one => `Thread ${short(one.thread)} couldn't be stopped yet${one.pids.length === 0 ? "" : `: process${one.pids.length === 1 ? "" : "es"} ${one.pids.join(", ")} still running`} (${one.why}). A running console keeps trying every few seconds; run this command again to try now.`),
12755
+ ];
12756
+ return succeed(write, json, command, { ...shown.payload, stopped: report.stopped, survivors: report.survivors }, () => lines);
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
+ }
package/dist/release.js CHANGED
@@ -47,6 +47,7 @@ export const ADVISORY_PR_CHECKS = {
47
47
  "workbench bundle / binary · linux-arm64": ".github/workflows/tui-bundle.yml",
48
48
  "workbench bundle / assemble": ".github/workflows/tui-bundle.yml",
49
49
  "gate changes": ".github/workflows/gate-changes.yml",
50
+ "guard checks": ".github/workflows/guard-checks.yml",
50
51
  };
51
52
  export const RELEASE_TAG_CHECKS = ["release proof", "package / binary · darwin-arm64", "package / binary · darwin-x64", "package / binary · linux-x64", "package / binary · linux-arm64", "package / assemble", "publish"];
52
53
  export const RELEASE_TAG_WORKFLOW = ".github/workflows/publish.yml";