toolroll 0.9.112 → 0.9.113

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 (42) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +28 -29
  3. package/dist/contracts/console-api.js +2 -1
  4. package/dist/contracts/engine-api.js +12 -0
  5. package/dist/easy-start.js +4 -1
  6. package/dist/engine-reads.js +15 -0
  7. package/dist/fast-terms.js +8 -4
  8. package/dist/flexible-agents.js +2 -8
  9. package/dist/flexible-answers.js +4 -26
  10. package/dist/flexible-available.js +31 -1
  11. package/dist/flexible-import.js +2 -14
  12. package/dist/flexible-launch.js +15 -3
  13. package/dist/flexible-launcher.js +0 -5
  14. package/dist/flexible-relay.js +7 -4
  15. package/dist/flexible-session.js +123 -32
  16. package/dist/flexible-setting-schema.js +10 -0
  17. package/dist/flexible-ship.js +8 -18
  18. package/dist/flexible-start.js +2 -2
  19. package/dist/flexible-thread.js +21 -27
  20. package/dist/flexible-turns.js +7 -17
  21. package/dist/flexible.js +9 -11
  22. package/dist/flow-triggers.js +4 -1
  23. package/dist/live-terminal.js +28 -0
  24. package/dist/local-owner.js +1 -0
  25. package/dist/operate.js +60 -4
  26. package/dist/release.js +1 -0
  27. package/dist/serve.js +9 -0
  28. package/dist/server/engine-api.js +91 -27
  29. package/dist/server/mutation-key.js +6 -0
  30. package/dist/server/route-table.js +3 -0
  31. package/dist/server/settings-section-table.js +3 -0
  32. package/dist/server/settings-sections.js +23 -0
  33. package/dist/server/settings.js +36 -3
  34. package/dist/server/terminals.js +3 -3
  35. package/dist/settings-proofs.js +2 -0
  36. package/dist/store.js +18 -4
  37. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  38. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  39. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  40. package/dist/tui/linux-x64/toolroll-tui +0 -0
  41. package/dist/work-index.js +4 -0
  42. package/package.json +1 -1
