toolroll 0.9.105 → 0.9.106

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/demo.js CHANGED
@@ -148,7 +148,7 @@ const DEMO_PROOF = {
148
148
  ],
149
149
  checks: [{ command: "npm test", exitCode: 0, summary: "214 tests passed, including the new rounding boundary cases." }],
150
150
  changed: ["src/payout.ts", "src/payout.test.ts"],
151
- caveats: ["The dashboard screenshot was captured against the ledger fixtures, not production data."],
151
+ caveats: [],
152
152
  screenshots: [{ path: "evidence/payout-dashboard.png", caption: "Payout dashboard after the fix — totals match the ledger." }],
153
153
  };
154
154
  const DEMO_COPY_PATCH = `diff --git a/src/inbox-copy.ts b/src/inbox-copy.ts
@@ -479,6 +479,7 @@ export function seedDemo(store, repos, evidenceRoot, now) {
479
479
  now: hoursAgo(27),
480
480
  });
481
481
  approve(store, done, "demo", hoursAgo(26), doneProposed.digest, token);
482
+ const doneCheck = store.setVerifyCommand({ repo: store.refFor("built-in", done).repo ?? repos.api, command: DEMO_CHECK_COMMAND, timeoutMs: 120_000, approvedBy: "demo" }, hoursAgo(26));
482
483
  const doneRoute = store.approvedRouteOf(done);
483
484
  const doneRun = store.startRun({
484
485
  taskRef: store.refFor("built-in", done).id,
@@ -505,11 +506,14 @@ export function seedDemo(store, repos, evidenceRoot, now) {
505
506
  ],
506
507
  filesTruncated: false,
507
508
  };
509
+ store.recordOutcomeFacts(doneRun, { headRevision: stat.head, handoff: DEMO_HANDOFF.conclusion });
508
510
  storeEvidence(store, evidenceRoot, doneRun, "diff-stat", "diff-stat.json", budgetedStatJson(stat), "parsed from git diff --numstat -z [demo: synthetic]", hoursAgo(8.5));
509
511
  storeEvidence(store, evidenceRoot, doneRun, "handoff", "handoff.json", demoHandoffBytes(store, doneRun, DEMO_HANDOFF), "composed at completion [demo: synthetic]", hoursAgo(8.4));
510
512
  storeEvidence(store, evidenceRoot, doneRun, "proof", "proof.json", Buffer.from(JSON.stringify(DEMO_PROOF, null, 2), "utf8"), "agent-authored proof (validated, re-serialized) [demo: synthetic]", hoursAgo(8.4));
511
513
  storeEvidence(store, evidenceRoot, doneRun, "screenshot", "screenshot-demo.png", DEMO_SCREENSHOT_PNG, "agent-claimed screenshot at evidence/payout-dashboard.png (validated png) [demo: synthetic]", hoursAgo(8.4));
512
- storeEvidence(store, evidenceRoot, doneRun, "check-log", "check-log.txt", Buffer.from(`$ npm test\n(exit 0)\n\n--- stdout ---\n214 tests passed.\n\n--- stderr ---\n`, "utf8"), `sh -c "npm test" (exit 0) [demo: synthetic]`, hoursAgo(8.4));
514
+ storeEvidence(store, evidenceRoot, doneRun, "check-log", "check-log.txt", Buffer.from(`=== Attempt summary ===\n- Project check · attempt 1: (exit 0)\n\n=== Project check · attempt 1 ===\n$ ${DEMO_CHECK_COMMAND}\n(exit 0)\n\n--- stdout ---\n214 tests passed.\n\n--- stderr ---\n`, "utf8"), `${DEMO_CHECK_COMMAND} (attempt recorded) [demo: synthetic]`, hoursAgo(8.4), { captureStatus: "ok" });
515
+ sealVerificationReceipt(store, evidenceRoot, doneRun, stat.head, doneCheck, { configured: true, ran: true, exitCode: 0 }, hoursAgo(8.4));
516
+ store.recordRunCheck(doneRun, { status: "passed", exitCode: 0, suites: [] }, hoursAgo(8.4));
513
517
  const demoProofParse = parseProof(JSON.stringify(DEMO_PROOF));
514
518
  const demoPngDims = imageDimensions(DEMO_SCREENSHOT_PNG, "png");
515
519
  const demoAdjudicated = adjudicate({
@@ -607,7 +611,7 @@ export function seedDemo(store, repos, evidenceRoot, now) {
607
611
  const copyStat = {
608
612
  schema: 1,
609
613
  base: "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
610
- head: "1c2d3e4f52aa01c9f3d7700e54bf8d69288fbe999",
614
+ head: "1c2d3e4f52aa01c9f3d7700e54bf8d69288fbe99",
611
615
  fileCount: 1,
612
616
  additions: 3,
613
617
  deletions: 1,
@@ -615,6 +619,7 @@ export function seedDemo(store, repos, evidenceRoot, now) {
615
619
  files: [{ path: "src/inbox-copy.ts", additions: 3, deletions: 1 }],
616
620
  filesTruncated: false,
617
621
  };
622
+ store.recordOutcomeFacts(copyReviewRun, { headRevision: copyStat.head, handoff: DEMO_COPY_HANDOFF.conclusion });
618
623
  storeEvidence(store, evidenceRoot, copyReviewRun, "diff-stat", "diff-stat.json", budgetedStatJson(copyStat), "parsed from git diff --numstat -z [demo: synthetic]", hoursAgo(3.6));
619
624
  storeEvidence(store, evidenceRoot, copyReviewRun, "handoff", "handoff.json", demoHandoffBytes(store, copyReviewRun, DEMO_COPY_HANDOFF), "composed at completion [demo: synthetic]", hoursAgo(3.5));
620
625
  storeEvidence(store, evidenceRoot, copyReviewRun, "proof", "proof.json", Buffer.from(JSON.stringify(DEMO_COPY_PROOF, null, 2), "utf8"), "agent-authored proof (validated, re-serialized) [demo: synthetic]", hoursAgo(3.5));
@@ -1,13 +1,16 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { existsSync, realpathSync } from "node:fs";
3
+ import { dirname, resolve } from "node:path";
3
4
  import { pathToFileURL } from "node:url";
4
5
  import { requestLocalLink } from "./console-instance.js";
5
6
  import { backgroundInstalled, backgroundOn, startInstalledService } from "./laptop-background.js";
6
7
  import { proveConsoleReadOnly } from "./quick-start.js";
7
- import { backgroundAsked, localModeCandidate, localModeOf, openStore, openStoreReadOnly, recordBackgroundAsked } from "./store.js";
8
+ import { backgroundAsked, installationCreatedBy, localModeCandidate, localModeOf, openStore, openStoreReadOnly, recordBackgroundAsked } from "./store.js";
8
9
  import { underAgent } from "./prompt.js";
10
+ import { savedLoginFile } from "./login-secrets.js";
9
11
  export { easyStartApplies, easyStartArgs } from "./easy-start-args.js";
10
12
  const EXIT = { ok: 0, failed: 1, usage: 2, refused: 3 };
13
+ export const START_OVER_POINTER = "This Toolroll was set up with a password. To start over without one: https://github.com/ap9000/toolroll/blob/main/docs/guide/linux.md#start-over-without-a-password";
11
14
  export async function runEasyStart(mode, args, seams) {
12
15
  const { write } = seams;
13
16
  const port = args.port === undefined || args.port === null ? null : Number(args.port);
@@ -40,11 +43,22 @@ export async function runEasyStart(mode, args, seams) {
40
43
  return (await seams.enrolled(repo)) ? EXIT.ok : seams.admit(repo);
41
44
  };
42
45
  let local = seams.localMode();
43
- if ((local === "candidate" || local === "absent") && !first.ok && first.state === "none" && await seams.initLocal())
44
- local = "on";
46
+ if ((local === "candidate" || local === "absent") && !first.ok && first.state === "none") {
47
+ const sandbox = await seams.sandbox();
48
+ if (sandbox.missing.length > 0) {
49
+ const { missingSandboxToolsWords } = await import("./sandbox-runtime.js");
50
+ for (const line of missingSandboxToolsWords(sandbox.missing))
51
+ write(line);
52
+ return EXIT.refused;
53
+ }
54
+ if (await seams.initLocal())
55
+ local = "on";
56
+ }
45
57
  if (local === "candidate")
46
58
  local = "off";
47
59
  if (local === "off") {
60
+ if (seams.passwordByLaptopStart())
61
+ write(START_OVER_POINTER);
48
62
  if (!first.ok)
49
63
  return seams.runUpForeground(rootArgs);
50
64
  const joined = await joinRepo();
@@ -104,7 +118,11 @@ export async function runEasyStart(mode, args, seams) {
104
118
  return EXIT.ok;
105
119
  };
106
120
  if (seams.localMode() !== "on") {
107
- write(`Toolroll is on ${url}. Sign in with your password.`);
121
+ const problem = (await seams.sandbox()).problem;
122
+ if (problem !== null)
123
+ write(`Toolroll can't start without a password here: ${problem}.`);
124
+ const saved = seams.savedLogin();
125
+ write(saved === null ? `Toolroll is on ${url}. Sign in with your password.` : `Toolroll is on ${url}. Your password: run \`cat -- '${saved.replaceAll("'", "'\\''")}'\``);
108
126
  await seams.openBrowser(url);
109
127
  return waitOwned();
110
128
  }
@@ -200,6 +218,31 @@ export function defaultEasyStartSeams(options) {
200
218
  stdin: process.stdin.isTTY === true, stdout: process.stdout.isTTY === true, agent: underAgent(process.env), json: false,
201
219
  remote: (await import("./local-owner.js")).localOwnerRequested(),
202
220
  }),
221
+ sandbox: async () => {
222
+ const { missingLinuxSandboxTools, sandboxRuntimeProblem } = await import("./sandbox-runtime.js");
223
+ if (process.platform !== "linux")
224
+ return { missing: [], problem: sandboxRuntimeProblem() };
225
+ const missing = missingLinuxSandboxTools();
226
+ return { missing, problem: missing.length > 0 ? null : sandboxRuntimeProblem() };
227
+ },
228
+ passwordByLaptopStart: () => {
229
+ const store = openStoreReadOnly(file);
230
+ if (store === null)
231
+ return false;
232
+ try {
233
+ return installationCreatedBy(store) === "laptop" && localModeOf(store) === null;
234
+ }
235
+ catch {
236
+ return false;
237
+ }
238
+ finally {
239
+ store.close();
240
+ }
241
+ },
242
+ savedLogin: () => {
243
+ const saved = resolve(savedLoginFile(dirname(file)));
244
+ return existsSync(saved) ? saved : null;
245
+ },
203
246
  serviceInstalled: () => backgroundInstalled(),