@@ -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(() => {
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,7 @@ 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";
270
271
  import { enableFlexible, FLEXIBLE_LAPSE_WORDS, FLEXIBLE_LEVEL_WORDS, FLEXIBLE_UNAVAILABLE, flexibleStanding, flexibleTermsWords, isFlexibleLevel, lowerFlexible, proposedFlexibleTerms, turnFlexibleOff } from "./flexible.js";
271
272
  import { reevaluateResultRecords } from "./route-results.js";
272
273
  import { holdRuleOff, routeRulesPass, taskEvidenceWords } from "./route-rules.js";
@@ -586,6 +587,10 @@ Agents — which provider and model each phase runs on
586
587
  size each new task with a quick model call (Claude Haiku, on your
587
588
  plan) before you approve; off, the default, sizes from the words alone
588
589
  and plans anything uncertain (config show task-sizing says which)
590
+ toolroll config set flexible on|off --as <you> --token <t>
591
+ interactive agent threads (beta), off by default: T in the workbench
592
+ starts a Claude Code thread inside Toolroll's sandbox, with your Claude
593
+ sign-in relayed (config show flexible says which)
589
594
  toolroll chat --as <you> [--repo <path>…] [--say "…"] [--end]
590
595
  [--ceiling-usd <n>] [--json] (password at the prompt;
591
596
  --token <t> only for scripts — it lands in shell history)
@@ -4230,6 +4235,8 @@ async function configCommand(positional, flags, context) {
4230
4235
  return quickAnswersConfig(action ?? "show", repoGiven !== undefined, flags, context);
4231
4236
  if (phase === "task-sizing")
4232
4237
  return taskSizingConfig(action ?? "show", positional[2], repoGiven !== undefined, flags, context);
4238
+ if (phase === "flexible")
4239
+ return flexibleConfig(action ?? "show", positional[2], repoGiven !== undefined, flags, context);
4233
4240
  if (action === undefined || action === "show") {
4234
4241
  const installation = store.listPhaseConfig(INSTALLATION_SCOPE);
4235
4242
  const project = scope === INSTALLATION_SCOPE ? [] : store.listPhaseConfig(scope);
@@ -8059,7 +8066,7 @@ function showTask(positional, context) {
8059
8066
  `${task.id} ${task.state}${ref.deliverable === "report" ? " (scout — delivers a report)" : ""}`,
8060
8067
  ` ${task.title}`,
8061
8068
  ...(detail.work === null ? [] : [
8062
- ` status: ${shared?.headline ?? detail.work.status.label}${shared === null ? "" : ` — ${shared.sentence}`}`,
8069
+ ` status: ${shared?.headline ?? detail.work.status.label}${shared === null ? "" : `${shared.headline === "On hold" ? " · " : " — "}${shared.sentence}`}`,
8063
8070
  ...(primaryAction === null ? [] : [` next: ${primaryAction.label}${primaryAction.target.decisionId === null ? "" : ` — decision #${primaryAction.target.decisionId}`}`]),
8064
8071
  ]),
8065
8072
  ...(task.state !== "done" || detail.proofVerdict === null
@@ -12575,8 +12582,6 @@ async function projectFlexibleCommand(positional, flags, context) {
12575
12582
  const action = positional[1] ?? "show";
12576
12583
  const command = `project flexible ${action}`;
12577
12584
  const { write, json } = context;
12578
- if (!FLEXIBLE_AVAILABLE)
12579
- return fail(write, json, command, "not-available", FLEXIBLE_UNAVAILABLE, EXIT.refused);
12580
12585
  const options = { show: [], enable: ["max", "default", "digest"], lower: ["max"], off: [] };
12581
12586
  const own = options[action];
12582
12587
  if (own === undefined || positional.length > 2)
@@ -12618,6 +12623,8 @@ async function projectFlexibleCommand(positional, flags, context) {
12618
12623
  if (acting === null)
12619
12624
  return refused(`${action === "enable" ? "Turning on Flexible needs your password" : "This needs your sign-in"}: pass --as and --token.`);
12620
12625
  if (action === "enable") {
12626
+ if (!flexibleAvailable(store))
12627
+ return fail(write, json, command, "not-available", FLEXIBLE_UNAVAILABLE, EXIT.refused);
12621
12628
  const proved = credentialApprover(store, acting.name, acting.token, repo);
12622
12629
  if (!proved.ok)
12623
12630
  return refused("Only an approver of this project, with their password typed now, turns on Flexible.");
@@ -12691,3 +12698,52 @@ async function taskSizingConfig(action, value, repoGiven, flags, context) {
12691
12698
  const shown = said();
12692
12699
  return succeed(write, json, command, shown.payload, shown.lines);
12693
12700
  }
12701
+ async function flexibleConfig(action, value, repoGiven, flags, context) {
12702
+ const { store, write, json, clock } = context;
12703
+ const command = `config ${action}`;
12704
+ if (repoGiven)
12705
+ return fail(write, json, command, "usage", "interactive agent threads are installation-wide: no --repo", EXIT.usage);
12706
+ const said = () => {
12707
+ const read = flexibleSetting(store);
12708
+ return { payload: { flexible: { on: read.on, by: read.by, at: read.at } }, lines: () => [read.on
12709
+ ? "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."
12710
+ : "Interactive agent threads (beta) are off. Turn them on with `toolroll config set flexible on`."] };
12711
+ };
12712
+ if (action === "show") {
12713
+ const shown = said();
12714
+ return succeed(write, json, command, shown.payload, shown.lines);
12715
+ }
12716
+ if (action !== "set" || (value !== "on" && value !== "off"))
12717
+ return fail(write, json, command, "usage", "`toolroll config set flexible on|off --as <you> --token <t>`", EXIT.usage);
12718
+ const personOnly = value === "on"
12719
+ ? "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."
12720
+ : "Only an instance operator, as a person with their password, turns interactive agent threads off; never a token, the lead or a chat app.";
12721
+ if (machineActing() || process.env["TOOLROLL_LEAD_TOKEN"] !== undefined || process.env["TOOLROLL_REMOTE_TOKEN"] !== undefined)
12722
+ return fail(write, json, command, "person-only", personOnly, EXIT.refused);
12723
+ if (passwordFreeOwner(store))
12724
+ 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);
12725
+ const acting = await askCredentials(flags, context);
12726
+ if (acting === null)
12727
+ 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);
12728
+ const saved = store.transact(() => {
12729
+ const verified = value === "on" ? credentialApprover(store, acting.name, acting.token) : authenticateApprover(store, acting.name, acting.token);
12730
+ if (!verified.ok || !personProof(verified.method) || !store.isInstanceOperator(acting.name))
12731
+ return false;
12732
+ setFlexibleSetting(store, value === "on", acting.name, clock());
12733
+ return true;
12734
+ });
12735
+ if (!saved)
12736
+ return fail(write, json, command, "unauthenticated", personOnly, EXIT.refused);
12737
+ const shown = said();
12738
+ if (value === "on")
12739
+ return succeed(write, json, command, shown.payload, shown.lines);
12740
+ const report = await stopFlexibleThreadsEverywhere(store, { reason: "interactive agent threads were turned off", clock });
12741
+ const short = (thread) => thread.slice(0, 8);
12742
+ const lines = [
12743
+ ...shown.lines(),
12744
+ ...(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(", ")}).`]),
12745
+ ...(report.stopped.some(one => one.network) ? ["The console that started them closes their network on its next check, within a few seconds."] : []),
12746
+ ...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.`),
12747
+ ];
12748
+ return succeed(write, json, command, { ...shown.payload, stopped: report.stopped, survivors: report.survivors }, () => lines);
12749
+ }
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";
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,13 @@ 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 { flexibleAvailable } from "../flexible-available.js";
7
7
  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";
8
+ import { admitFlexibleThreadOwner, answerFlexibleRequest, closeFlexibleSessions, flexibleThreadChangeOf, flexibleThreadLiveOf, flexibleThreadsOf, FLEXIBLE_WAIT_MS, flexibleThreadsExist, flexibleWorkOpen, openFlexibleSessions, recoverFlexibleHolders, startFlexibleThread, settleFlexibleStops, tickFlexibleSessions, waitFlexibleThreadChange } from "../flexible-session.js";
9
9
  import { createFlexibleLauncher } from "../flexible-launcher.js";
10
10
  import { flexibleStartCard } from "../flexible-start.js";
11
11
  import { summaryLines } from "../approval-summary.js";
12
+ import { termsOfLines } from "../fast-terms.js";
12
13
  import { localActNow } from "../local-owner.js";
13
14
  import { authenticateApprover } from "../scope.js";
14
15
  import { defaultChainOf, installModeNow } from "../install-mode.js";
@@ -111,21 +112,25 @@ export function createEngineHandlers(runtime) {
111
112
  };
112
113
  return sendChecked(response, 200, "liveSessionWindow", body);
113
114
  }
114
- const flexible = (() => {
115
- if (!FLEXIBLE_AVAILABLE)
116
- return null;
115
+ let flexible = null;
116
+ let launcher = null;
117
+ const openHost = () => {
118
+ if (flexible !== null)
119
+ return flexible;
117
120
  const opened = openFlexibleSessions(store);
118
121
  if (!opened.ok)
119
122
  return null;
123
+ flexible = opened.sessions;
120
124
  void recoverFlexibleHolders(store, opened.sessions).catch(() => { });
121
- return opened.sessions;
122
- })();
123
- const launcher = (() => {
124
- if (!FLEXIBLE_AVAILABLE || flexible === null)
125
- return null;
126
125
  const made = createFlexibleLauncher(store);
127
- return "prepare" in made ? made : null;
128
- })();
126
+ launcher = "prepare" in made ? made : null;
127
+ return flexible;
128
+ };
129
+ if (flexibleAvailable(store) || flexibleWorkOpen(store))
130
+ openHost();
131
+ const threadsOn = () => flexibleAvailable(store) ? openHost() : null;
132
+ const threadsRead = () => flexible ?? (flexibleAvailable(store) || flexibleThreadsExist(store) ? openHost() : null);
133
+ let stopping = false;
129
134
  const ownedThread = (request, who, sessions, thread) => {
130
135
  if (rereadBrowser(runtime, request, who) === null)
131
136
  return null;
@@ -137,8 +142,9 @@ export function createEngineHandlers(runtime) {
137
142
  const { url, who, request, response } = ctx;
138
143
  if (who.via !== "cookie")
139
144
  return refusal(response, 403, "session");
140
- if (!FLEXIBLE_AVAILABLE || flexible === null)
141
- return refusal(response, 404, "not-available");
145
+ const flexible = threadsRead();
146
+ if (flexible === null)
147
+ return refusal(response, 404, "thread");
142
148
  const known = url.searchParams.get("known"), wait = url.searchParams.get("wait");
143
149
  const plain = new URL(url.href);
144
150
  plain.searchParams.delete("known");
@@ -174,22 +180,25 @@ export function createEngineHandlers(runtime) {
174
180
  const { url, who, request, response } = ctx;
175
181
  if (who.via !== "cookie")
176
182
  return refusal(response, 403, "session");
177
- if (!FLEXIBLE_AVAILABLE || flexible === null)
178
- return refusal(response, 404, "not-available");
179
183
  if ([...url.searchParams.keys()].length > 0)
180
184
  return refusal(response, 400, "request");
181
185
  if (rereadBrowser(runtime, request, who) === null)
182
186
  return refusal(response, 403, "session");
187
+ const on = flexibleAvailable(store);
188
+ const flexible = threadsRead();
189
+ if (flexible === null)
190
+ return sendChecked(response, 200, "liveThreads", { version: ENGINE_API_VERSION, on, threads: [] });
183
191
  const read = flexibleThreadsOf(store, flexible, { owner: who.name });
184
192
  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))
193
+ return refusal(response, 404, "thread");
194
+ const body = { version: ENGINE_API_VERSION, on, threads: read.threads.filter(one => store.accountCanAccess(who.name, one.repo))
187
195
  .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
196
  return sendChecked(response, 200, "liveThreads", body);
189
197
  }
190
198
  async function threadAnswer(ctx) {
191
199
  const { url, who, request, response, posted } = ctx;
192
- if (!FLEXIBLE_AVAILABLE || flexible === null)
200
+ const flexible = threadsOn();
201
+ if (flexible === null)
193
202
  return acted(response, 404, "refused", FLEXIBLE_UNAVAILABLE);
194
203
  if (who.via !== "cookie")
195
204
  return acted(response, 403, "refused", "Only a person signed in here can answer an agent.");
@@ -219,13 +228,17 @@ export function createEngineHandlers(runtime) {
219
228
  }
220
229
  async function threadStart(ctx) {
221
230
  const { who, request, response, posted } = ctx;
222
- if (!FLEXIBLE_AVAILABLE || flexible === null)
231
+ const flexible = threadsOn();
232
+ if (flexible === null)
223
233
  return acted(response, 404, "refused", FLEXIBLE_UNAVAILABLE);
224
234
  if (who.via !== "cookie" || rereadBrowser(runtime, request, who) === null)
225
235
  return acted(response, 403, "refused", "Only a person signed in here can start a thread.");
226
236
  if (launcher === null)
227
237
  return acted(response, 409, "refused", "This console can't give a thread its network, so no thread was started.");
228
238
  const body = readForm(posted, CONSOLE_FORMS.threadStart);
239
+ const agent = body.get("agent");
240
+ if (agent !== null && agent !== "claude")
241
+ return acted(response, 409, "refused", FLEXIBLE_CLAUDE_ONLY);
229
242
  const repo = body.get("repo") ?? "", message = body.get("message") ?? "";
230
243
  if (!store.accountCanAccess(who.name, repo))
231
244
  return acted(response, 403, "refused", "That project is outside your access.");
@@ -266,6 +279,30 @@ export function createEngineHandlers(runtime) {
266
279
  return refusal(response, 404, "task");
267
280
  return sendChecked(response, 200, "stepCards", stepCardsOf({ store, family, now: clock(), access: runtime.workAccess(), evidenceRoot, viewer: who.name }));
268
281
  }
282
+ async function taskApproval(ctx) {
283
+ const { url, response, who, request } = ctx;
284
+ if (who.via !== "cookie")
285
+ return refusal(response, 403, "session");
286
+ if (!runtime.browserKeys.terminalKeyed(who, request))
287
+ return refusal(response, 403, "key");
288
+ if ([...url.searchParams.keys()].length > 0)
289
+ return refusal(response, 400, "request");
290
+ const family = familyAt(url, "approval");
291
+ if (family === null)
292
+ return refusal(response, 404, "task");
293
+ const taskId = family.current.id;
294
+ const none = (problem) => sendChecked(response, 200, "approvalCard", { version: ENGINE_API_VERSION, task: taskId, key: null, digest: null, nonce: null, terms: [], problem });
295
+ const waits = (view) => view.nonce !== "" && view.approvalDigest != null && view.approvalSummary != null;
296
+ const view = runtime.taskViewData(taskId, who, null, { mintNonce: false });
297
+ if (view === null)
298
+ return refusal(response, 404, "task");
299
+ if (!waits(view))
300
+ return none(NOTHING_TO_APPROVE);
301
+ if (view.approvalLocal?.eligible !== true)
302
+ return none(`${view.approvalLocal?.eligible === false ? `${view.approvalLocal.message} ` : "This approval needs your password. "}${APPROVE_IN_BROWSER}`);
303
+ return sendChecked(response, 200, "approvalCard", { version: ENGINE_API_VERSION, task: taskId, key: view.approvalSummary.key, digest: view.approvalDigest,
304
+ nonce: runtime.heldApprovalNonce(who.name, taskId, view.approvalDigest), terms: approvalTermsOf(view.approvalSummary, view.planContract ?? null, view.revision ?? null), problem: null });
305
+ }
269
306
  async function taskDiff(ctx) {
270
307
  const { url, response } = ctx;
271
308
  const params = url.searchParams, runParam = params.get("run"), fileParam = params.get("file"), fromParam = params.get("from"), countParam = params.get("count");
@@ -334,29 +371,38 @@ export function createEngineHandlers(runtime) {
334
371
  return sendChecked(response, 200, "linkRedemption", body);
335
372
  }
336
373
  return {
337
- upkeep: () => { if (flexible !== null) {
374
+ upkeep: () => {
375
+ const host = flexible;
376
+ if (host === null)
377
+ return;
338
378
  try {
339
- tickFlexibleSessions(store, flexible);
379
+ tickFlexibleSessions(store, host);
340
380
  }
341
381
  catch { }
342
- } },
382
+ if (stopping)
383
+ return;
384
+ stopping = true;
385
+ void settleFlexibleStops(store, host).catch(() => { }).finally(() => { stopping = false; });
386
+ },
343
387
  close: async () => {
388
+ const host = flexible, made = launcher;
344
389
  try {
345
- if (flexible !== null)
346
- await closeFlexibleSessions(store, flexible);
390
+ if (host !== null)
391
+ await closeFlexibleSessions(store, host);
347
392
  }
348
393
  finally {
349
- await launcher?.close();
394
+ await made?.close();
350
395
  }
351
396
  },
352
397
  registrations: [
353
398
  ...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
399
  "agents.live.thread.answer": threadAnswer, "agents.live.thread.start": threadStart }),
355
- ...handlersOf("tasks", { "task.steps": taskSteps, "task.diff": taskDiff }),
400
+ ...handlersOf("tasks", { "task.steps": taskSteps, "task.approval": taskApproval, "task.diff": taskDiff }),
356
401
  ...handlersOf("people", {}, { "edge.login-link-json": redeemLink }),
357
402
  ],
358
403
  };
359
404
  }
405
+ export const FLEXIBLE_CLAUDE_ONLY = "Interactive agent threads run Claude Code only for now. Codex threads come later. Nothing was started.";
360
406
  const START_PROOFS = new Set(["password-now", "sso-now", "fresh-password", "fresh-sso", "session", "local-owner"]);
361
407
  const FRESH_PROOFS = new Set(["password-now", "sso-now", "fresh-password", "fresh-sso", "local-owner"]);
362
408
  function bodyOf(request, cap) {
@@ -376,3 +422,21 @@ function bodyOf(request, cap) {
376
422
  request.on("error", () => resolve(null));
377
423
  });
378
424
  }
425
+ export const NOTHING_TO_APPROVE = "Nothing on this task is waiting for your approval.";
426
+ export const APPROVE_IN_BROWSER = "Press w to open it in your browser.";
427
+ export function approvalTermsOf(summary, contract, revision) {
428
+ const terms = termsOfLines(summaryLines(summary));
429
+ if (contract !== null && "problem" in contract)
430
+ terms.push({ label: "Plan record", words: contract.problem });
431
+ else if (contract !== null && (contract.filed || contract.revision === true) && contract.changes.length > 0) {
432
+ const count = `${contract.changes.length} change${contract.changes.length === 1 ? "" : "s"}`;
433
+ terms.push({ label: "Plan changes", words: [contract.revision === true ? `The plan makes ${count} from your notes:` : `The plan makes ${count} to what you filed:`,
434
+ ...contract.changeWords, ...(contract.amendment === null ? [] : [`Why: ${contract.amendment}`])].join("\n") });
435
+ }
436
+ if (revision !== null && "problem" in revision)
437
+ terms.push({ label: "Sent back", words: revision.problem });
438
+ else if (revision !== null && revision.comments.length > 0) {
439
+ 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") });
440
+ }
441
+ return terms;
442
+ }
@@ -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)