204
247
  startService: async () => {
205
248
  const store = openStore(file);
package/dist/flow-code.js CHANGED
@@ -6,6 +6,7 @@ import { dirname, join } from "node:path";
6
6
  import { buildCacheEnv, buildCacheFolder, checkLaunchRoot, fenceFor, linuxFenceAvailable, macosFenceAvailable, runFolders, taskBoundary, trustedWorktreeBinding, writeAllowlist } from "./agent-fence.js";
7
7
  import { readDenyPath } from "./project-sandbox.js";
8
8
  import { poolRootOf } from "./worktree.js";
9
+ import { linuxSandboxToolsWords } from "./sandbox-runtime.js";
9
10
  import { SETUP_ENV_ALLOWLIST, SETUP_ENV_DENYLIST } from "./builder.js";
10
11
  import { redactSecretLines, scanForSecrets } from "./evidence.js";
11
12
  import { scrubSecrets } from "./flow-secrets.js";
@@ -129,7 +130,7 @@ export async function flowLaunch(store, options) {
129
130
  const available = options.available ?? (() => macosFenceAvailable() || linuxFenceAvailable());
130
131
  const fenced = available();
131
132
  if (!fenced && !store.unfencedAgentsAllowed()) {
132
- return { problem: "This machine can't confine the flow's script (no macOS sandbox, no working bubblewrap), so it didn't run. Install bubblewrap, socat and ripgrep (Linux), or an instance operator allows unconfined agents with `toolroll config unconfined-agents allow`." };
133
+ return { problem: "This machine can't confine the flow's script (no macOS sandbox, no working bubblewrap), so it didn't run. Install " + linuxSandboxToolsWords() + " (Linux), or an instance operator allows unconfined agents with `toolroll config unconfined-agents allow`." };
133
134
  }
134
135
  let own;
135
136
  try {
package/dist/guides.js CHANGED
@@ -274,7 +274,7 @@ ${AUTHORITY_LINE}
274
274
  ## Install and sign-in
275
275
 
276
276
  - One command, inside the repository: \`npx toolroll up\` (or
277
- \`bunx toolroll up\`; Node 22.13+ must be installed — Bun's own
277
+ \`bunx toolroll up\`; Node 22.20+ must be installed — Bun's own
278
278
  runtime cannot host it). \`up\` mints the first login and saves it beside the
279
279
  database in \`.toolroll-secrets/up-login.txt\` (every start prints that path and the
280
280
  \`cat\` command that shows the password, never the password itself),
package/dist/invoke.js CHANGED
@@ -28,7 +28,7 @@ import { localModeOn } from "./local-owner.js";
28
28
  import { CHECK_STAMP_VERSION, EVERYWHERE, unfencedStamp } from "./check-stamp.js";
29
29
  import { CHECK_ACCESS_DEFAULT, checkAccessHere, localModeCap, narrowestAccess, narrowestNetwork, signInsAvailable } from "./check-access.js";
30
30
  import { readDenyPath } from "./project-sandbox.js";
31
- import { sandboxRuntimeWords } from "./sandbox-runtime.js";
31
+ import { linuxSandboxToolsWords, sandboxRuntimeWords } from "./sandbox-runtime.js";
32
32
  import { canonicalJson } from "./canonical-json.js";
33
33
  import { deliveredFile } from "./code-map-admission.js";
34
34
  import { buildCacheEnv, buildCacheFolder, grantFolder, writeAllowlist, WRITES_DEFAULT, CheckoutBindingError, trustedWorktreeBinding, checkoutGitEnv, HARDENED_GIT_ARGS, codexFenceArgv, fenceFor, fencedGitEnv, LEGACY_SANDBOX, launchSandboxOf, linuxFenceAvailable, macosFenceAvailable, NO_GRANTS, sandboxedSpawn, serverGrantsOf, runFolders, taskBoundary } from "./agent-fence.js";
@@ -318,7 +318,7 @@ export async function invokeAgent(store, runId, spec, invocation, options) {
318
318
  codexHome?.cleanup();
319
319
  removeAgentDatabase(isolatedDb.dir);
320
320
  return { kind: "refused", reason: "containment", providerVersion: attested?.version ?? null,
321
- diagnostic: "This machine can't confine an agent (no macOS sandbox, no working bubblewrap), so nothing was started. Install bubblewrap, socat and ripgrep (Linux), or an instance operator allows unconfined agents with `toolroll config unconfined-agents allow`." };
321
+ diagnostic: "This machine can't confine an agent (no macOS sandbox, no working bubblewrap), so nothing was started. Install " + linuxSandboxToolsWords() + " (Linux), or an instance operator allows unconfined agents with `toolroll config unconfined-agents allow`." };
322
322
  }
323
323
  let egress = null;
324
324
  let runTemp = null;
@@ -755,7 +755,7 @@ export function fencedCommands(store, runId, writes, inner, available = () => ma
755
755
  stampLaunch(store, [runId], unfencedStamp());
756
756
  return inner(file, args, options);
757
757
  }
758
- return { code: 1, stdout: "", stderr: "This machine can't confine the build's commands (no macOS sandbox, no working bubblewrap), so they didn't run. Install bubblewrap, socat and ripgrep (Linux), or an instance operator allows unconfined agents with `toolroll config unconfined-agents allow`.\n", timedOut: false, notFound: false };
758
+ return { code: 1, stdout: "", stderr: "This machine can't confine the build's commands (no macOS sandbox, no working bubblewrap), so they didn't run. Install " + linuxSandboxToolsWords() + " (Linux), or an instance operator allows unconfined agents with `toolroll config unconfined-agents allow`.\n", timedOut: false, notFound: false };
759
759
  }
760
760
  const own = realpathSync(mkdtempSync(join(checkLaunchRoot(), "so-cmd-")));
761
761
  try {
@@ -811,7 +811,7 @@ export function fencedCheckoutCommands(store, repo, checkout, inner, available =
811
811
  stampLaunch(store, stampRuns, unfencedStamp());
812
812
  return inner(file, args, options);
813
813
  }
814
- return { code: 1, stdout: "", stderr: "This machine can't confine the project's checks (no macOS sandbox, no working bubblewrap), so they didn't run. Install bubblewrap, socat and ripgrep (Linux), or an instance operator allows unconfined agents with `toolroll config unconfined-agents allow`.\n", timedOut: false, notFound: false };
814
+ return { code: 1, stdout: "", stderr: "This machine can't confine the project's checks (no macOS sandbox, no working bubblewrap), so they didn't run. Install " + linuxSandboxToolsWords() + " (Linux), or an instance operator allows unconfined agents with `toolroll config unconfined-agents allow`.\n", timedOut: false, notFound: false };
815
815
  }
816
816
  const databaseFile = store.databaseFile();
817
817
  if (databaseFile === null) {
@@ -17,11 +17,11 @@ export const LEAD_SAY_MAX = 300;
17
17
  const BATCH_LINES = 8;
18
18
  const ENDS_SQL = LEAD_ENDS.map(one => `'${one}'`).join(",");
19
19
  export const LEAD_CLAIM_SQL = `COALESCE((SELECT CASE
20
- WHEN EXISTS(SELECT 1 FROM action_ledger e WHERE e.task_id IN (SELECT m.id FROM ordered m WHERE m.root_ref = c.root_ref)
20
+ WHEN EXISTS(SELECT 1 FROM action_ledger e WHERE e.task_id IN (SELECT value FROM json_each(c.fam_ids))
21
21
  AND e.id > claim.id AND e.actor = claim.actor AND e.action IN (${ENDS_SQL})) THEN 0
22
- WHEN EXISTS(SELECT 1 FROM task_act t WHERE t.task_ref IN (SELECT m.ref_id FROM ordered m WHERE m.root_ref = c.root_ref)
22
+ WHEN EXISTS(SELECT 1 FROM task_act t WHERE t.task_ref IN (SELECT value FROM json_each(c.fam_refs))
23
23
  AND t.act IN (${DONE_ACTS_SQL}) AND t.at >= claim.at) THEN 0
24
- WHEN (SELECT MAX(a.at) FROM action_ledger a WHERE a.task_id IN (SELECT m.id FROM ordered m WHERE m.root_ref = c.root_ref)
24
+ WHEN (SELECT MAX(a.at) FROM action_ledger a WHERE a.task_id IN (SELECT value FROM json_each(c.fam_ids))
25
25
  AND a.id >= claim.id AND a.actor = claim.actor) > $leadIdleSince THEN 1 ELSE 2 END
26
26
  FROM action_ledger claim WHERE claim.id = (SELECT MAX(id) FROM action_ledger WHERE task_id = c.root_id AND action = '${LEAD_CLAIMED}' AND actor = $leadOf)), 0)`;
27
27
  function familyOf(store, taskId) {
package/dist/operate.js CHANGED
@@ -198,6 +198,7 @@ import { mintCoordinator, revokeCoordinator, listCoordinators } from "./coordina
198
198
  import { serveMcp } from "./mcp.js";
199
199
  import { createInterface } from "node:readline";
200
200
  import { hashPassword } from "./scope.js";
201
+ import { noticeDueOnce, CONTAINMENT_NOTICE_FACT } from "./store.js";
201
202
  import { propose, approve, addApprover, authenticateAccount, authenticateApprover as passwordApprover, describeScope, approvalOf, hashToken as hashApproverToken, modeFilingCoverage, acceptanceLinesToInput, parseAcceptanceCriteria, splitAcceptanceRubric, rubricIsPlaceholder, isCommitSha, credentialProof, rememberedLogin, personApprovalOf } from "./scope.js";
202
203
  import { CHAT_APPROVE_ALL, presetTerms, modeTermsJson, modeDigestOf, modeTermsFromJson, modeWords, MODE_MAX_DAYS } from "./modes.js";
203
204
  import { WorktreePool } from "./worktree.js";
@@ -10748,9 +10749,15 @@ async function runUpWorkerRole(context, config, port, build) {
10748
10749
  const prefix = (repo) => (activeRepos.size > 1 ? `[${projectName(repo)}] ` : "");
10749
10750
  const containmentDetail = config.verbose || !config.terminal;
10750
10751
  let containmentSaid = false;
10752
+ const firstContainmentNotice = () => { try {
10753
+ return noticeDueOnce(context.store, CONTAINMENT_NOTICE_FACT, clock());
10754
+ }
10755
+ catch {
10756
+ return true;
10757
+ } };
10751
10758
  const containmentLines = (effective) => {
10752
10759
  const notice = containmentNotice(effective);
10753
- if (notice !== null && !containmentSaid)
10760
+ if (notice !== null && !containmentSaid && (containmentDetail || firstContainmentNotice()))
10754
10761
  progress(notice);
10755
10762
  containmentSaid = true;
10756
10763
  return containmentDetail || effective.refusal !== null ? [`watch: ${describeContainment(effective)}`] : [];
@@ -1,7 +1,7 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { existsSync, mkdirSync, readFileSync } from "node:fs";
2
+ import { accessSync, constants as fsConstants, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
3
3
  import { createRequire } from "node:module";
4
- import { dirname, join } from "node:path";
4
+ import { delimiter, dirname, join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { wrapCommandWithSandboxMacOS } from "@anthropic-ai/sandbox-runtime/dist/sandbox/macos-sandbox-utils.js";
7
7
  import { checkLinuxDependencies, getLinuxDependencyStatus } from "@anthropic-ai/sandbox-runtime/dist/sandbox/linux-sandbox-utils.js";
@@ -27,6 +27,9 @@ export function sandboxRuntimeProblem(platform = process.platform) {
27
27
  return probe.status === 0 ? null : "sandbox-exec can't start a sandbox here (is this already inside one?)";
28
28
  }
29
29
  if (platform === "linux") {
30
+ const missing = missingLinuxSandboxTools();
31
+ if (missing.length > 0)
32
+ return `${toolWords(missing)} ${missing.length === 1 ? "is" : "are"} not installed (${linuxSandboxInstallLine(missing)})`;
30
33
  const checked = checkLinuxDependencies();
31
34
  if (checked.errors.length > 0)
32
35
  return checked.errors.join("; ");
@@ -39,6 +42,37 @@ export function sandboxRuntimeProblem(platform = process.platform) {
39
42
  }
40
43
  return `the sandbox runtime has no sandbox for ${platform}`;
41
44
  }
45
+ export const LINUX_SANDBOX_TOOLS = [
46
+ { command: "bwrap", package: "bubblewrap" },
47
+ { command: "socat", package: "socat" },
48
+ { command: "rg", package: "ripgrep" },
49
+ ];
50
+ function toolWords(packages) {
51
+ return packages.length <= 1 ? packages.join("") : `${packages.slice(0, -1).join(", ")} and ${packages.at(-1)}`;
52
+ }
53
+ export function missingLinuxSandboxTools(path = process.env["PATH"] ?? "") {
54
+ const folders = path.split(delimiter).filter(folder => folder !== "");
55
+ const found = (command) => folders.some(folder => {
56
+ try {
57
+ accessSync(join(folder, command), fsConstants.X_OK);
58
+ return statSync(join(folder, command)).isFile();
59
+ }
60
+ catch {
61
+ return false;
62
+ }
63
+ });
64
+ return LINUX_SANDBOX_TOOLS.filter(tool => !found(tool.command)).map(tool => tool.package);
65
+ }
66
+ export function linuxSandboxInstallLine(packages = LINUX_SANDBOX_TOOLS.map(tool => tool.package)) {
67
+ return `sudo apt install ${packages.join(" ")} (Fedora: sudo dnf install ${packages.join(" ")})`;
68
+ }
69
+ export const linuxSandboxToolsWords = () => toolWords(LINUX_SANDBOX_TOOLS.map(tool => tool.package));
70
+ export function missingSandboxToolsWords(missing) {
71
+ return [
72
+ `Toolroll needs ${toolWords(missing)} to run agents in a sandbox on this computer.`,
73
+ `Install ${missing.length === 1 ? "it" : "them"}, then run toolroll again: ${linuxSandboxInstallLine(missing)}`,
74
+ ];
75
+ }
42
76
  export function shellQuote(words) {
43
77
  return words.map(word => /^[A-Za-z0-9_@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`).join(" ");
44
78
  }
package/dist/store.js CHANGED
@@ -18656,3 +18656,7 @@ function viewPreferenceShapeProblem(db) {
18656
18656
  const want = canonicalDdl(V160_SCHEMA.trim().replace(/;$/, "")).trim();
18657
18657
  return canonicalDdl(String(row["sql"])).trim() === want ? null : "the view_preference table has an unknown shape";
18658
18658
  }
18659
+ export const CONTAINMENT_NOTICE_FACT = "containment-notice-shown";
18660
+ export function noticeDueOnce(store, key, now) {
18661
+ return Number(store.handle.prepare("INSERT OR IGNORE INTO installation_fact (key, value, created_at) VALUES (?, 'yes', ?)").run(key, now.toISOString()).changes) === 1;
18662
+ }
@@ -17,7 +17,14 @@ toolroll update --yes update: verify, let running work finish, back up
17
17
  --at HH:MM wait until then (e.g. --at 03:00)
18
18
  --allow-downgrade with --version, go back to an older release
19
19
  toolroll update --rollback [--yes] return to the previous version and its database backup
20
- toolroll update --status | --resume | --cancel`;
20
+ toolroll update --status | --resume | --cancel
21
+ Releases 0.9.105 and earlier don't start on a Node whose SQLite is 3.54 or newer (Node 22.23, 24.22, 26.13 and later).`;
22
+ export function oldReleaseProblem(target, sqlite) {
23
+ const [major = 0, minor = 0] = (sqlite ?? "").split(".").map(part => Number.parseInt(part, 10) || 0);
24
+ if ((major < 3 || (major === 3 && minor < 54)) || isNewer(target, "0.9.105"))
25
+ return null;
26
+ return `Toolroll ${target} can't start on this Node: its SQLite (${sqlite}) refuses that release's Tasks list ("VIEWs and/or subqueries nested too deep"). Releases 0.9.105 and earlier need a Node whose SQLite is older than 3.54, such as Node 22.22.0.`;
27
+ }
21
28
  export async function runUpdateCommand(args, write, deps = {}) {
22
29
  const has = (name) => args.includes(`--${name}`);
23
30
  const value = (name) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined; };
@@ -91,6 +98,11 @@ export async function runUpdateCommand(args, write, deps = {}) {
91
98
  write("There is no completed update to roll back.");
92
99
  return 1;
93
100
  }
101
+ const old = oldReleaseProblem(last.from.version, deps.sqlite ?? process.versions.sqlite);
102
+ if (old !== null) {
103
+ write(old);
104
+ return 1;
105
+ }
94
106
  if (!has("yes")) {
95
107
  write(`Roll back ${last.to.version} → ${last.from.version}, with the database as it was before the update (${last.finishedAt?.slice(0, 16).replace("T", " ") ?? "unknown"} UTC).`);
96
108
  const since = recordsSince(databaseFile, last.finishedAt ?? last.updatedAt);
@@ -122,6 +134,11 @@ export async function runUpdateCommand(args, write, deps = {}) {
122
134
  write(`Toolroll ${version} is older than ${current.version}. Add --allow-downgrade to go back to it.`);
123
135
  return 1;
124
136
  }
137
+ const old = downgrade ? oldReleaseProblem(version, deps.sqlite ?? process.versions.sqlite) : null;
138
+ if (old !== null) {
139
+ write(old);
140
+ return 1;
141
+ }
125
142
  if (!has("yes")) {
126
143
  write(`Update Toolroll ${current.version} → ${version}.`);
127
144
  write(`${when === "now" ? "Refuses if any work is running" : when === "at" ? `Waits until ${at}, then pauses new work and lets running work finish` : "Pauses new work and lets running work finish"}; verifies the package came from ap9000/toolroll's publish workflow; backs up and rehearses the database; keeps ${current.version} for toolroll update --rollback.`);
package/dist/tui.js CHANGED
@@ -67,7 +67,7 @@ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#isr
67
67
  `))}patchConsole(){this.options.debug||(this.restoreConsole=_c((u,a)=>{u==="stdout"&&this.writeToStdout(a),u==="stderr"&&(a.startsWith("The above error occurred")||this.writeToStderr(a))}))}initKittyKeyboard(){if(!this.options.kittyKeyboard)return;let u=this.options.kittyKeyboard,a=u.mode??"auto";if(a==="disabled"||!this.options.stdin.isTTY||!this.options.stdout.isTTY)return;let l=u.flags??["disambiguateEscapeCodes"];if(a==="enabled"){this.enableKittyProtocol(l);return}let g=Ui.env.TERM??"",E=Ui.env.TERM_PROGRAM??"",s="KITTY_WINDOW_ID"in Ui.env||g==="xterm-kitty"||E==="WezTerm"||E==="ghostty";!qe&&s&&this.confirmKittySupport(l)}confirmKittySupport(u){let{stdin:a,stdout:l}=this.options,g=[],E=()=>{this.cancelKittyDetection=void 0,clearTimeout(I),a.removeListener("data",s);let Q=Cy(g);g=[],Q.length>0&&a.unshift(Buffer.from(Q))},s=Q=>{let y=typeof Q=="string"?Buffer.from(Q):Q;for(let v of y)g.push(v);cy(g)&&(E(),this.isUnmounted||this.enableKittyProtocol(u))};a.on("data",s);let I=setTimeout(E,200);this.cancelKittyDetection=E,l.write("\x1B[?u")}enableKittyProtocol(u){this.options.stdout.write(`\x1B[>${_Q(u)}u`),this.kittyProtocolEnabled=!0}};var Qy=(e,u)=>{let a={stdout:Uo.stdout,stdin:Uo.stdin,stderr:Uo.stderr,debug:!1,exitOnCtrlC:!0,patchConsole:!0,maxFps:30,incrementalRendering:!1,concurrent:!1,...fy(u)},l=Dy(a.stdout,()=>new za(a),a.concurrent??!1);return l.render(e),{rerender:l.render,unmount(){l.unmount()},waitUntilExit:l.waitUntilExit,cleanup:()=>Hi.delete(a.stdout),clear:l.clear}},TE=Qy,fy=(e={})=>e instanceof Iy?{stdout:e,stdin:Uo.stdin}:e,Dy=(e,u,a)=>{let l=Hi.get(e);return l?l.isConcurrent!==a&&console.warn(`Warning: render() was called with concurrent: ${a}, but the existing instance for this stdout uses concurrent: ${l.isConcurrent}. The concurrent option only takes effect on the first render. Call unmount() first if you need to change the rendering mode.`):(l=u(),Hi.set(e,l)),l};var dy=aA(Zl(),1);var To=aA(SA(),1);var XQ=aA(SA(),1);var py=aA(SA(),1);var my=aA(SA(),1);var LE=aA(SA(),1);import{Buffer as hy}from"node:buffer";var yy=/^(?:\x1b)([a-zA-Z0-9])$/,Sy=/^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/,jQ={OP:"f1",OQ:"f2",OR:"f3",OS:"f4","[11~":"f1","[12~":"f2","[13~":"f3","[14~":"f4","[[A":"f1","[[B":"f2","[[C":"f3","[[D":"f4","[[E":"f5","[15~":"f5","[17~":"f6","[18~":"f7","[19~":"f8","[20~":"f9","[21~":"f10","[23~":"f11","[24~":"f12","[A":"up","[B":"down","[C":"right","[D":"left","[E":"clear","[F":"end","[H":"home",OA:"up",OB:"down",OC:"right",OD:"left",OE:"clear",OF:"end",OH:"home","[1~":"home","[2~":"insert","[3~":"delete","[4~":"end","[5~":"pageup","[6~":"pagedown","[[5~":"pageup","[[6~":"pagedown","[7~":"home","[8~":"end","[a":"up","[b":"down","[c":"right","[d":"left","[e":"clear","[2$":"insert","[3$":"delete","[5$":"pageup","[6$":"pagedown","[7$":"home","[8$":"end",Oa:"up",Ob:"down",Oc:"right",Od:"left",Oe:"clear","[2^":"insert","[3^":"delete","[5^":"pageup","[6^":"pagedown","[7^":"home","[8^":"end","[Z":"tab"},VQ=[...Object.values(jQ),"backspace"],Fy=e=>["[a","[b","[c","[d","[e","[2$","[3$","[5$","[6$","[7$","[8$","[Z"].includes(e),Ny=e=>["Oa","Ob","Oc","Od","Oe","[2^","[3^","[5^","[6^","[7^","[8^"].includes(e),WQ=/^\x1b\[(\d+)(?:;(\d+)(?::(\d+))?(?:;([\d:]+))?)?u$/,Ry=/^\x1b\[(\d+);(\d+):(\d+)([A-Za-z~])$/,vy={A:"up",B:"down",C:"right",D:"left",E:"clear",F:"end",H:"home",P:"f1",Q:"f2",R:"f3",S:"f4"},wy={2:"insert",3:"delete",5:"pageup",6:"pagedown",7:"home",8:"end",11:"f1",12:"f2",13:"f3",14:"f4",15:"f5",17:"f6",18:"f7",19:"f8",20:"f9",21:"f10",23:"f11",24:"f12"},ZQ={27:"escape",9:"tab",127:"delete",8:"backspace",57358:"capslock",57359:"scrolllock",57360:"numlock",57361:"printscreen",57362:"pause",57363:"menu",57376:"f13",57377:"f14",57378:"f15",57379:"f16",57380:"f17",57381:"f18",57382:"f19",57383:"f20",57384:"f21",57385:"f22",57386:"f23",57387:"f24",57388:"f25",57389:"f26",57390:"f27",57391:"f28",57392:"f29",57393:"f30",57394:"f31",57395:"f32",57396:"f33",57397:"f34",57398:"f35",57399:"kp0",57400:"kp1",57401:"kp2",57402:"kp3",57403:"kp4",57404:"kp5",57405:"kp6",57406:"kp7",57407:"kp8",57408:"kp9",57409:"kpdecimal",57410:"kpdivide",57411:"kpmultiply",57412:"kpsubtract",57413:"kpadd",57414:"kpenter",57415:"kpequal",57416:"kpseparator",57417:"kpleft",57418:"kpright",57419:"kpup",57420:"kpdown",57421:"kppageup",57422:"kppagedown",57423:"kphome",57424:"kpend",57425:"kpinsert",57426:"kpdelete",57427:"kpbegin",57428:"mediaplay",57429:"mediapause",57430:"mediaplaypause",57431:"mediareverse",57432:"mediastop",57433:"mediafastforward",57434:"mediarewind",57435:"mediatracknext",57436:"mediatrackprevious",57437:"mediarecord",57438:"lowervolume",57439:"raisevolume",57440:"mutevolume",57441:"leftshift",57442:"leftcontrol",57443:"leftalt",57444:"leftsuper",57445:"lefthyper",57446:"leftmeta",57447:"rightshift",57448:"rightcontrol",57449:"rightalt",57450:"rightsuper",57451:"righthyper",57452:"rightmeta",57453:"isoLevel3Shift",57454:"isoLevel5Shift"},PQ=e=>e>=0&&e<=1114111&&!(e>=55296&&e<=57343),bE=e=>PQ(e)?String.fromCodePoint(e):"?";function $Q(e){return e===3?"release":e===2?"repeat":"press"}function Af(e){return{ctrl:!!(e&We.ctrl),shift:!!(e&We.shift),meta:!!(e&We.meta),option:!!(e&We.alt),super:!!(e&We.super),hyper:!!(e&We.hyper),capsLock:!!(e&We.capsLock),numLock:!!(e&We.numLock)}}var Gy=e=>{let u=WQ.exec(e);if(!u)return null;let a=parseInt(u[1],10),l=u[2]?Math.max(0,parseInt(u[2],10)-1):0,g=u[3]?parseInt(u[3],10):1,E=u[4];if(!PQ(a))return null;let s;E&&(s=E.split(":").map(y=>bE(parseInt(y,10))).join(""));let I,Q;return a===32?(I="space",Q=!0):a===13?(I="return",Q=!0):ZQ[a]?(I=ZQ[a],Q=!1):a>=1&&a<=26?(I=String.fromCodePoint(a+96),Q=!1):(I=bE(a).toLowerCase(),Q=!0),Q&&!s&&(s=bE(a)),{name:I,...Af(l),eventType:$Q(g),sequence:e,raw:e,isKittyProtocol:!0,isPrintable:Q,text:s}},My=e=>{let u=Ry.exec(e);if(!u)return null;let a=parseInt(u[1],10),l=Math.max(0,parseInt(u[2],10)-1),g=parseInt(u[3],10),E=u[4],s=E==="~"?wy[a]:vy[E];return s?{name:s,...Af(l),eventType:$Q(g),sequence:e,raw:e,isKittyProtocol:!0,isPrintable:!1}:null},xy=(e="")=>{let u;hy.isBuffer(e)?e[0]>127&&e[1]===void 0?(e[0]-=128,e="\x1B"+String(e)):e=String(e):e!==void 0&&typeof e!="string"?e=String(e):e||(e="");let a=Gy(e);if(a)return a;let l=My(e);if(l)return l;if(WQ.test(e))return{name:"",ctrl:!1,meta:!1,shift:!1,option:!1,sequence:e,raw:e,isKittyProtocol:!0,isPrintable:!1};let g={name:"",ctrl:!1,meta:!1,shift:!1,option:!1,sequence:e,raw:e};if(g.sequence=g.sequence||e||g.name,e==="\r"||e==="\x1B\r")g.raw=void 0,g.name="return",g.option=e.length===2;else if(e===`
68
68
  `)g.name="enter";else if(e===" ")g.name="tab";else if(e==="\b"||e==="\x1B\b")g.name="backspace",g.meta=e.charAt(0)==="\x1B";else if(e===""||e==="\x1B")g.name="delete",g.meta=e.charAt(0)==="\x1B";else if(e==="\x1B"||e==="\x1B\x1B")g.name="escape",g.meta=e.length===2;else if(e===" "||e==="\x1B ")g.name="space",g.meta=e.length===2;else if(e.length===1&&e<="")g.name=String.fromCharCode(e.charCodeAt(0)+97-1),g.ctrl=!0;else if(e.length===1&&e>="0"&&e<="9")g.name="number";else if(e.length===1&&e>="a"&&e<="z")g.name=e;else if(e.length===1&&e>="A"&&e<="Z")g.name=e.toLowerCase(),g.shift=!0;else if(u=yy.exec(e))g.meta=!0,g.shift=/^[A-Z]$/.test(u[1]);else if(u=Sy.exec(e)){let E=[...e];E[0]==="\x1B"&&E[1]==="\x1B"&&(g.option=!0);let s=[u[1],u[2],u[4],u[6]].filter(Boolean).join(""),I=(u[3]||u[5]||1)-1;g.ctrl=!!(I&4),g.meta=!!(I&10),g.shift=!!(I&1),g.code=s,g.name=jQ[s],g.shift=Fy(s)||g.shift,g.ctrl=Ny(s)||g.ctrl}return g},tf=xy;var ef=aA(SA(),1);var Hy=()=>(0,ef.useContext)(Ro),bo=Hy;var Uy=(e,u={})=>{let{stdin:a,setRawMode:l,internal_exitOnCtrlC:g,internal_eventEmitter:E}=bo();(0,LE.useEffect)(()=>{if(u.isActive!==!1)return l(!0),()=>{l(!1)}},[u.isActive,l]),(0,LE.useEffect)(()=>{if(u.isActive===!1)return;let s=I=>{let Q=tf(I),y={upArrow:Q.name==="up",downArrow:Q.name==="down",leftArrow:Q.name==="left",rightArrow:Q.name==="right",pageDown:Q.name==="pagedown",pageUp:Q.name==="pageup",home:Q.name==="home",end:Q.name==="end",return:Q.name==="return",escape:Q.name==="escape",ctrl:Q.ctrl,shift:Q.shift,tab:Q.name==="tab",backspace:Q.name==="backspace",delete:Q.name==="delete",meta:Q.meta||Q.name==="escape"||Q.option,super:Q.super??!1,hyper:Q.hyper??!1,capsLock:Q.capsLock??!1,numLock:Q.numLock??!1,eventType:Q.eventType},v;Q.isKittyProtocol?Q.isPrintable?v=Q.text??Q.name:Q.ctrl&&Q.name.length===1?v=Q.name:v="":Q.ctrl?v=Q.name:v=Q.sequence,!Q.isKittyProtocol&&VQ.includes(Q.name)&&(v=""),v.startsWith("\x1B")&&(v=v.slice(1)),v.length===1&&typeof v[0]=="string"&&/[A-Z]/.test(v[0])&&(y.shift=!0),(!(v==="c"&&y.ctrl)||!g)&&fe.batchedUpdates(()=>{e(v,y)})};return E?.on("input",s),()=>{E?.removeListener("input",s)}},[u.isActive,a,g,e])},OE=Uy;var nf=aA(SA(),1);var Ty=()=>(0,nf.useContext)(No),kE=Ty;var by=aA(SA(),1);var Ly=aA(SA(),1);var JE=aA(SA(),1);var Oy=aA(SA(),1);var ky=aA(SA(),1);var Lo=aA(SA(),1);import{pathToFileURL as $y}from"node:url";var Jy=["[data-ink-approve]",'[data-ink-act="accept"]',"[data-accept-result][data-primary-action]"],Ky=['[data-act="request-changes"]','[data-act="revise"]','a.result-feedback-link[href="#request-changes"]'],Yy=['[data-act="retry"]','form[data-retry] button[type="submit"]','form[data-rebuild] button[type="submit"]'],_y=['form[action$="/plan"] button[type="submit"]'],KE=[{keys:"n",says:"new task",web:{kind:"go",href:"/tasks/new"},tui:"new"},{keys:"a",says:"Approve or Accept (presses the button on the page)",web:{kind:"press",selectors:Jy},tui:"ink"},{keys:"b",says:"Send back (opens its note)",web:{kind:"press",selectors:Ky},tui:"send-back"},{keys:"r",says:"Retry (presses the button on the page)",web:{kind:"press",selectors:Yy},tui:"retry"},{keys:"p",says:"Ask for a plan (presses the button on the page)",web:{kind:"press",selectors:_y},tui:"plan"},{keys:"/",says:"search",web:{kind:"search"},tui:{none:"The terminal has no search; press w to open the console."}},{keys:"g h",says:"go Home",web:{kind:"go",href:"/"},tui:"list"},{keys:"g t",says:"go to Tasks",web:{kind:"go",href:"/tasks"},tui:"list"},{keys:"?",says:"these shortcuts",web:{kind:"help"},tui:"help"}],uf=e=>e.split(" ").join(" then ");var PA=aA(SA(),1);var zy=/[‪-‮⁦-⁩]/g;function qy(e){return e.replace(/(?:\x1b\[|\u009b)[0-?]*[ -/]*[@-~]/g,"").replace(/(?:\x1b\]|\u009d)[^\x07\x1b\u009c]*(?:\x07|\x1b\\|\u009c)?/g,"").replace(/\x1b[ -/]*[0-~]/g,"").replace(/\t/g," ").replace(/[\x00-\x1f\x7f-\x9f]/g,"").replace(new RegExp("\\p{Cf}","gu"),"").replace(zy,"")}function af(e){return e.split(`
69
69
  `).map(qy).join(`
70
- `)}var YE=["you","working","done"],lf={you:"Waiting on you",working:"Working",done:"Done"};var L=aA(qa(),1);function RA({children:e,...u}){return(0,L.jsx)(eA,{...u,children:af(e)})}var jy={new:"new task",ink:"approve the plan (shows it in full first)","send-back":"send the result back",retry:"retry",plan:"ask for a plan",list:"back to the task list",help:"these keys"},Vy=["j / k or ↑ / ↓ move","Enter open the task",...[...KE.filter(e=>typeof e.tui=="string").reduce((e,u)=>e.set(u.tui,[...e.get(u.tui)??[],uf(u.keys)]),new Map)].flatMap(([e,u])=>[`${u.join(", ").padEnd(15)} ${jy[e]}`,...e==="ink"?["c accept the result (shows it first)"]:[]]),"s stop the running attempt","1–9 answer the task's question","w open in the browser","Esc back","q quit"];function Wy(e){let u=a=>a.group===null?YE.length:YE.indexOf(a.group);return e.map((a,l)=>({row:a,index:l})).sort((a,l)=>u(a.row)-u(l.row)||a.index-l.index).map(a=>a.row)}var Py=e=>e.group===null?"Other":lf[e.group],Ef=e=>[...e].filter(u=>u>=" "&&u!=="").join("");function sf({source:e,session:u,onExit:a,pollMs:l=1e3}){let{exit:g}=kE(),[E,s]=(0,PA.useState)(null),[I,Q]=(0,PA.useState)(null),[y,v]=(0,PA.useState)(0),[w,p]=(0,PA.useState)({kind:"main"}),[M,U]=(0,PA.useState)(null),[J,H]=(0,PA.useState)(null),[P,FA]=(0,PA.useState)([]),NA=(0,PA.useRef)(null),gA=(0,PA.useRef)(0),xA=(0,PA.useRef)(!1),vA=Wy(E?.rows??[]),QA=vA[Math.min(y,Math.max(vA.length-1,0))],LA=(0,PA.useCallback)(async()=>{let N=await e.snapshot();s(N),N.rows.length===0&&Q(await e.setup())},[e]);(0,PA.useEffect)(()=>{LA()},[LA]),(0,PA.useEffect)(()=>{let N=setInterval(()=>{gA.current+=1;let S=e.changed();(S!==NA.current||gA.current%5===0)&&(NA.current=S,LA())},l);return()=>clearInterval(N)},[e,LA,l]);let yt=QA?.id??null;(0,PA.useEffect)(()=>{if(yt===null){FA([]);return}FA(e.live(yt));let N=setInterval(()=>FA(e.live(yt)),l);return()=>clearInterval(N)},[e,yt,l]);let Ht=N=>{xA.current||(xA.current=!0,g(),a?.(N))},Xt=(0,PA.useRef)(!1),OA=async N=>{H("Working…");try{let S=await e.act(N);return S.ok?(U(S.message),await LA(),N.kind==="new"&&u.shouldAskBackground()&&p({kind:"background"}),!0):(S.needsPassword?p({kind:"password",message:S.message}):U(S.message),!1)}finally{H(null)}},Bt=async(N,S)=>{let O=await e.task(N);O===null?U("That task can't be read now."):S(O)},Ut=N=>Bt(N,S=>{S.plan===null?U("No plan is waiting for your approval on this task."):p({kind:"approve",task:S})}),St=async(N,S=!1)=>{let O=await e.result(N);if(O===null){U("This task has no finished result to accept.");return}p({kind:"accept",result:O,reason:"",changed:S})},Tt=N=>Bt(N,S=>{S.plan!==null?p({kind:"approve",task:S}):S.hasResult?St(N):U("No plan or result is waiting for you on this task.")}),Ot=async(N,S,O)=>{H("Working…");let X;try{X=await e.act({kind:"complete",id:N.id,runId:N.runId,digest:N.digest,checked:S,reason:O})}finally{H(null)}if(X.ok){U(X.message),p({kind:"main"}),await LA();return}if(X.changed===!0){p({kind:"main"}),U("This result changed while you were reading it. Nothing was accepted."),await St(N.id,!0);return}X.needsPassword?p({kind:"password",message:X.message}):(U(X.message),p({kind:"main"}))},GA=N=>Bt(N,S=>{S.retry==null?U("Nothing to retry on this task."):p({kind:"retry",task:S,retry:S.retry})}),Dt=N=>Bt(N,S=>{S.planAsk==null?U("This task can't be planned now."):OA({kind:"plan",id:N,source:S.planAsk.source})}),He=(N,S)=>{if(S===null){U("Nothing is running on this task.");return}OA({kind:"stop",id:N,runId:S})},Ue=(N,S)=>{let O=N.decisions[0],X=O?.options[S];O===void 0||X===void 0||OA({kind:"answer",decision:O.id,option:X.id}).then(W=>{W&&p({kind:"main"})})},Zt=()=>{H("Opening the browser…"),u.openBrowser().then(N=>{U(N),H(null)})},de=()=>{u.owned()?p({kind:"quit"}):Ht("leave")},kt=(N,S,O)=>{if(Xt.current&&(Xt.current=!1,N==="h"||N==="t"))return p({kind:"main"}),!0;if(N==="g")return Xt.current=!0,!0;if(N==="/"){let X=KE.find(W=>W.keys==="/").tui;return U(typeof X=="string"?null:X.none),!0}return N==="n"?(p({kind:"compose",purpose:"new",id:null,text:"",project:0}),!0):N==="w"?(Zt(),!0):N==="?"?(p({kind:"help"}),!0):N==="q"?(de(),!0):S===null?!1:N==="a"?(Tt(S),!0):N==="s"?(He(S,O),!0):N==="b"?(p({kind:"compose",purpose:"revise",id:S,text:"",project:0}),!0):N==="r"?(GA(S),!0):N==="c"?(St(S),!0):N==="p"?(Dt(S),!0):!1},XA=(N,S)=>{if(J===null){if(S.ctrl&&N==="c"){de();return}switch(w.kind){case"main":{if(N==="j"||S.downArrow){v(O=>Math.min(O+1,Math.max(vA.length-1,0)));return}if(N==="k"||S.upArrow){v(O=>Math.max(O-1,0));return}if(S.return&&QA!==void 0){Bt(QA.id,O=>p({kind:"task",task:O}));return}if(S.escape){U(null);return}kt(N,QA?.id??null,QA?.liveRunId??null);return}case"task":{if(S.escape||S.leftArrow){p({kind:"main"});return}if(/^[1-9]$/.test(N)){Ue(w.task,Number(N)-1);return}kt(N,w.task.id,w.task.liveRunId);return}case"approve":{if(S.escape||N==="n"){p({kind:"main"}),U("Nothing approved.");return}if(N==="y"){let{task:O}=w;OA({kind:"approve",id:O.id,digest:O.plan.digest}).then(X=>{X&&p({kind:"main"})})}return}case"retry":{if(S.escape||N==="n"){p({kind:"main"}),U("Nothing retried.");return}if(N==="y"){let{task:O,retry:X}=w;OA({kind:"retry",id:O.id,runId:X.runId,digest:X.digest}).then(()=>p(W=>W.kind==="retry"?{kind:"main"}:W))}return}case"accept":{let{result:O}=w,X=()=>{p({kind:"main"}),U("Nothing accepted.")};if(S.escape){X();return}if(!O.ready||O.owed!=="exception"){if(N==="w"){Zt();return}if(!O.ready){(N==="n"||N==="q")&&X();return}if(N==="n"){X();return}N==="y"&&Ot(O,O.owed==="person-check",null);return}if(S.backspace||S.delete){p({...w,reason:w.reason.slice(0,-1)});return}if(S.return){let dA=w.reason.trim();dA!==""&&Ot(O,!1,dA);return}let W=Ef(N);W!==""&&p({...w,reason:w.reason+W});return}case"build":{if(S.escape){p({kind:"main"}),U("Nothing started.");return}if(N==="p"){let{text:O,repo:X}=w;p({kind:"main"}),OA({kind:"new",text:O,repo:X});return}if(S.return){let{preview:O,digest:X}=w.terms;OA({kind:"build",preview:O,digest:X}).then(W=>{W&&p({kind:"main"})})}return}case"compose":{if(S.escape){p({kind:"main"});return}let O=E?.projects??[];if(S.tab&&w.purpose==="new"&&O.length>1){p({...w,project:(w.project+1)%O.length});return}if(S.backspace||S.delete){p({...w,text:w.text.slice(0,-1)});return}if(S.return){let W=w.text.trim();if(W==="")return;let dA=w.purpose==="new"?{kind:"new",text:W,repo:O[w.project]??null}:{kind:"revise",id:w.id,text:W};if(p({kind:"main"}),dA.kind==="new"){H("Reading it…"),e.fastTerms(W,dA.repo).catch(()=>null).then(Ft=>{H(null),Ft===null?OA(dA):p({kind:"build",terms:Ft,text:W,repo:dA.repo})});return}OA(dA);return}let X=Ef(N);X!==""&&p({...w,text:w.text+X});return}case"quit":{N==="s"?Ht("stop"):N==="b"?Ht("keep"):S.escape&&p({kind:"main"});return}case"background":{let O=N==="y"||N==="Y";if(!O&&N!=="n"&&N!=="N"&&!S.return)return;p({kind:"main"}),H(O?"Moving Toolroll to the background…":"Saving…"),u.answerBackground(O).then(X=>{U(X),H(null)});return}default:(S.escape||S.return||N==="q")&&p({kind:"main"})}}},ie=(0,PA.useRef)(XA);ie.current=XA,OE((0,PA.useCallback)((N,S)=>ie.current(N,S),[]));let Jt=J??M;return(0,L.jsxs)(cA,{flexDirection:"column",children:[(0,L.jsxs)(cA,{justifyContent:"space-between",children:[(0,L.jsx)(eA,{bold:!0,children:"Toolroll"}),E?.needsYou?(0,L.jsx)(RA,{bold:!0,children:E.needsYou}):(0,L.jsx)(eA,{dimColor:!0,children:"Nothing needs you"}),E?.learning?(0,L.jsx)(RA,{dimColor:!0,children:E.learning}):null]}),lA(),Jt===null?null:(0,L.jsx)(RA,{children:Jt}),(0,L.jsx)(eA,{dimColor:!0,children:ut()})]});function ut(){switch(w.kind){case"main":return vA.length===0?"n new task · w browser · ? help · q quit":"j/k move · Enter open · n new · a approve/accept · b send back · r retry · p plan · s stop · w browser · ? help · q quit";case"task":return`a approve/accept · b send back · r retry${w.task.planAsk==null?"":" · p plan it"} · s stop · 1–9 answer · w browser · Esc back`;case"approve":return"y approve · Esc cancel";case"retry":return"y retry · Esc cancel";case"accept":return w.result.ready?w.result.owed==="person-check"?"y yes, it looks right · n no · w open in the browser · Esc cancel":w.result.owed==="exception"?"Enter accept · Esc cancel":"y accept · w open in the browser · Esc cancel":"w open in the browser · Esc back";case"build":return"Enter Build · p plan it first · Esc cancel";case"compose":return w.purpose==="new"&&(E?.projects.length??0)>1?"Enter send · Tab project · Esc cancel":"Enter send · Esc cancel";case"quit":return"s stop · b background · Esc cancel";case"background":return"y yes · n no";default:return"Esc back"}}function lA(){switch(w.kind){case"help":return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Keys"}),Vy.map(N=>(0,L.jsx)(eA,{children:N},N))]});case"password":return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:"This needs your password"}),(0,L.jsx)(RA,{children:w.message}),E?.passwordSet?(0,L.jsx)(eA,{children:"Sign in in the browser, then do it there."}):(0,L.jsx)(eA,{children:"Set a password: run `toolroll password set`"})]});case"quit":return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Quit Toolroll?"}),(0,L.jsx)(eA,{children:"s Stop agents and quit (running work is saved)"}),(0,L.jsx)(eA,{children:"b Keep running, and start when you log in"})]});case"background":return(0,L.jsx)(cA,{borderStyle:"single",paddingX:1,children:(0,L.jsx)(eA,{bold:!0,children:"Start Toolroll when you log in, so tasks keep going? (y/N)"})});case"build":return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Build approves exactly this:"}),w.terms.terms.map((N,S)=>(0,L.jsx)(RA,{children:`${N.label}: ${N.words}`},S))]});case"compose":{let N=E?.projects[w.project]??null;return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:w.purpose==="new"?"New task":"What should change?"}),w.purpose==="new"&&N!==null?(0,L.jsx)(RA,{dimColor:!0,children:`In ${N}`}):null,(0,L.jsxs)(eA,{children:[(0,L.jsx)(RA,{children:w.text}),(0,L.jsx)(eA,{inverse:!0,children:" "})]})]})}case"accept":{let{result:N}=w;return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(RA,{bold:!0,children:`Accept this result? ${N.title}`}),(0,L.jsx)(RA,{dimColor:!0,children:`Build #${N.runId}`}),w.changed?(0,L.jsx)(eA,{bold:!0,children:"This result changed while you were reading it. This is the new one."}):null,N.summary.length===0?null:(0,L.jsx)(cA,{flexDirection:"column",marginTop:1,children:N.summary.map((S,O)=>(0,L.jsx)(RA,{children:S},O))}),(0,L.jsxs)(cA,{flexDirection:"column",marginTop:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Changed files"}),N.files===null?(0,L.jsx)(eA,{children:"The changed files couldn't be read. Press w to see them in the browser."}):N.files.names.length===0?(0,L.jsx)(eA,{children:"None."}):(0,L.jsxs)(L.Fragment,{children:[N.files.names.map(S=>(0,L.jsx)(RA,{children:` ${S}`},S)),N.files.more>0?(0,L.jsx)(eA,{children:` and ${N.files.more} more`}):null]})]}),N.requirements.length===0?null:(0,L.jsxs)(cA,{flexDirection:"column",marginTop:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Requirements"}),N.requirements.map((S,O)=>(0,L.jsx)(RA,{children:` ${S.word}: ${S.statement}`},O))]}),N.checks.length===0?null:(0,L.jsx)(cA,{flexDirection:"column",marginTop:1,children:N.checks.map((S,O)=>(0,L.jsx)(RA,{...O===0?{bold:!0}:{},children:S},O))}),(0,L.jsx)(cA,{flexDirection:"column",marginTop:1,children:N.ready?N.owed==="person-check"?(0,L.jsx)(eA,{bold:!0,children:"Did you check it yourself? (y/n)"}):N.owed==="exception"?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(eA,{bold:!0,children:"Say why you accept it anyway:"}),(0,L.jsxs)(eA,{children:[(0,L.jsx)(RA,{children:w.reason}),(0,L.jsx)(eA,{inverse:!0,children:" "})]})]}):(0,L.jsx)(eA,{bold:!0,children:"Accept it and mark the task done? (y/n)"}):(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(eA,{bold:!0,children:"You can't accept it yet."}),N.blockers.map((S,O)=>(0,L.jsx)(RA,{children:S},O))]})})]})}case"retry":return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(RA,{bold:!0,children:`Retry build #${w.retry.runId}? ${w.task.title}`}),(0,L.jsx)(eA,{children:"Same plan, same agent. Its branch and workspace are kept."})]});case"approve":return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(RA,{bold:!0,children:`Approve this plan? ${w.task.title}`}),w.task.plan.lines.map((N,S)=>(0,L.jsx)(RA,{children:N},S))]});case"task":{let{task:N}=w,S=N.decisions[0];return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(RA,{bold:!0,children:N.title}),(0,L.jsx)(RA,{children:`${N.status}${N.detail===""?"":` · ${N.detail}`}`}),N.plan===null?null:(0,L.jsx)(eA,{children:"A plan waits for your approval (a)."}),(N.ready?.length??0)===0?null:(0,L.jsx)(cA,{flexDirection:"column",marginTop:1,children:N.ready.map((O,X)=>(0,L.jsx)(RA,{...X===0?{bold:!0}:{},children:O},X))}),S===void 0?null:(0,L.jsxs)(cA,{flexDirection:"column",marginTop:1,children:[(0,L.jsx)(RA,{bold:!0,children:S.question}),S.options.map((O,X)=>(0,L.jsx)(RA,{children:`${X+1} ${O.label}`},O.id))]}),P.length===0?null:(0,L.jsx)(cA,{flexDirection:"column",marginTop:1,children:P.slice(-12).map((O,X)=>(0,L.jsx)(RA,{dimColor:!0,children:O},X))})]})}default:return E===null?(0,L.jsx)(eA,{dimColor:!0,children:"Loading…"}):vA.length===0?(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Get to your first result"}),(I?.lines??["No tasks yet. Press n to write one."]).map((N,S)=>(0,L.jsx)(RA,{children:N},S))]}):(0,L.jsxs)(cA,{children:[(0,L.jsx)(cA,{flexDirection:"column",width:"45%",borderStyle:"single",paddingX:1,children:vA.map((N,S)=>(0,L.jsxs)(PA.Fragment,{children:[S===0||vA[S-1].group!==N.group?(0,L.jsx)(eA,{bold:!0,children:Py(N)}):null,(0,L.jsxs)(eA,{inverse:N===QA,wrap:"truncate-end",children:[N===QA?"> ":" ",(0,L.jsx)(RA,{children:N.title})," ",(0,L.jsx)(RA,{...N.needsYou?{bold:!0}:{dimColor:!0},children:N.status})]})]},N.id))}),(0,L.jsx)(cA,{flexDirection:"column",flexGrow:1,borderStyle:"single",paddingX:1,children:QA===void 0?(0,L.jsx)(eA,{dimColor:!0,children:"Nothing selected"}):(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(RA,{bold:!0,wrap:"truncate-end",children:QA.title}),(0,L.jsx)(RA,{children:`${QA.status}${QA.detail===""?"":` · ${QA.detail}`}`}),P.length===0?(0,L.jsx)(eA,{dimColor:!0,children:QA.liveRunId===null?"No agent is working on it now.":"Waiting for output…"}):P.slice(-12).map((N,S)=>(0,L.jsx)(RA,{dimColor:!0,wrap:"truncate-end",children:N},S))]})})]})}}}function Bf(){let e=[{id:"t3",title:"Sample: upgrade the test runner",status:"Needs you",detail:"Plan ready to approve",needsYou:!0,liveRunId:null,repo:null,group:"you"},{id:"t1",title:"Sample: fix the login redirect",status:"Running",detail:"Sample task (not real)",needsYou:!1,liveRunId:1,repo:null,group:"working"},{id:"t2",title:"Sample: add CSV export",status:"Complete",detail:"Sample task (not real)",needsYou:!1,liveRunId:null,repo:null,group:"done"}];return{fastTerms:async()=>null,snapshot:async()=>({rows:e,needsYou:"1 task needs you: Sample: upgrade the test runner",projects:[],passwordSet:!1}),task:async u=>{let a=e.find(g=>g.id===u);return a===void 0?null:{id:u,title:a.title,status:a.status,detail:a.detail,liveRunId:a.liveRunId,hasResult:a.status==="Complete",decisions:[],plan:a.needsYou?{digest:"sample",lines:["Goal: upgrade the test runner (sample)"]}:null}},live:u=>u==="t1"?["Editing src/auth.ts (sample)"]:[],changed:()=>0,act:async()=>({ok:!1,message:"This is a sample: nothing changes.",needsPassword:!1}),result:async u=>u!=="t2"?null:{id:u,runId:2,digest:"sample",title:"Sample: add CSV export",ready:!0,blockers:[],summary:["Added a CSV export button to the orders page (sample)."],files:{names:["src/export.ts (sample)"],more:0},requirements:[{word:"You check",statement:"The CSV opens in a spreadsheet (sample)."}],checks:["Sample: checks are not real here."],owed:"person-check"},setup:async()=>null}}function cf(){return{owned:()=>!1,openBrowser:async()=>"This is a sample.",shouldAskBackground:()=>!1,answerBackground:async()=>"This is a sample."}}var If=aA(qa(),1);async function A2(e=Bf(),u=cf()){if(!process.stdin.isTTY||!process.stdout.isTTY)throw new Error("The terminal UI needs an interactive terminal.");let a="leave";return await TE((0,If.jsx)(sf,{source:e,session:u,onExit:g=>{a=g}}),{exitOnCtrlC:!1}).waitUntilExit(),a}var Cf=process.argv[1];Cf!==void 0&&import.meta.url===$y(Cf).href&&A2().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
70
+ `)}var YE=["you","working","done"],lf={you:"Waiting on you",working:"Working",done:"Done"};var L=aA(qa(),1);function RA({children:e,...u}){return(0,L.jsx)(eA,{...u,children:af(e)})}var jy={new:"new task",ink:"approve the plan (shows it in full first)","send-back":"send the result back",retry:"retry",plan:"ask for a plan",list:"back to the task list",help:"these keys"},Vy=["j / k or ↑ / ↓ move","Enter open the task",...[...KE.filter(e=>typeof e.tui=="string").reduce((e,u)=>e.set(u.tui,[...e.get(u.tui)??[],uf(u.keys)]),new Map)].flatMap(([e,u])=>[`${u.join(", ").padEnd(15)} ${jy[e]}`,...e==="ink"?["c accept the result (shows it first)"]:[]]),"s stop the running attempt","1–9 answer the task's question","w open in the browser","Esc back","q quit"];function Wy(e){let u=a=>a.group===null?YE.length:YE.indexOf(a.group);return e.map((a,l)=>({row:a,index:l})).sort((a,l)=>u(a.row)-u(l.row)||a.index-l.index).map(a=>a.row)}var Py=e=>e.group===null?"Other":lf[e.group],Ef=e=>[...e].filter(u=>u>=" "&&u!=="").join("");function sf({source:e,session:u,onExit:a,pollMs:l=1e3}){let{exit:g}=kE(),[E,s]=(0,PA.useState)(null),[I,Q]=(0,PA.useState)(null),[y,v]=(0,PA.useState)(0),[w,p]=(0,PA.useState)({kind:"main"}),[M,U]=(0,PA.useState)(null),[J,H]=(0,PA.useState)(null),[P,FA]=(0,PA.useState)([]),NA=(0,PA.useRef)(null),gA=(0,PA.useRef)(0),xA=(0,PA.useRef)(!1),vA=Wy(E?.rows??[]),QA=vA[Math.min(y,Math.max(vA.length-1,0))],LA=(0,PA.useCallback)(async()=>{let N=await e.snapshot();s(N),N.rows.length===0&&Q(await e.setup())},[e]);(0,PA.useEffect)(()=>{LA()},[LA]),(0,PA.useEffect)(()=>{let N=setInterval(()=>{gA.current+=1;let S=e.changed();(S!==NA.current||gA.current%5===0)&&(NA.current=S,LA())},l);return()=>clearInterval(N)},[e,LA,l]);let yt=QA?.id??null;(0,PA.useEffect)(()=>{if(yt===null){FA([]);return}FA(e.live(yt));let N=setInterval(()=>FA(e.live(yt)),l);return()=>clearInterval(N)},[e,yt,l]);let Ht=N=>{xA.current||(xA.current=!0,g(),a?.(N))},Xt=(0,PA.useRef)(!1),OA=async N=>{H("Working…");try{let S=await e.act(N);return S.ok?(U(S.message),await LA(),!0):(S.needsPassword?p({kind:"password",message:S.message}):U(S.message),!1)}finally{H(null)}},Bt=async(N,S)=>{let O=await e.task(N);O===null?U("That task can't be read now."):S(O)},Ut=N=>Bt(N,S=>{S.plan===null?U("No plan is waiting for your approval on this task."):p({kind:"approve",task:S})}),St=async(N,S=!1)=>{let O=await e.result(N);if(O===null){U("This task has no finished result to accept.");return}p({kind:"accept",result:O,reason:"",changed:S})},Tt=N=>Bt(N,S=>{S.plan!==null?p({kind:"approve",task:S}):S.hasResult?St(N):U("No plan or result is waiting for you on this task.")}),Ot=async(N,S,O)=>{H("Working…");let X;try{X=await e.act({kind:"complete",id:N.id,runId:N.runId,digest:N.digest,checked:S,reason:O})}finally{H(null)}if(X.ok){U(X.message),p(u.shouldAskBackground()?{kind:"background"}:{kind:"main"}),await LA();return}if(X.changed===!0){p({kind:"main"}),U("This result changed while you were reading it. Nothing was accepted."),await St(N.id,!0);return}X.needsPassword?p({kind:"password",message:X.message}):(U(X.message),p({kind:"main"}))},GA=N=>Bt(N,S=>{S.retry==null?U("Nothing to retry on this task."):p({kind:"retry",task:S,retry:S.retry})}),Dt=N=>Bt(N,S=>{S.planAsk==null?U("This task can't be planned now."):OA({kind:"plan",id:N,source:S.planAsk.source})}),He=(N,S)=>{if(S===null){U("Nothing is running on this task.");return}OA({kind:"stop",id:N,runId:S})},Ue=(N,S)=>{let O=N.decisions[0],X=O?.options[S];O===void 0||X===void 0||OA({kind:"answer",decision:O.id,option:X.id}).then(W=>{W&&p({kind:"main"})})},Zt=()=>{H("Opening the browser…"),u.openBrowser().then(N=>{U(N),H(null)})},de=()=>{u.owned()?p({kind:"quit"}):Ht("leave")},kt=(N,S,O)=>{if(Xt.current&&(Xt.current=!1,N==="h"||N==="t"))return p({kind:"main"}),!0;if(N==="g")return Xt.current=!0,!0;if(N==="/"){let X=KE.find(W=>W.keys==="/").tui;return U(typeof X=="string"?null:X.none),!0}return N==="n"?(p({kind:"compose",purpose:"new",id:null,text:"",project:0}),!0):N==="w"?(Zt(),!0):N==="?"?(p({kind:"help"}),!0):N==="q"?(de(),!0):S===null?!1:N==="a"?(Tt(S),!0):N==="s"?(He(S,O),!0):N==="b"?(p({kind:"compose",purpose:"revise",id:S,text:"",project:0}),!0):N==="r"?(GA(S),!0):N==="c"?(St(S),!0):N==="p"?(Dt(S),!0):!1},XA=(N,S)=>{if(J===null){if(S.ctrl&&N==="c"){de();return}switch(w.kind){case"main":{if(N==="j"||S.downArrow){v(O=>Math.min(O+1,Math.max(vA.length-1,0)));return}if(N==="k"||S.upArrow){v(O=>Math.max(O-1,0));return}if(S.return&&QA!==void 0){Bt(QA.id,O=>p({kind:"task",task:O}));return}if(S.escape){U(null);return}kt(N,QA?.id??null,QA?.liveRunId??null);return}case"task":{if(S.escape||S.leftArrow){p({kind:"main"});return}if(/^[1-9]$/.test(N)){Ue(w.task,Number(N)-1);return}kt(N,w.task.id,w.task.liveRunId);return}case"approve":{if(S.escape||N==="n"){p({kind:"main"}),U("Nothing approved.");return}if(N==="y"){let{task:O}=w;OA({kind:"approve",id:O.id,digest:O.plan.digest}).then(X=>{X&&p({kind:"main"})})}return}case"retry":{if(S.escape||N==="n"){p({kind:"main"}),U("Nothing retried.");return}if(N==="y"){let{task:O,retry:X}=w;OA({kind:"retry",id:O.id,runId:X.runId,digest:X.digest}).then(()=>p(W=>W.kind==="retry"?{kind:"main"}:W))}return}case"accept":{let{result:O}=w,X=()=>{p({kind:"main"}),U("Nothing accepted.")};if(S.escape){X();return}if(!O.ready||O.owed!=="exception"){if(N==="w"){Zt();return}if(!O.ready){(N==="n"||N==="q")&&X();return}if(N==="n"){X();return}N==="y"&&Ot(O,O.owed==="person-check",null);return}if(S.backspace||S.delete){p({...w,reason:w.reason.slice(0,-1)});return}if(S.return){let dA=w.reason.trim();dA!==""&&Ot(O,!1,dA);return}let W=Ef(N);W!==""&&p({...w,reason:w.reason+W});return}case"build":{if(S.escape){p({kind:"main"}),U("Nothing started.");return}if(N==="p"){let{text:O,repo:X}=w;p({kind:"main"}),OA({kind:"new",text:O,repo:X});return}if(S.return){let{preview:O,digest:X}=w.terms;OA({kind:"build",preview:O,digest:X}).then(W=>{W&&p({kind:"main"})})}return}case"compose":{if(S.escape){p({kind:"main"});return}let O=E?.projects??[];if(S.tab&&w.purpose==="new"&&O.length>1){p({...w,project:(w.project+1)%O.length});return}if(S.backspace||S.delete){p({...w,text:w.text.slice(0,-1)});return}if(S.return){let W=w.text.trim();if(W==="")return;let dA=w.purpose==="new"?{kind:"new",text:W,repo:O[w.project]??null}:{kind:"revise",id:w.id,text:W};if(p({kind:"main"}),dA.kind==="new"){H("Reading it…"),e.fastTerms(W,dA.repo).catch(()=>null).then(Ft=>{H(null),Ft===null?OA(dA):p({kind:"build",terms:Ft,text:W,repo:dA.repo})});return}OA(dA);return}let X=Ef(N);X!==""&&p({...w,text:w.text+X});return}case"quit":{N==="s"?Ht("stop"):N==="b"?Ht("keep"):S.escape&&p({kind:"main"});return}case"background":{let O=N==="y"||N==="Y";if(!O&&N!=="n"&&N!=="N"&&!S.return)return;p({kind:"main"}),H(O?"Moving Toolroll to the background…":"Saving…"),u.answerBackground(O).then(X=>{U(X),H(null)});return}default:(S.escape||S.return||N==="q")&&p({kind:"main"})}}},ie=(0,PA.useRef)(XA);ie.current=XA,OE((0,PA.useCallback)((N,S)=>ie.current(N,S),[]));let Jt=J??M;return(0,L.jsxs)(cA,{flexDirection:"column",children:[(0,L.jsxs)(cA,{justifyContent:"space-between",children:[(0,L.jsx)(eA,{bold:!0,children:"Toolroll"}),E?.needsYou?(0,L.jsx)(RA,{bold:!0,children:E.needsYou}):(0,L.jsx)(eA,{dimColor:!0,children:"Nothing needs you"}),E?.learning?(0,L.jsx)(RA,{dimColor:!0,children:E.learning}):null]}),lA(),Jt===null?null:(0,L.jsx)(RA,{children:Jt}),(0,L.jsx)(eA,{dimColor:!0,children:ut()})]});function ut(){switch(w.kind){case"main":return vA.length===0?"n new task · w browser · ? help · q quit":"j/k move · Enter open · n new · a approve/accept · b send back · r retry · p plan · s stop · w browser · ? help · q quit";case"task":return`a approve/accept · b send back · r retry${w.task.planAsk==null?"":" · p plan it"} · s stop · 1–9 answer · w browser · Esc back`;case"approve":return"y approve · Esc cancel";case"retry":return"y retry · Esc cancel";case"accept":return w.result.ready?w.result.owed==="person-check"?"y yes, it looks right · n no · w open in the browser · Esc cancel":w.result.owed==="exception"?"Enter accept · Esc cancel":"y accept · w open in the browser · Esc cancel":"w open in the browser · Esc back";case"build":return"Enter Build · p plan it first · Esc cancel";case"compose":return w.purpose==="new"&&(E?.projects.length??0)>1?"Enter send · Tab project · Esc cancel":"Enter send · Esc cancel";case"quit":return"s stop · b background · Esc cancel";case"background":return"y yes · n no";default:return"Esc back"}}function lA(){switch(w.kind){case"help":return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Keys"}),Vy.map(N=>(0,L.jsx)(eA,{children:N},N))]});case"password":return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:"This needs your password"}),(0,L.jsx)(RA,{children:w.message}),E?.passwordSet?(0,L.jsx)(eA,{children:"Sign in in the browser, then do it there."}):(0,L.jsx)(eA,{children:"Set a password: run `toolroll password set`"})]});case"quit":return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Quit Toolroll?"}),(0,L.jsx)(eA,{children:"s Stop agents and quit (running work is saved)"}),(0,L.jsx)(eA,{children:"b Keep running, and start when you log in"})]});case"background":return(0,L.jsx)(cA,{borderStyle:"single",paddingX:1,children:(0,L.jsx)(eA,{bold:!0,children:"Start Toolroll when you log in, so tasks keep going? (y/N)"})});case"build":return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Build approves exactly this:"}),w.terms.terms.map((N,S)=>(0,L.jsx)(RA,{children:`${N.label}: ${N.words}`},S))]});case"compose":{let N=E?.projects[w.project]??null;return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:w.purpose==="new"?"New task":"What should change?"}),w.purpose==="new"&&N!==null?(0,L.jsx)(RA,{dimColor:!0,children:`In ${N}`}):null,(0,L.jsxs)(eA,{children:[(0,L.jsx)(RA,{children:w.text}),(0,L.jsx)(eA,{inverse:!0,children:" "})]})]})}case"accept":{let{result:N}=w;return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(RA,{bold:!0,children:`Accept this result? ${N.title}`}),(0,L.jsx)(RA,{dimColor:!0,children:`Build #${N.runId}`}),w.changed?(0,L.jsx)(eA,{bold:!0,children:"This result changed while you were reading it. This is the new one."}):null,N.summary.length===0?null:(0,L.jsx)(cA,{flexDirection:"column",marginTop:1,children:N.summary.map((S,O)=>(0,L.jsx)(RA,{children:S},O))}),(0,L.jsxs)(cA,{flexDirection:"column",marginTop:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Changed files"}),N.files===null?(0,L.jsx)(eA,{children:"The changed files couldn't be read. Press w to see them in the browser."}):N.files.names.length===0?(0,L.jsx)(eA,{children:"None."}):(0,L.jsxs)(L.Fragment,{children:[N.files.names.map(S=>(0,L.jsx)(RA,{children:` ${S}`},S)),N.files.more>0?(0,L.jsx)(eA,{children:` and ${N.files.more} more`}):null]})]}),N.requirements.length===0?null:(0,L.jsxs)(cA,{flexDirection:"column",marginTop:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Requirements"}),N.requirements.map((S,O)=>(0,L.jsx)(RA,{children:` ${S.word}: ${S.statement}`},O))]}),N.checks.length===0?null:(0,L.jsx)(cA,{flexDirection:"column",marginTop:1,children:N.checks.map((S,O)=>(0,L.jsx)(RA,{...O===0?{bold:!0}:{},children:S},O))}),(0,L.jsx)(cA,{flexDirection:"column",marginTop:1,children:N.ready?N.owed==="person-check"?(0,L.jsx)(eA,{bold:!0,children:"Did you check it yourself? (y/n)"}):N.owed==="exception"?(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(eA,{bold:!0,children:"Say why you accept it anyway:"}),(0,L.jsxs)(eA,{children:[(0,L.jsx)(RA,{children:w.reason}),(0,L.jsx)(eA,{inverse:!0,children:" "})]})]}):(0,L.jsx)(eA,{bold:!0,children:"Accept it and mark the task done? (y/n)"}):(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(eA,{bold:!0,children:"You can't accept it yet."}),N.blockers.map((S,O)=>(0,L.jsx)(RA,{children:S},O))]})})]})}case"retry":return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(RA,{bold:!0,children:`Retry build #${w.retry.runId}? ${w.task.title}`}),(0,L.jsx)(eA,{children:"Same plan, same agent. Its branch and workspace are kept."})]});case"approve":return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(RA,{bold:!0,children:`Approve this plan? ${w.task.title}`}),w.task.plan.lines.map((N,S)=>(0,L.jsx)(RA,{children:N},S))]});case"task":{let{task:N}=w,S=N.decisions[0];return(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(RA,{bold:!0,children:N.title}),(0,L.jsx)(RA,{children:`${N.status}${N.detail===""?"":` · ${N.detail}`}`}),N.plan===null?null:(0,L.jsx)(eA,{children:"A plan waits for your approval (a)."}),(N.ready?.length??0)===0?null:(0,L.jsx)(cA,{flexDirection:"column",marginTop:1,children:N.ready.map((O,X)=>(0,L.jsx)(RA,{...X===0?{bold:!0}:{},children:O},X))}),S===void 0?null:(0,L.jsxs)(cA,{flexDirection:"column",marginTop:1,children:[(0,L.jsx)(RA,{bold:!0,children:S.question}),S.options.map((O,X)=>(0,L.jsx)(RA,{children:`${X+1} ${O.label}`},O.id))]}),P.length===0?null:(0,L.jsx)(cA,{flexDirection:"column",marginTop:1,children:P.slice(-12).map((O,X)=>(0,L.jsx)(RA,{dimColor:!0,children:O},X))})]})}default:return E===null?(0,L.jsx)(eA,{dimColor:!0,children:"Loading…"}):vA.length===0?(0,L.jsxs)(cA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Get to your first result"}),(I?.lines??["No tasks yet. Press n to write one."]).map((N,S)=>(0,L.jsx)(RA,{children:N},S))]}):(0,L.jsxs)(cA,{children:[(0,L.jsx)(cA,{flexDirection:"column",width:"45%",borderStyle:"single",paddingX:1,children:vA.map((N,S)=>(0,L.jsxs)(PA.Fragment,{children:[S===0||vA[S-1].group!==N.group?(0,L.jsx)(eA,{bold:!0,children:Py(N)}):null,(0,L.jsxs)(eA,{inverse:N===QA,wrap:"truncate-end",children:[N===QA?"> ":" ",(0,L.jsx)(RA,{children:N.title})," ",(0,L.jsx)(RA,{...N.needsYou?{bold:!0}:{dimColor:!0},children:N.status})]})]},N.id))}),(0,L.jsx)(cA,{flexDirection:"column",flexGrow:1,borderStyle:"single",paddingX:1,children:QA===void 0?(0,L.jsx)(eA,{dimColor:!0,children:"Nothing selected"}):(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(RA,{bold:!0,wrap:"truncate-end",children:QA.title}),(0,L.jsx)(RA,{children:`${QA.status}${QA.detail===""?"":` · ${QA.detail}`}`}),P.length===0?(0,L.jsx)(eA,{dimColor:!0,children:QA.liveRunId===null?"No agent is working on it now.":"Waiting for output…"}):P.slice(-12).map((N,S)=>(0,L.jsx)(RA,{dimColor:!0,wrap:"truncate-end",children:N},S))]})})]})}}}function Bf(){let e=[{id:"t3",title:"Sample: upgrade the test runner",status:"Needs you",detail:"Plan ready to approve",needsYou:!0,liveRunId:null,repo:null,group:"you"},{id:"t1",title:"Sample: fix the login redirect",status:"Running",detail:"Sample task (not real)",needsYou:!1,liveRunId:1,repo:null,group:"working"},{id:"t2",title:"Sample: add CSV export",status:"Complete",detail:"Sample task (not real)",needsYou:!1,liveRunId:null,repo:null,group:"done"}];return{fastTerms:async()=>null,snapshot:async()=>({rows:e,needsYou:"1 task needs you: Sample: upgrade the test runner",projects:[],passwordSet:!1}),task:async u=>{let a=e.find(g=>g.id===u);return a===void 0?null:{id:u,title:a.title,status:a.status,detail:a.detail,liveRunId:a.liveRunId,hasResult:a.status==="Complete",decisions:[],plan:a.needsYou?{digest:"sample",lines:["Goal: upgrade the test runner (sample)"]}:null}},live:u=>u==="t1"?["Editing src/auth.ts (sample)"]:[],changed:()=>0,act:async()=>({ok:!1,message:"This is a sample: nothing changes.",needsPassword:!1}),result:async u=>u!=="t2"?null:{id:u,runId:2,digest:"sample",title:"Sample: add CSV export",ready:!0,blockers:[],summary:["Added a CSV export button to the orders page (sample)."],files:{names:["src/export.ts (sample)"],more:0},requirements:[{word:"You check",statement:"The CSV opens in a spreadsheet (sample)."}],checks:["Sample: checks are not real here."],owed:"person-check"},setup:async()=>null}}function cf(){return{owned:()=>!1,openBrowser:async()=>"This is a sample.",shouldAskBackground:()=>!1,answerBackground:async()=>"This is a sample."}}var If=aA(qa(),1);async function A2(e=Bf(),u=cf()){if(!process.stdin.isTTY||!process.stdout.isTTY)throw new Error("The terminal UI needs an interactive terminal.");let a="leave";return await TE((0,If.jsx)(sf,{source:e,session:u,onExit:g=>{a=g}}),{exitOnCtrlC:!1}).waitUntilExit(),a}var Cf=process.argv[1];Cf!==void 0&&import.meta.url===$y(Cf).href&&A2().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
71
71
  `),process.exitCode=1});export{A2 as startTui};
72
72
  /*! Bundled license information:
73
73