toolroll 0.9.108 → 0.9.110

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 (187) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/dist/advanced-view.js +0 -1
  3. package/dist/agent-detect.js +244 -0
  4. package/dist/agent-fence.js +47 -5
  5. package/dist/agent-state.js +5 -2
  6. package/dist/agentconfig.js +2 -2
  7. package/dist/approval-summary.js +344 -0
  8. package/dist/assignment-ui.js +5 -5
  9. package/dist/assignment.js +5 -2
  10. package/dist/attest.js +2 -2
  11. package/dist/browser/terminal.js +1 -1
  12. package/dist/browser/workspace.css +2 -2
  13. package/dist/browser/workspace.js +37 -34
  14. package/dist/browser-crew.js +4 -4
  15. package/dist/browser-workspace.js +4 -11
  16. package/dist/builder.js +45 -3
  17. package/dist/chat-actions.js +24 -17
  18. package/dist/chat-controls.js +6 -5
  19. package/dist/chat-core.js +3 -1
  20. package/dist/chat-decide.js +102 -47
  21. package/dist/chat-delivery-state.js +2 -0
  22. package/dist/chat-delivery.js +3 -2
  23. package/dist/chat-live.js +2 -1
  24. package/dist/chat-quiet.js +3 -3
  25. package/dist/chat-task-actions.js +6 -0
  26. package/dist/chat-voice.js +2 -2
  27. package/dist/check-report.js +1 -1
  28. package/dist/cli-help.js +12 -13
  29. package/dist/cli.js +6 -3
  30. package/dist/console-chrome.js +10 -3
  31. package/dist/console-instance.js +10 -1
  32. package/dist/contracts/console-api.js +14 -8
  33. package/dist/contracts/engine-api.js +271 -0
  34. package/dist/contracts/handoff.js +4 -0
  35. package/dist/coordinator.js +2 -2
  36. package/dist/decision.js +17 -0
  37. package/dist/demo-chat.js +1 -1
  38. package/dist/demo.js +6 -0
  39. package/dist/design/kit.js +4 -3
  40. package/dist/discord-api.js +4 -3
  41. package/dist/discord-chat.js +3 -1
  42. package/dist/dispatch.js +3 -8
  43. package/dist/easy-start-args.js +7 -3
  44. package/dist/easy-start.js +25 -0
  45. package/dist/egress.js +72 -10
  46. package/dist/engine-handoff.js +34 -0
  47. package/dist/engine-reads.js +261 -0
  48. package/dist/eval-world.js +3 -2
  49. package/dist/evidence.js +2 -0
  50. package/dist/fast-start.js +55 -14
  51. package/dist/fast-terms.js +2 -2
  52. package/dist/first-run.js +10 -2
  53. package/dist/flexible-agents.js +234 -0
  54. package/dist/flexible-answers-schema.js +61 -0
  55. package/dist/flexible-answers.js +889 -0
  56. package/dist/flexible-available.js +1 -0
  57. package/dist/flexible-custody.js +494 -0
  58. package/dist/flexible-import.js +782 -0
  59. package/dist/flexible-launch-schema.js +72 -0
  60. package/dist/flexible-launch.js +331 -0
  61. package/dist/flexible-launcher.js +88 -0
  62. package/dist/flexible-levels.js +34 -0
  63. package/dist/flexible-merge-guard.js +47 -0
  64. package/dist/flexible-refs.js +47 -0
  65. package/dist/flexible-relay-cancel.js +19 -0
  66. package/dist/flexible-relay-schema.js +55 -0
  67. package/dist/flexible-relay-upstreams.js +36 -0
  68. package/dist/flexible-relay.js +1032 -0
  69. package/dist/flexible-schema.js +32 -0
  70. package/dist/flexible-session.js +732 -0
  71. package/dist/flexible-ship-schema.js +81 -0
  72. package/dist/flexible-ship.js +694 -0
  73. package/dist/flexible-start.js +80 -0
  74. package/dist/flexible-thread-schema.js +30 -0
  75. package/dist/flexible-thread.js +676 -0
  76. package/dist/flexible-turns-schema.js +69 -0
  77. package/dist/flexible-turns.js +490 -0
  78. package/dist/flexible-ui.js +44 -0
  79. package/dist/flexible.js +368 -0
  80. package/dist/flow-actions.js +6 -4
  81. package/dist/flow-steps.js +1 -1
  82. package/dist/flows-cli.js +2 -1
  83. package/dist/git-views.js +44 -41
  84. package/dist/guides.js +11 -10
  85. package/dist/install-mode.js +225 -0
  86. package/dist/keymap.js +1 -1
  87. package/dist/lead-context.js +1 -1
  88. package/dist/lead-doors.js +7 -1
  89. package/dist/limits-ui.js +8 -1
  90. package/dist/live-bus.js +70 -13
  91. package/dist/live-reply.js +6 -0
  92. package/dist/live-terminal.js +425 -29
  93. package/dist/local-owner.js +6 -0
  94. package/dist/model-choices.js +12 -6
  95. package/dist/needs-you.js +3 -3
  96. package/dist/nightly-github.js +2 -2
  97. package/dist/notification-delivery.js +11 -0
  98. package/dist/operate.js +185 -33
  99. package/dist/outbound-privacy.js +204 -0
  100. package/dist/passwordless.js +2 -1
  101. package/dist/project-delete-ui.js +2 -1
  102. package/dist/project-delete.js +15 -0
  103. package/dist/provider-auth.js +1 -1
  104. package/dist/provider-connection.js +5 -3
  105. package/dist/publish.js +5 -0
  106. package/dist/pull-request-flow.js +26 -7
  107. package/dist/push.js +5 -1
  108. package/dist/release-card.js +11 -3
  109. package/dist/release.js +11 -1
  110. package/dist/result-actions.js +3 -0
  111. package/dist/result-evidence-readers.js +8 -2
  112. package/dist/result-review.js +20 -9
  113. package/dist/route-store.js +2 -2
  114. package/dist/sandbox-launch.js +32 -8
  115. package/dist/sandbox-runtime.js +16 -7
  116. package/dist/sandbox-tools.js +176 -0
  117. package/dist/scope.js +12 -36
  118. package/dist/scout-net.js +7 -2
  119. package/dist/serve.js +90 -40
  120. package/dist/server/chat.js +9 -9
  121. package/dist/server/chrome.js +19 -17
  122. package/dist/server/console.css +33 -6
  123. package/dist/server/engine-api.js +378 -0
  124. package/dist/server/flows.js +2 -2
  125. package/dist/server/guards.js +10 -4
  126. package/dist/server/home.js +37 -5
  127. package/dist/server/http.js +11 -2
  128. package/dist/server/in-place.js +5 -4
  129. package/dist/server/kit.js +2 -2
  130. package/dist/server/link-redemption.js +52 -0
  131. package/dist/server/live.js +100 -10
  132. package/dist/server/mutation-key.js +21 -7
  133. package/dist/server/pages.js +129 -74
  134. package/dist/server/people-tokens.js +17 -41
  135. package/dist/server/render-chat.js +2 -1
  136. package/dist/server/render-history.js +18 -4
  137. package/dist/server/render-new-task.js +4 -4
  138. package/dist/server/render-pages.js +21 -39
  139. package/dist/server/render-people.js +2 -2
  140. package/dist/server/render-projects.js +5 -5
  141. package/dist/server/render-results.js +30 -14
  142. package/dist/server/render-tasks.js +155 -155
  143. package/dist/server/retired-routes.js +37 -4
  144. package/dist/server/route-policy.js +8 -0
  145. package/dist/server/route-table.js +43 -5
  146. package/dist/server/settings-computers.js +140 -0
  147. package/dist/server/settings-scripts.js +15 -0
  148. package/dist/server/settings-section-table.js +59 -0
  149. package/dist/server/settings-sections.js +291 -0
  150. package/dist/server/settings.js +247 -28
  151. package/dist/server/task-views.js +55 -15
  152. package/dist/server/tasks.js +168 -98
  153. package/dist/server/terminals.js +181 -28
  154. package/dist/server/welcome.js +40 -14
  155. package/dist/settings-groups-ui.js +26 -107
  156. package/dist/settings-proofs.js +18 -11
  157. package/dist/slack-api.js +4 -3
  158. package/dist/slack-chat.js +5 -3
  159. package/dist/spend.js +46 -12
  160. package/dist/sqlite-telemetry.js +70 -21
  161. package/dist/status-probe.js +343 -0
  162. package/dist/store.js +206 -10
  163. package/dist/task-link.js +64 -0
  164. package/dist/teams-api.js +4 -3
  165. package/dist/teams-chat.js +4 -2
  166. package/dist/telegram-lead.js +2 -1
  167. package/dist/telegram-live.js +2 -1
  168. package/dist/telegram-team.js +2 -1
  169. package/dist/telegram.js +17 -5
  170. package/dist/trusted-path.js +162 -0
  171. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  172. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  173. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  174. package/dist/tui/linux-x64/toolroll-tui +0 -0
  175. package/dist/tui-launch.js +282 -0
  176. package/dist/tui-source.js +5 -3
  177. package/dist/tui.js +2 -2
  178. package/dist/typed-words-schema.js +18 -0
  179. package/dist/webhooks.js +8 -4
  180. package/dist/welcome-facts.js +25 -17
  181. package/dist/work-index.js +126 -29
  182. package/dist/work-reads.js +279 -0
  183. package/dist/workspace-ui.js +5 -0
  184. package/package.json +4 -2
  185. package/scripts/crash-canary.mjs +1 -1
  186. package/scripts/pilot.mjs +1 -1
  187. package/scripts/provider-canary.mjs +5 -3
@@ -0,0 +1,162 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { lstatSync, realpathSync } from "node:fs";
3
+ import { dirname, isAbsolute } from "node:path";
4
+ const ACL_CHANGE = new Set(["write", "append", "add_file", "add_subdirectory", "delete", "delete_child", "writeattr", "writeextattr", "writesecurity", "chown"]);
5
+ const ACL_RIGHTS = new Set([...ACL_CHANGE, "read", "execute", "readattr", "readextattr", "readsecurity", "list", "search", "file_inherit", "directory_inherit", "limit_inherit", "only_inherit"]);
6
+ const ACL_READ_MS = 3_000;
7
+ export const platformAcl = () => (process.platform === "darwin" ? macAcl : null);
8
+ export function boundedAcl(deadline, read = process.platform === "darwin" ? macAclWithin : null) {
9
+ if (read === null)
10
+ return null;
11
+ const seen = new Map();
12
+ return path => {
13
+ let verdict = seen.get(path);
14
+ if (verdict === undefined) {
15
+ const left = deadline - Date.now();
16
+ verdict = left <= 0 ? { ok: false, why: "can't be read in time" } : read(path, Math.min(left, ACL_READ_MS));
17
+ seen.set(path, verdict);
18
+ }
19
+ return verdict;
20
+ };
21
+ }
22
+ export function trustedFolders(folder, uid, acl) {
23
+ const owned = (owner) => owner === uid || owner === 0;
24
+ try {
25
+ for (let first = true;; first = false) {
26
+ const dir = lstatSync(folder);
27
+ if (!dir.isDirectory())
28
+ return { ok: false, why: `${folder} isn't a folder` };
29
+ if (!owned(dir.uid))
30
+ return { ok: false, why: `${folder} is owned by another user` };
31
+ const sticky = (dir.mode & 0o1000) !== 0;
32
+ if ((dir.mode & 0o022) !== 0 && (first || !sticky))
33
+ return { ok: false, why: `others can change ${folder} (group- or world-writable)` };
34
+ const dirAcl = acl?.(folder);
35
+ if (dirAcl !== undefined && !dirAcl.ok)
36
+ return { ok: false, why: `the ACL of ${folder} ${dirAcl.why}` };
37
+ const up = dirname(folder);
38
+ if (up === folder)
39
+ return { ok: true };
40
+ folder = up;
41
+ }
42
+ }
43
+ catch (error) {
44
+ return { ok: false, why: `it can't be checked (${error.code ?? "unreadable"})` };
45
+ }
46
+ }
47
+ export function trustedBinary(path, uid, acl = platformAcl()) {
48
+ if (!isAbsolute(path))
49
+ return { ok: false, why: "it isn't an absolute path" };
50
+ if (uid === undefined)
51
+ return { ok: false, why: "who owns it can't be checked on this system" };
52
+ let real;
53
+ try {
54
+ real = realpathSync(path);
55
+ }
56
+ catch (error) {
57
+ return { ok: false, why: `it isn't there (${error.code ?? "unreadable"})` };
58
+ }
59
+ try {
60
+ const file = lstatSync(real);
61
+ if (!file.isFile())
62
+ return { ok: false, why: "it isn't a file" };
63
+ if (file.uid !== uid && file.uid !== 0)
64
+ return { ok: false, why: "it is owned by another user" };
65
+ if ((file.mode & 0o022) !== 0)
66
+ return { ok: false, why: "others can change it (group- or world-writable)" };
67
+ const fileAcl = acl?.(real);
68
+ if (fileAcl !== undefined && !fileAcl.ok)
69
+ return { ok: false, why: `its ACL ${fileAcl.why}` };
70
+ }
71
+ catch (error) {
72
+ return { ok: false, why: `it can't be checked (${error.code ?? "unreadable"})` };
73
+ }
74
+ const folders = trustedFolders(dirname(real), uid, acl);
75
+ return folders.ok ? { ok: true, real } : folders;
76
+ }
77
+ export function rootOwnedFolders(folder, acl = platformAcl(), owners = [0], who = "root") {
78
+ let real;
79
+ try {
80
+ real = realpathSync(folder);
81
+ }
82
+ catch (error) {
83
+ return { ok: false, why: `${folder} isn't there (${error.code ?? "unreadable"})` };
84
+ }
85
+ try {
86
+ for (let at = real;; at = dirname(at)) {
87
+ const dir = lstatSync(at);
88
+ if (!dir.isDirectory())
89
+ return { ok: false, why: `${at} isn't a folder` };
90
+ if (!owners.includes(dir.uid))
91
+ return { ok: false, why: `${at} isn't owned by ${who}` };
92
+ if ((dir.mode & 0o022) !== 0)
93
+ return { ok: false, why: `others can change ${at} (group- or world-writable)` };
94
+ const dirAcl = acl?.(at);
95
+ if (dirAcl !== undefined && !dirAcl.ok)
96
+ return { ok: false, why: `the ACL of ${at} ${dirAcl.why}` };
97
+ if (dirname(at) === at)
98
+ return { ok: true, real };
99
+ }
100
+ }
101
+ catch (error) {
102
+ return { ok: false, why: `it can't be checked (${error.code ?? "unreadable"})` };
103
+ }
104
+ }
105
+ export function rootOwnedBinary(path, acl = platformAcl(), owners = [0], who = "root") {
106
+ if (!isAbsolute(path))
107
+ return { ok: false, why: "it isn't an absolute path" };
108
+ let real;
109
+ try {
110
+ real = realpathSync(path);
111
+ }
112
+ catch (error) {
113
+ return { ok: false, why: `it isn't there (${error.code ?? "unreadable"})` };
114
+ }
115
+ try {
116
+ const file = lstatSync(real);
117
+ if (!file.isFile())
118
+ return { ok: false, why: "it isn't a file" };
119
+ if (!owners.includes(file.uid))
120
+ return { ok: false, why: `${real} isn't owned by ${who}` };
121
+ if ((file.mode & 0o022) !== 0)
122
+ return { ok: false, why: `others can change ${real} (group- or world-writable)` };
123
+ const fileAcl = acl?.(real);
124
+ if (fileAcl !== undefined && !fileAcl.ok)
125
+ return { ok: false, why: `its ACL ${fileAcl.why}` };
126
+ }
127
+ catch (error) {
128
+ return { ok: false, why: `it can't be checked (${error.code ?? "unreadable"})` };
129
+ }
130
+ const folders = rootOwnedFolders(dirname(real), acl, owners, who);
131
+ return folders.ok ? { ok: true, real } : folders;
132
+ }
133
+ export function aclVerdictOf(output) {
134
+ const lines = output.split("\n");
135
+ if (lines.at(-1) === "")
136
+ lines.pop();
137
+ if (lines.length === 0 || !/^[-dlbcpsw][-rwxsStT]{9}[@+]? /.test(lines[0]))
138
+ return { ok: false, why: "can't be read" };
139
+ for (const line of lines.slice(1)) {
140
+ const entry = /^ \d+: (\S.*?) (?:inherited )?(allow|deny) ([a-z_]+(?:,[a-z_]+)*)$/.exec(line);
141
+ if (entry === null)
142
+ return { ok: false, why: "can't be read" };
143
+ const rights = entry[3].split(",");
144
+ if (rights.some(right => !ACL_RIGHTS.has(right)))
145
+ return { ok: false, why: "can't be read (an unknown right)" };
146
+ const granted = rights.filter(right => ACL_CHANGE.has(right));
147
+ if (entry[2] === "allow" && granted.length > 0)
148
+ return { ok: false, why: `allows ${entry[1]} to change it (${granted.join(",")})` };
149
+ }
150
+ return { ok: true };
151
+ }
152
+ function macAcl(path) {
153
+ return macAclWithin(path, ACL_READ_MS);
154
+ }
155
+ function macAclWithin(path, ms) {
156
+ if (/[\u0000-\u001f\u007f]/.test(path))
157
+ return { ok: false, why: "can't be read (a control character in the path)" };
158
+ const ran = spawnSync("/bin/ls", ["-lde", "--", path], { encoding: "utf8", timeout: Math.max(1, Math.floor(ms)), env: { LC_ALL: "C", PATH: "/usr/bin:/bin" }, stdio: ["ignore", "pipe", "ignore"] });
159
+ if (ran.status !== 0 || typeof ran.stdout !== "string")
160
+ return { ok: false, why: "can't be read" };
161
+ return aclVerdictOf(ran.stdout);
162
+ }
Binary file
Binary file
@@ -0,0 +1,282 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { lstatSync, readFileSync, realpathSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { spawnHoldingLink } from "./engine-handoff.js";
6
+ import { trustedBinary } from "./trusted-path.js";
7
+ export { aclVerdictOf, trustedBinary } from "./trusted-path.js";
8
+ export const TUI_EXIT = { leave: 0, stop: 40, keep: 41, classic: 42, unprotected: 43 };
9
+ export const TUI_PACKAGES = Object.freeze({
10
+ "darwin-arm64": "@toolroll/tui-darwin-arm64", "darwin-x64": "@toolroll/tui-darwin-x64",
11
+ "linux-x64": "@toolroll/tui-linux-x64", "linux-arm64": "@toolroll/tui-linux-arm64",
12
+ });
13
+ const ASK_CAP = 1024;
14
+ const SELF_CHECK_MS = 3_000;
15
+ const READY_MS = 5_000;
16
+ const KILL_AFTER_MS = 1_000;
17
+ const READY = "protected";
18
+ export const packageRootOf = (moduleUrl) => {
19
+ const root = join(dirname(fileURLToPath(moduleUrl)), "..");
20
+ try {
21
+ return realpathSync(root);
22
+ }
23
+ catch {
24
+ return root;
25
+ }
26
+ };
27
+ const defaultRoot = () => packageRootOf(import.meta.url);
28
+ export const bundledBinary = (root, key) => join(root, "dist", "tui", key, "toolroll-tui");
29
+ const defaultSelfCheck = (binary) => {
30
+ const ran = spawnSync(binary, ["--version"], { encoding: "utf8", timeout: SELF_CHECK_MS, stdio: ["ignore", "pipe", "ignore"] });
31
+ return { status: ran.status, stdout: ran.stdout ?? "", ...(ran.error === undefined ? {} : { error: ran.error.code ?? ran.error.message }) };
32
+ };
33
+ export function identityOf(path) {
34
+ try {
35
+ const st = lstatSync(path, { bigint: true });
36
+ return { dev: st.dev, ino: st.ino, size: st.size, mtimeNs: st.mtimeNs };
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ const sameIdentity = (a, b) => a !== null && a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs;
43
+ function presence(path) {
44
+ try {
45
+ lstatSync(path);
46
+ return { kind: "present" };
47
+ }
48
+ catch (error) {
49
+ const code = error.code;
50
+ return code === "ENOENT" ? { kind: "absent" } : { kind: "refused", why: `${path} can't be checked (${code ?? "unreadable"})` };
51
+ }
52
+ }
53
+ function bundledCandidate(root, key) {
54
+ let realRoot;
55
+ try {
56
+ realRoot = realpathSync(root);
57
+ }
58
+ catch (error) {
59
+ const code = error.code;
60
+ return code === "ENOENT" ? { kind: "absent" } : { kind: "refused", why: `${root} can't be checked (${code ?? "unreadable"})` };
61
+ }
62
+ const parts = ["dist", "tui", key, "toolroll-tui"];
63
+ let at = realRoot;
64
+ for (const [i, part] of parts.entries()) {
65
+ at = join(at, part);
66
+ let st;
67
+ try {
68
+ st = lstatSync(at);
69
+ }
70
+ catch (error) {
71
+ const code = error.code;
72
+ if (code === "ENOENT")
73
+ return { kind: "absent" };
74
+ return { kind: "refused", why: `${at} can't be checked (${code ?? "unreadable"})` };
75
+ }
76
+ if (st.isSymbolicLink())
77
+ return { kind: "refused", why: `${at} is a link: the binary the package ships must be inside it` };
78
+ if (i < parts.length - 1 && !st.isDirectory())
79
+ return { kind: "refused", why: `${at} isn't a folder` };
80
+ }
81
+ let real;
82
+ try {
83
+ real = realpathSync(at);
84
+ }
85
+ catch (error) {
86
+ return { kind: "refused", why: `${at} can't be checked (${error.code ?? "unreadable"})` };
87
+ }
88
+ if (!real.startsWith(`${realRoot}${sep}`))
89
+ return { kind: "refused", why: `${at} isn't inside the package` };
90
+ return { kind: "present", path: at };
91
+ }
92
+ function packageCandidates(root, name) {
93
+ const parts = name.split("/");
94
+ const places = [join(root, "node_modules", ...parts)];
95
+ if (basename(dirname(root)) === "node_modules")
96
+ places.push(join(dirname(root), ...parts));
97
+ return places;
98
+ }
99
+ function packageCandidate(root, name) {
100
+ for (const place of packageCandidates(root, name)) {
101
+ const manifestPath = join(place, "package.json");
102
+ const there = presence(manifestPath);
103
+ if (there.kind === "absent")
104
+ continue;
105
+ if (there.kind === "refused")
106
+ return there;
107
+ let manifest;
108
+ try {
109
+ manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
110
+ }
111
+ catch (error) {
112
+ return { kind: "refused", why: `${manifestPath} can't be read (${error.code ?? "not JSON"})` };
113
+ }
114
+ if (manifest.name === name)
115
+ return { kind: "present", path: join(place, "bin", "toolroll-tui") };
116
+ }
117
+ return { kind: "absent" };
118
+ }
119
+ function checkoutCandidate(root) {
120
+ for (const marker of [join(root, ".git"), join(root, "tui", "Cargo.toml")]) {
121
+ const there = presence(marker);
122
+ if (there.kind !== "present")
123
+ return there;
124
+ }
125
+ const built = join(root, "tui", "target", "release", "toolroll-tui");
126
+ const there = presence(built);
127
+ return there.kind === "present" ? { kind: "present", path: built } : there;
128
+ }
129
+ export function chooseTuiBinary(input) {
130
+ const ignored = (input.env["TOOLROLL_TUI_BINARY"] ?? "") === "" ? undefined
131
+ : "TOOLROLL_TUI_BINARY is ignored: pass --tui-binary <absolute path> to use your own build";
132
+ const note = (choice, more) => {
133
+ const notice = [more, ignored].filter(one => one !== undefined).join(". ");
134
+ return notice === "" ? choice : { ...choice, notice };
135
+ };
136
+ if (input.env["TOOLROLL_SCREEN"] === "classic")
137
+ return note({ ok: false, why: "TOOLROLL_SCREEN=classic asks for it" });
138
+ if (input.screenReader)
139
+ return note({ ok: false, why: "it works with screen readers" });
140
+ const root = input.packageRoot ?? defaultRoot();
141
+ const uid = input.uid ?? process.getuid?.();
142
+ const key = `${input.platform}-${input.arch}`;
143
+ const name = Object.hasOwn(TUI_PACKAGES, key) ? TUI_PACKAGES[key] : undefined;
144
+ let binary;
145
+ let notice;
146
+ if (input.devBinary !== undefined && input.devBinary !== null) {
147
+ if (!isAbsolute(input.devBinary))
148
+ return note({ ok: false, why: "--tui-binary needs an absolute path" });
149
+ const trusted = trustedBinary(input.devBinary, uid);
150
+ if (!trusted.ok)
151
+ return note({ ok: false, why: `--tui-binary ${input.devBinary} can't be trusted: ${trusted.why}` });
152
+ binary = trusted.real;
153
+ notice = `Using your own terminal workbench build at ${binary} (--tui-binary)`;
154
+ }
155
+ else {
156
+ const candidates = [
157
+ () => (name === undefined ? { kind: "absent" } : bundledCandidate(root, key)),
158
+ () => (name === undefined ? { kind: "absent" } : packageCandidate(root, name)),
159
+ () => checkoutCandidate(root),
160
+ ];
161
+ let found = null;
162
+ for (const candidate of candidates) {
163
+ const one = candidate();
164
+ if (one.kind === "absent")
165
+ continue;
166
+ if (one.kind === "refused")
167
+ return note({ ok: false, why: `the terminal workbench can't be trusted: ${one.why}` });
168
+ found = one.path ?? null;
169
+ break;
170
+ }
171
+ if (found === null) {
172
+ if (name === undefined)
173
+ return note({ ok: false, why: `the terminal workbench isn't built for ${input.platform}-${input.arch} yet` });
174
+ return note({ ok: false, why: "the terminal workbench isn't installed on this computer" });
175
+ }
176
+ const trusted = trustedBinary(found, uid);
177
+ if (!trusted.ok)
178
+ return note({ ok: false, why: `the terminal workbench at ${found} can't be trusted: ${trusted.why}` });
179
+ binary = trusted.real;
180
+ }
181
+ const identity = identityOf(binary);
182
+ if (identity === null)
183
+ return note({ ok: false, why: `the terminal workbench at ${binary} can't be checked` }, notice);
184
+ const check = (input.selfCheck ?? defaultSelfCheck)(binary);
185
+ if (check.status === TUI_EXIT.unprotected)
186
+ return note({ ok: false, why: "the terminal workbench couldn't turn off crash dumps on this computer" }, notice);
187
+ if (check.status !== 0)
188
+ return note({ ok: false, why: `the terminal workbench didn't start (${check.error ?? (check.status === null ? "no answer" : `exit ${check.status}`)})` }, notice);
189
+ const said = /^toolroll-tui \S+ contract ([0-9a-f]{64})$/.exec(check.stdout.trim());
190
+ if (said === null || said[1] !== input.contract)
191
+ return note({ ok: false, why: "the terminal workbench is from another Toolroll version" }, notice);
192
+ if (!sameIdentity(identityOf(binary), identity))
193
+ return note({ ok: false, why: "the terminal workbench changed while it was being checked" }, notice);
194
+ return note({ ok: true, binary, identity }, notice);
195
+ }
196
+ export async function runTuiBinary(input) {
197
+ const args = ["--control-fd", "4", ...(input.session.owned() ? ["--owned"] : []), ...(input.project === null ? [] : ["--project", input.project])];
198
+ if (!isAbsolute(input.binary))
199
+ throw new Error("the terminal workbench is started only by its checked, absolute path");
200
+ if (input.identity !== undefined && !sameIdentity(identityOf(input.binary), input.identity))
201
+ return "changed";
202
+ const { child, send } = spawnHoldingLink(input.binary, args, input.link, {
203
+ ...(input.cwd === undefined ? {} : { cwd: input.cwd }), ...(input.env === undefined ? {} : { env: input.env }),
204
+ ...(input.stdio === undefined ? {} : { stdio: input.stdio }), control: true,
205
+ });
206
+ input.started?.(child);
207
+ let sentLink = false;
208
+ let expired = false;
209
+ let killTimer;
210
+ const running = () => child.exitCode === null && child.signalCode === null;
211
+ const readyTimer = setTimeout(() => {
212
+ if (sentLink)
213
+ return;
214
+ expired = true;
215
+ if (!running())
216
+ return;
217
+ child.kill("SIGTERM");
218
+ killTimer = setTimeout(() => { if (running())
219
+ child.kill("SIGKILL"); }, input.killAfterMs ?? KILL_AFTER_MS);
220
+ }, input.readyMs ?? READY_MS);
221
+ const asks = child.stdio[4];
222
+ if (asks !== null && asks !== undefined && "on" in asks) {
223
+ let pending = "";
224
+ asks.on("error", () => { });
225
+ asks.on("data", (chunk) => {
226
+ pending += chunk.toString("utf8");
227
+ if (pending.length > ASK_CAP && !pending.includes("\n")) {
228
+ pending = "\u0000";
229
+ return;
230
+ }
231
+ let at;
232
+ while ((at = pending.indexOf("\n")) >= 0) {
233
+ const line = pending.slice(0, at);
234
+ pending = pending.slice(at + 1);
235
+ if (line.startsWith("\u0000") || line.length > ASK_CAP)
236
+ continue;
237
+ let ask = null;
238
+ try {
239
+ ask = JSON.parse(line);
240
+ }
241
+ catch {
242
+ ask = null;
243
+ }
244
+ if (ask !== null && typeof ask === "object" && ask["ready"] === READY) {
245
+ if (!sentLink && !expired) {
246
+ sentLink = send();
247
+ clearTimeout(readyTimer);
248
+ }
249
+ continue;
250
+ }
251
+ if (ask !== null && typeof ask === "object" && ask["want"] === "browser") {
252
+ void input.session.openBrowser().catch(() => "The browser couldn't be opened.").then(said => {
253
+ if ("write" in asks && !child.killed && child.exitCode === null)
254
+ asks.write(`${JSON.stringify({ said })}\n`);
255
+ });
256
+ }
257
+ }
258
+ });
259
+ }
260
+ const forward = (signal) => () => { if (child.exitCode === null)
261
+ child.kill(signal); };
262
+ const handlers = ["SIGTERM", "SIGHUP"].map(signal => [signal, forward(signal)]);
263
+ for (const [signal, handler] of handlers)
264
+ process.on(signal, handler);
265
+ const code = await new Promise(resolve => {
266
+ child.once("error", () => resolve(-1));
267
+ child.once("exit", (exit, signal) => resolve(signal === null ? exit : null));
268
+ });
269
+ for (const [signal, handler] of handlers)
270
+ process.off(signal, handler);
271
+ clearTimeout(readyTimer);
272
+ clearTimeout(killTimer);
273
+ if (!sentLink)
274
+ return "classic";
275
+ if (code === TUI_EXIT.stop)
276
+ return "stop";
277
+ if (code === TUI_EXIT.keep)
278
+ return "keep";
279
+ if (code === TUI_EXIT.classic || code === TUI_EXIT.unprotected || code === -1)
280
+ return "classic";
281
+ return "leave";
282
+ }
@@ -8,7 +8,7 @@ import { checklistLines, mergeChecklistOf } from "./merge-checklist.js";
8
8
  import { runAsLocalOwner } from "./local-owner.js";
9
9
  import { snapshotLiveRuns } from "./peek-cli.js";
10
10
  import { loadProjectRegistry } from "./repos.js";
11
- import { describeScope } from "./scope.js";
11
+ import { approvalSummaryOf, describeScope, summaryContextOf } from "./approval-summary.js";
12
12
  import { localModeOf, openStoreReadOnly } from "./store.js";
13
13
  import { routeChangeOf } from "./route-change.js";
14
14
  import { flakyCount } from "./flaky.js";
@@ -88,7 +88,9 @@ export function createTuiSource(options) {
88
88
  const task = record(answer["task"]), work = record(answer["work"]), status = record(work["status"]);
89
89
  const store = read();
90
90
  const scope = store === null ? null : store.getScope(id);
91
- const plan = scope === null || scope.approvedDigest === scope.digest ? null : { digest: scope.digest, lines: [...(store === null ? [] : routeLines(store, id)), ...describeScope(scope)].map(line => terminalText(line)) };
91
+ const context = store === null || scope === null ? null : summaryContextOf(store, id, scope, clock());
92
+ const plan = scope === null || scope.approvedDigest === scope.digest ? null : { digest: scope.digest, lines: [...(store === null ? [] : routeLines(store, id)), ...describeScope(scope, undefined, null, context)].map(line => terminalText(line)),
93
+ ...(context === null ? {} : { terms: approvalSummaryOf(scope, context).key }) };
92
94
  let hasResult = false;
93
95
  try {
94
96
  hasResult = store !== null && assignmentOf(store, id, clock(), { principal: "operator", repos: null })?.receipt != null;
@@ -149,7 +151,7 @@ export function createTuiSource(options) {
149
151
  done = "Building. It starts next.";
150
152
  break;
151
153
  case "approve":
152
- argv = ["task", "approve", act.id, "--yes", "--digest", act.digest];
154
+ argv = ["task", "approve", act.id, "--yes", "--digest", act.digest, ...(act.terms === undefined ? [] : ["--terms", act.terms])];
153
155
  done = "Approved. An agent starts on it.";
154
156
  break;
155
157
  case "stop":
package/dist/tui.js CHANGED
@@ -65,9 +65,9 @@ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#isr
65
65
  `;if(this.lastOutputHeight>=this.options.stdout.rows){let Q=Nu(this.options.stdout);Q&&this.options.stdout.write(Fu),this.options.stdout.write(nt.clearTerminal+this.fullStaticOutput+a),this.lastOutput=a,this.lastOutputToRender=I,this.lastOutputHeight=l,this.log.sync(I),Q&&this.options.stdout.write(Kn);return}if(E){let Q=Nu(this.options.stdout);Q&&this.options.stdout.write(Fu),this.log.clear(),this.options.stdout.write(g),this.log(I),Q&&this.options.stdout.write(Kn)}else(a!==this.lastOutput||this.log.isCursorDirty())&&this.throttledLog(I);this.lastOutput=a,this.lastOutputToRender=I,this.lastOutputHeight=l};render(u){let a=UE.default.createElement(Yn.Provider,{value:{isScreenReaderEnabled:this.isScreenReaderEnabled}},UE.default.createElement(KQ,{stdin:this.options.stdin,stdout:this.options.stdout,stderr:this.options.stderr,exitOnCtrlC:this.options.exitOnCtrlC,writeToStdout:this.writeToStdout,writeToStderr:this.writeToStderr,setCursorPosition:this.setCursorPosition,onExit:this.handleAppExit},u));this.options.concurrent?de.updateContainer(a,this.container,null,xo):(de.updateContainerSync(a,this.container,null,xo),de.flushSyncWork())}writeToStdout(u){if(this.isUnmounted)return;if(this.options.debug){this.options.stdout.write(u+this.fullStaticOutput+this.lastOutput);return}if(Xe){this.options.stdout.write(u);return}let a=Nu(this.options.stdout);a&&this.options.stdout.write(Fu),this.log.clear(),this.options.stdout.write(u),this.restoreLastOutput(),a&&this.options.stdout.write(Kn)}writeToStderr(u){if(this.isUnmounted)return;if(this.options.debug){this.options.stderr.write(u),this.options.stdout.write(this.fullStaticOutput+this.lastOutput);return}if(Xe){this.options.stderr.write(u);return}let a=Nu(this.options.stdout);a&&this.options.stdout.write(Fu),this.log.clear(),this.options.stderr.write(u),this.restoreLastOutput(),a&&this.options.stdout.write(Kn)}unmount(u){if(this.isUnmounted||this.isUnmounting)return;this.isUnmounting=!0,this.beforeExitHandler&&(Ui.off("beforeExit",this.beforeExitHandler),this.beforeExitHandler=void 0);let a=this.options.stdout,l=!a.destroyed&&!a.writableEnded&&(a.writable??!0),g=v=>{typeof v.flush=="function"&&(l?v.flush():typeof v.cancel=="function"&&v.cancel())};g(this.throttledOnRender??{}),l&&(!this.throttledOnRender||!this.hasPendingThrottledRender&&this.fullStaticOutput==="")&&(this.calculateLayout(),this.onRender()),this.isUnmounted=!0,this.unsubscribeExit(),typeof this.restoreConsole=="function"&&this.restoreConsole(),typeof this.unsubscribeResize=="function"&&this.unsubscribeResize(),this.cancelKittyDetection&&this.cancelKittyDetection();let E=this.throttledLog;if(g(E),l){if(this.kittyProtocolEnabled)try{this.options.stdout.write("\x1B[<u")}catch{}Xe?this.options.stdout.write(this.lastOutput+`
66
66
  `):this.options.debug||this.log.done()}this.kittyProtocolEnabled=!1,this.options.concurrent?de.updateContainer(null,this.container,null,xo):(de.updateContainerSync(null,this.container,null,xo),de.flushSyncWork()),Hi.delete(this.options.stdout);let{exitResult:s}=this,I=()=>{HE(u)?this.rejectExitPromise(u):this.resolveExitPromise(s)},Q=u!==void 0&&!HE(u),S=a._writableState!==void 0||a.writableLength!==void 0;Q?I():l&&S?this.options.stdout.write("",I):setImmediate(I)}async waitUntilExit(){return this.exitPromise||=new Promise((u,a)=>{this.resolveExitPromise=u,this.rejectExitPromise=a}),this.beforeExitHandler||(this.beforeExitHandler=()=>{this.unmount()},Ui.once("beforeExit",this.beforeExitHandler)),this.exitPromise}clear(){!Xe&&!this.options.debug&&(this.log.clear(),this.log.sync(this.lastOutputToRender||this.lastOutput+`
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";!Xe&&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=Iy(g);g=[],Q.length>0&&a.unshift(Buffer.from(Q))},s=Q=>{let S=typeof Q=="string"?Buffer.from(Q):Q;for(let v of S)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 fy=(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,...Dy(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=fy,Dy=(e={})=>e instanceof Qy?{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 py=oA(Zl(),1);var To=oA(SA(),1);var XQ=oA(SA(),1);var my=oA(SA(),1);var hy=oA(SA(),1);var LE=oA(SA(),1);import{Buffer as yy}from"node:buffer";var Sy=/^(?:\x1b)([a-zA-Z0-9])$/,Fy=/^(?:\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"],Ny=e=>["[a","[b","[c","[d","[e","[2$","[3$","[5$","[6$","[7$","[8$","[Z"].includes(e),Ry=e=>["Oa","Ob","Oc","Od","Oe","[2^","[3^","[5^","[6^","[7^","[8^"].includes(e),WQ=/^\x1b\[(\d+)(?:;(\d+)(?::(\d+))?(?:;([\d:]+))?)?u$/,vy=/^\x1b\[(\d+);(\d+):(\d+)([A-Za-z~])$/,wy={A:"up",B:"down",C:"right",D:"left",E:"clear",F:"end",H:"home",P:"f1",Q:"f2",R:"f3",S:"f4"},Gy={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&Pe.ctrl),shift:!!(e&Pe.shift),meta:!!(e&Pe.meta),option:!!(e&Pe.alt),super:!!(e&Pe.super),hyper:!!(e&Pe.hyper),capsLock:!!(e&Pe.capsLock),numLock:!!(e&Pe.numLock)}}var My=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(S=>bE(parseInt(S,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}},xy=e=>{let u=vy.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==="~"?Gy[a]:wy[E];return s?{name:s,...Af(l),eventType:$Q(g),sequence:e,raw:e,isKittyProtocol:!0,isPrintable:!1}:null},Hy=(e="")=>{let u;yy.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=My(e);if(a)return a;let l=xy(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
- `)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=Sy.exec(e))g.meta=!0,g.shift=/^[A-Z]$/.test(u[1]);else if(u=Fy.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=Ny(s)||g.shift,g.ctrl=Ry(s)||g.ctrl}return g},tf=Hy;var ef=oA(SA(),1);var Uy=()=>(0,ef.useContext)(Ro),bo=Uy;var Ty=(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),S={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])&&(S.shift=!0),(!(v==="c"&&S.ctrl)||!g)&&de.batchedUpdates(()=>{e(v,S)})};return E?.on("input",s),()=>{E?.removeListener("input",s)}},[u.isActive,a,g,e])},OE=Ty;var nf=oA(SA(),1);var by=()=>(0,nf.useContext)(No),kE=by;var Ly=oA(SA(),1);var Oy=oA(SA(),1);var JE=oA(SA(),1);var ky=oA(SA(),1);var Jy=oA(SA(),1);var Lo=oA(SA(),1);import{pathToFileURL as A2}from"node:url";var Ky=["[data-ink-approve]",'[data-ink-act="accept"]',"[data-accept-result][data-primary-action]"],Yy=['[data-act="request-changes"]','[data-act="revise"]','a.result-feedback-link[href="#request-changes"]'],_y=['[data-act="retry"]','form[data-retry] button[type="submit"]','form[data-rebuild] button[type="submit"]'],zy=['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:Ky},tui:"ink"},{keys:"b",says:"Send back (opens its note)",web:{kind:"press",selectors:Yy},tui:"send-back"},{keys:"r",says:"Retry (presses the button on the page)",web:{kind:"press",selectors:_y},tui:"retry"},{keys:"p",says:"Ask for a plan (presses the button on the page)",web:{kind:"press",selectors:zy},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 jA=oA(SA(),1);var qy=/[‪-‮⁦-⁩]/g;function Xy(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(qy,"")}function af(e){return e.split(`
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=Sy.exec(e))g.meta=!0,g.shift=/^[A-Z]$/.test(u[1]);else if(u=Fy.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=Ny(s)||g.shift,g.ctrl=Ry(s)||g.ctrl}return g},tf=Hy;var ef=oA(SA(),1);var Uy=()=>(0,ef.useContext)(Ro),bo=Uy;var Ty=(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),S={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])&&(S.shift=!0),(!(v==="c"&&S.ctrl)||!g)&&de.batchedUpdates(()=>{e(v,S)})};return E?.on("input",s),()=>{E?.removeListener("input",s)}},[u.isActive,a,g,e])},OE=Ty;var nf=oA(SA(),1);var by=()=>(0,nf.useContext)(No),kE=by;var Ly=oA(SA(),1);var Oy=oA(SA(),1);var JE=oA(SA(),1);var ky=oA(SA(),1);var Jy=oA(SA(),1);var Lo=oA(SA(),1);import{pathToFileURL as A2}from"node:url";var Ky=["[data-ink-approve]",'[data-ink-act="accept"]',"[data-accept-result][data-primary-action]"],Yy=['[data-act="request-changes"]','[data-act="revise"]','a.result-feedback-link[href="#request-changes"]'],_y=['[data-act="retry"]','form[data-retry] button[type="submit"]','form[data-rebuild] button[type="submit"]'],zy=['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:Ky},tui:"ink"},{keys:"b",says:"Send back (opens its note)",web:{kind:"press",selectors:Yy},tui:"send-back"},{keys:"r",says:"Retry (presses the button on the page)",web:{kind:"press",selectors:_y},tui:"retry"},{keys:"p",says:"Ask for a plan (presses the button on the page)",web:{kind:"press",selectors:zy},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 Work",web:{kind:"go",href:"/"},tui:"list"},{keys:"?",says:"these shortcuts",web:{kind:"help"},tui:"help"}],uf=e=>e.split(" ").join(" then ");var jA=oA(SA(),1);var qy=/[‪-‮⁦-⁩]/g;function Xy(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(qy,"")}function af(e){return e.split(`
69
69
  `).map(Xy).join(`
70
- `)}var YE=["you","working","done"],lf={you:"Waiting on you",working:"Working",done:"Done"};var L=oA(qa(),1);function NA({children:e,...u}){return(0,L.jsx)(eA,{...u,children:af(e)})}var Vy={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"},Wy=["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)} ${Vy[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 Py(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 $y=e=>e.group===null?"Other":lf[e.group];function Ef(e,u){return!u||e.status!=="Planning"&&e.status!=="Building"?e:{...e,status:"Waiting",detail:"Toolroll's background worker isn't running.",liveRunId:null}}var sf=e=>[...e].filter(u=>u>=" "&&u!=="").join("");function Bf({source:e,session:u,onExit:a,pollMs:l=1e3}){let{exit:g}=kE(),[E,s]=(0,jA.useState)(null),[I,Q]=(0,jA.useState)(null),[S,v]=(0,jA.useState)(0),[N,p]=(0,jA.useState)({kind:"main"}),[M,U]=(0,jA.useState)(null),[O,H]=(0,jA.useState)(null),[W,FA]=(0,jA.useState)([]),[dA,EA]=(0,jA.useState)(()=>u.stopped?.()??null),GA=(0,jA.useRef)(null),kA=(0,jA.useRef)(0),JA=(0,jA.useRef)(!1),HA=Py(E?.rows??[]).map(y=>Ef(y,dA!==null)),TA=HA[Math.min(S,Math.max(HA.length-1,0))],It=(0,jA.useCallback)(async()=>{let y=await e.snapshot();s(y),y.rows.length===0&&Q(await e.setup())},[e]);(0,jA.useEffect)(()=>{It()},[It]),(0,jA.useEffect)(()=>{let y=setInterval(()=>{let G=u.stopped?.()??null;EA(P=>P===G?P:G),kA.current+=1;let K=e.changed();(K!==GA.current||kA.current%5===0)&&(GA.current=K,It())},l);return()=>clearInterval(y)},[e,u,It,l]);let kt=TA?.id??null;(0,jA.useEffect)(()=>{if(kt===null){FA([]);return}FA(e.live(kt));let y=setInterval(()=>FA(e.live(kt)),l);return()=>clearInterval(y)},[e,kt,l]);let Qt=y=>{JA.current||(JA.current=!0,g(),a?.(y))},vt=(0,jA.useRef)(!1),bA=async(y,G="Working…")=>{H(G);try{let K=await e.act(y);return K.ok?(U(K.message),await It(),!0):(K.needsPassword?p({kind:"password",message:K.message}):U(K.message),!1)}finally{H(null)}},ft=async(y,G)=>{let K=await e.task(y);K===null?U("That task can't be read now."):G(K)},Jt=y=>ft(y,G=>{G.plan===null?U("No plan is waiting for your approval on this task."):p({kind:"approve",task:G})}),bt=async(y,G=!1)=>{let K=await e.result(y);if(K===null){U("This task has no finished result to accept.");return}p({kind:"accept",result:K,reason:"",changed:G})},vA=y=>ft(y,G=>{G.plan!==null?p({kind:"approve",task:G}):G.hasResult?bt(y):U("No plan or result is waiting for you on this task.")}),Dt=async(y,G,K)=>{H("Working…");let P;try{P=await e.act({kind:"complete",id:y.id,runId:y.runId,digest:y.digest,checked:G,reason:K})}finally{H(null)}if(P.ok){U(P.message),p(u.shouldAskBackground()?{kind:"background"}:{kind:"main"}),await It();return}if(P.changed===!0){p({kind:"main"}),U("This result changed while you were reading it. Nothing was accepted."),await bt(y.id,!0);return}P.needsPassword?p({kind:"password",message:P.message}):(U(P.message),p({kind:"main"}))},Ue=async y=>{let G=await e.result(y);if(G===null){U("This task has no finished result to send back.");return}p({kind:"compose",purpose:"revise",id:y,text:"",project:0,runId:G.runId})},Te=y=>ft(y,G=>{G.retry==null?U("Nothing to retry on this task."):p({kind:"retry",task:G,retry:G.retry})}),ae=y=>ft(y,G=>{G.planAsk==null?U("This task can't be planned now."):bA({kind:"plan",id:y,source:G.planAsk.source})}),be=(y,G)=>{if(G===null){U("Nothing is running on this task.");return}bA({kind:"stop",id:y,runId:G})},Zt=(y,G)=>{let K=y.decisions[0],P=K?.options[G];K===void 0||P===void 0||bA({kind:"answer",decision:K.id,option:P.id}).then(MA=>{MA&&p({kind:"main"})})},VA=()=>{H("Opening the browser…"),u.openBrowser().then(y=>{U(y),H(null)})},le=()=>{u.owned()?p({kind:"quit"}):Qt("leave")},Kt=(y,G,K)=>{if(vt.current&&(vt.current=!1,y==="h"||y==="t"))return p({kind:"main"}),!0;if(y==="g")return vt.current=!0,!0;if(y==="/"){let P=KE.find(MA=>MA.keys==="/").tui;return U(typeof P=="string"?null:P.none),!0}return y==="n"?(p({kind:"compose",purpose:"new",id:null,text:"",project:0,runId:null}),!0):y==="w"?(VA(),!0):y==="?"?(p({kind:"help"}),!0):y==="q"?(le(),!0):G===null?!1:y==="a"?(vA(G),!0):y==="s"?(be(G,K),!0):y==="b"?(Ue(G),!0):y==="r"?(Te(G),!0):y==="c"?(bt(G),!0):y==="p"?(ae(G),!0):!1},it=(y,G)=>{if(O===null){if(G.ctrl&&y==="c"){le();return}switch(N.kind){case"main":{if(y==="j"||G.downArrow){v(K=>Math.min(K+1,Math.max(HA.length-1,0)));return}if(y==="k"||G.upArrow){v(K=>Math.max(K-1,0));return}if(G.return&&TA!==void 0){ft(TA.id,K=>p({kind:"task",task:K}));return}if(G.escape){U(null);return}if(y==="s"&&HA.length===0&&I?.sample===!0){bA({kind:"sample"},"Adding the sample project…");return}Kt(y,TA?.id??null,TA?.liveRunId??null);return}case"task":{if(G.escape||G.leftArrow){p({kind:"main"});return}if(/^[1-9]$/.test(y)){Zt(N.task,Number(y)-1);return}Kt(y,N.task.id,N.task.liveRunId);return}case"approve":{if(G.escape||y==="n"){p({kind:"main"}),U("Nothing approved.");return}if(y==="y"){let{task:K}=N;bA({kind:"approve",id:K.id,digest:K.plan.digest}).then(P=>{P&&p({kind:"main"})})}return}case"retry":{if(G.escape||y==="n"){p({kind:"main"}),U("Nothing retried.");return}if(y==="y"){let{task:K,retry:P}=N;bA({kind:"retry",id:K.id,runId:P.runId,digest:P.digest}).then(()=>p(MA=>MA.kind==="retry"?{kind:"main"}:MA))}return}case"accept":{let{result:K}=N,P=()=>{p({kind:"main"}),U("Nothing accepted.")};if(G.escape){P();return}if(!K.ready||K.owed!=="exception"){if(y==="w"){VA();return}if(!K.ready){(y==="n"||y==="q")&&P();return}if(y==="n"){P();return}y==="y"&&Dt(K,K.owed==="person-check",null);return}if(G.backspace||G.delete){p({...N,reason:N.reason.slice(0,-1)});return}if(G.return){let tt=N.reason.trim();tt!==""&&Dt(K,!1,tt);return}let MA=sf(y);MA!==""&&p({...N,reason:N.reason+MA});return}case"build":{if(G.escape){p({kind:"main"}),U("Nothing started.");return}if(y==="p"){let{text:K,repo:P}=N;p({kind:"main"}),bA({kind:"new",text:K,repo:P});return}if(G.return){let{preview:K,digest:P}=N.terms;bA({kind:"build",preview:K,digest:P}).then(MA=>{MA&&p({kind:"main"})})}return}case"compose":{if(G.escape){p({kind:"main"});return}let K=E?.projects??[];if(G.tab&&N.purpose==="new"&&K.length>1){p({...N,project:(N.project+1)%K.length});return}if(G.backspace||G.delete){p({...N,text:N.text.slice(0,-1)});return}if(G.return){let MA=N.text.trim();if(MA==="")return;let tt=N.purpose==="new"?{kind:"new",text:MA,repo:K[N.project]??null}:{kind:"revise",id:N.id,text:MA,runId:N.runId};if(p({kind:"main"}),tt.kind==="new"){H("Reading it…"),e.fastTerms(MA,tt.repo).catch(()=>null).then(Vt=>{H(null),Vt===null?bA(tt):p({kind:"build",terms:Vt,text:MA,repo:tt.repo})});return}bA(tt);return}let P=sf(y);P!==""&&p({...N,text:N.text+P});return}case"quit":{y==="s"?Qt("stop"):y==="b"?Qt("keep"):G.escape&&p({kind:"main"});return}case"background":{let K=y==="y"||y==="Y";if(!K&&y!=="n"&&y!=="N"&&!G.return)return;p({kind:"main"}),H(K?"Moving Toolroll to the background…":"Saving…"),u.answerBackground(K).then(P=>{U(P),H(null)});return}default:(G.escape||G.return||y==="q")&&p({kind:"main"})}}},aA=(0,jA.useRef)(it);aA.current=it,OE((0,jA.useCallback)((y,G)=>aA.current(y,G),[]));let jt=O??dA??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)(NA,{bold:!0,children:E.needsYou}):(0,L.jsx)(eA,{dimColor:!0,children:"Nothing needs you"}),E?.learning?(0,L.jsx)(NA,{dimColor:!0,children:E.learning}):null]}),lA(),jt===null?null:(0,L.jsx)(NA,{...O===null&&dA!==null?{bold:!0}:{},children:jt}),(0,L.jsx)(eA,{dimColor:!0,children:V()})]});function V(){switch(N.kind){case"main":return HA.length===0?`${I?.sample===!0?"s sample project · ":""}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${N.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 N.result.ready?N.result.owed==="person-check"?"y yes, it looks right · n no · w open in the browser · Esc cancel":N.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 N.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(N.kind){case"help":return(0,L.jsxs)(CA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Keys"}),Wy.map(y=>(0,L.jsx)(eA,{children:y},y))]});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)(NA,{children:N.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:"}),N.terms.terms.map((y,G)=>(0,L.jsx)(NA,{children:`${y.label}: ${y.words}`},G))]});case"compose":{let y=E?.projects[N.project]??null;return(0,L.jsxs)(CA,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:N.purpose==="new"?"New task":"What should change?"}),N.purpose==="new"&&y!==null?(0,L.jsx)(NA,{dimColor:!0,children:`In ${y}`}):null,(0,L.jsxs)(eA,{children:[(0,L.jsx)(NA,{children:N.text}),(0,L.jsx)(eA,{inverse:!0,children:" "})]})]})}case"accept":{let{result:y}=N;return(0,L.jsxs)(CA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(NA,{bold:!0,children:`Accept this result? ${y.title}`}),(0,L.jsx)(NA,{dimColor:!0,children:`Build #${y.runId}`}),N.changed?(0,L.jsx)(eA,{bold:!0,children:"This result changed while you were reading it. This is the new one."}):null,y.summary.length===0?null:(0,L.jsx)(CA,{flexDirection:"column",marginTop:1,children:y.summary.map((G,K)=>(0,L.jsx)(NA,{children:G},K))}),(0,L.jsxs)(CA,{flexDirection:"column",marginTop:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Changed files"}),y.files===null?(0,L.jsx)(eA,{children:"The changed files couldn't be read. Press w to see them in the browser."}):y.files.names.length===0?(0,L.jsx)(eA,{children:"None."}):(0,L.jsxs)(L.Fragment,{children:[y.files.names.map(G=>(0,L.jsx)(NA,{children:` ${G}`},G)),y.files.more>0?(0,L.jsx)(eA,{children:` and ${y.files.more} more`}):null]})]}),y.requirements.length===0?null:(0,L.jsxs)(CA,{flexDirection:"column",marginTop:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Requirements"}),y.requirements.map((G,K)=>(0,L.jsx)(NA,{children:` ${G.word}: ${G.statement}`},K))]}),y.checks.length===0?null:(0,L.jsx)(CA,{flexDirection:"column",marginTop:1,children:y.checks.map((G,K)=>(0,L.jsx)(NA,{...K===0?{bold:!0}:{},children:G},K))}),(0,L.jsx)(CA,{flexDirection:"column",marginTop:1,children:y.ready?y.owed==="person-check"?(0,L.jsx)(eA,{bold:!0,children:"Did you check it yourself? (y/n)"}):y.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)(NA,{children:N.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."}),y.blockers.map((G,K)=>(0,L.jsx)(NA,{children:G},K))]})})]})}case"retry":return(0,L.jsxs)(CA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(NA,{bold:!0,children:`Retry build #${N.retry.runId}? ${N.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)(NA,{bold:!0,children:`Approve this plan? ${N.task.title}`}),N.task.plan.lines.map((y,G)=>(0,L.jsx)(NA,{children:y},G))]});case"task":{let y=Ef(N.task,dA!==null),G=y.decisions[0];return(0,L.jsxs)(CA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(NA,{bold:!0,children:y.title}),(0,L.jsx)(NA,{children:`${y.status}${y.detail===""?"":` · ${y.detail}`}`}),y.plan===null?null:(0,L.jsx)(eA,{children:"A plan waits for your approval (a)."}),(y.ready?.length??0)===0?null:(0,L.jsx)(CA,{flexDirection:"column",marginTop:1,children:y.ready.map((K,P)=>(0,L.jsx)(NA,{...P===0?{bold:!0}:{},children:K},P))}),G===void 0?null:(0,L.jsxs)(CA,{flexDirection:"column",marginTop:1,children:[(0,L.jsx)(NA,{bold:!0,children:G.question}),G.options.map((K,P)=>(0,L.jsx)(NA,{children:`${P+1} ${K.label}`},K.id))]}),W.length===0?null:(0,L.jsx)(CA,{flexDirection:"column",marginTop:1,children:W.slice(-12).map((K,P)=>(0,L.jsx)(NA,{dimColor:!0,children:K},P))})]})}default:return E===null?(0,L.jsx)(eA,{dimColor:!0,children:"Loading…"}):HA.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((y,G)=>(0,L.jsx)(NA,{children:y},G))]}):(0,L.jsxs)(CA,{children:[(0,L.jsx)(CA,{flexDirection:"column",width:"45%",borderStyle:"single",paddingX:1,children:HA.map((y,G)=>(0,L.jsxs)(jA.Fragment,{children:[G===0||HA[G-1].group!==y.group?(0,L.jsx)(eA,{bold:!0,children:$y(y)}):null,(0,L.jsxs)(eA,{inverse:y===TA,wrap:"truncate-end",children:[y===TA?"> ":" ",(0,L.jsx)(NA,{children:y.title})," ",(0,L.jsx)(NA,{...y.needsYou?{bold:!0}:{dimColor:!0},children:y.status})]})]},y.id))}),(0,L.jsx)(CA,{flexDirection:"column",flexGrow:1,borderStyle:"single",paddingX:1,children:TA===void 0?(0,L.jsx)(eA,{dimColor:!0,children:"Nothing selected"}):(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(NA,{bold:!0,wrap:"truncate-end",children:TA.title}),(0,L.jsx)(NA,{children:`${TA.status}${TA.detail===""?"":` · ${TA.detail}`}`}),W.length===0?(0,L.jsx)(eA,{dimColor:!0,children:TA.liveRunId===null?"No agent is working on it now.":"Waiting for output…"}):W.slice(-12).map((y,G)=>(0,L.jsx)(NA,{dimColor:!0,wrap:"truncate-end",children:y},G))]})})]})}}}function cf(){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 Qf=oA(qa(),1);async function t2(e=cf(),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,Qf.jsx)(Bf,{source:e,session:u,onExit:g=>{a=g}}),{exitOnCtrlC:!1}).waitUntilExit(),a}var If=process.argv[1];If!==void 0&&import.meta.url===A2(If).href&&t2().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=oA(qa(),1);function NA({children:e,...u}){return(0,L.jsx)(eA,{...u,children:af(e)})}var Vy={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"},Wy=["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)} ${Vy[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 Py(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 $y=e=>e.group===null?"Other":lf[e.group];function Ef(e,u){return!u||e.status!=="Planning"&&e.status!=="Building"?e:{...e,status:"Waiting",detail:"Toolroll's background worker isn't running.",liveRunId:null}}var sf=e=>[...e].filter(u=>u>=" "&&u!=="").join("");function Bf({source:e,session:u,onExit:a,pollMs:l=1e3}){let{exit:g}=kE(),[E,s]=(0,jA.useState)(null),[I,Q]=(0,jA.useState)(null),[S,v]=(0,jA.useState)(0),[N,p]=(0,jA.useState)({kind:"main"}),[M,U]=(0,jA.useState)(null),[O,H]=(0,jA.useState)(null),[W,FA]=(0,jA.useState)([]),[dA,EA]=(0,jA.useState)(()=>u.stopped?.()??null),GA=(0,jA.useRef)(null),kA=(0,jA.useRef)(0),JA=(0,jA.useRef)(!1),HA=Py(E?.rows??[]).map(y=>Ef(y,dA!==null)),TA=HA[Math.min(S,Math.max(HA.length-1,0))],It=(0,jA.useCallback)(async()=>{let y=await e.snapshot();s(y),y.rows.length===0&&Q(await e.setup())},[e]);(0,jA.useEffect)(()=>{It()},[It]),(0,jA.useEffect)(()=>{let y=setInterval(()=>{let G=u.stopped?.()??null;EA(P=>P===G?P:G),kA.current+=1;let K=e.changed();(K!==GA.current||kA.current%5===0)&&(GA.current=K,It())},l);return()=>clearInterval(y)},[e,u,It,l]);let kt=TA?.id??null;(0,jA.useEffect)(()=>{if(kt===null){FA([]);return}FA(e.live(kt));let y=setInterval(()=>FA(e.live(kt)),l);return()=>clearInterval(y)},[e,kt,l]);let Qt=y=>{JA.current||(JA.current=!0,g(),a?.(y))},vt=(0,jA.useRef)(!1),bA=async(y,G="Working…")=>{H(G);try{let K=await e.act(y);return K.ok?(U(K.message),await It(),!0):(K.needsPassword?p({kind:"password",message:K.message}):U(K.message),!1)}finally{H(null)}},ft=async(y,G)=>{let K=await e.task(y);K===null?U("That task can't be read now."):G(K)},Jt=y=>ft(y,G=>{G.plan===null?U("No plan is waiting for your approval on this task."):p({kind:"approve",task:G})}),bt=async(y,G=!1)=>{let K=await e.result(y);if(K===null){U("This task has no finished result to accept.");return}p({kind:"accept",result:K,reason:"",changed:G})},vA=y=>ft(y,G=>{G.plan!==null?p({kind:"approve",task:G}):G.hasResult?bt(y):U("No plan or result is waiting for you on this task.")}),Dt=async(y,G,K)=>{H("Working…");let P;try{P=await e.act({kind:"complete",id:y.id,runId:y.runId,digest:y.digest,checked:G,reason:K})}finally{H(null)}if(P.ok){U(P.message),p(u.shouldAskBackground()?{kind:"background"}:{kind:"main"}),await It();return}if(P.changed===!0){p({kind:"main"}),U("This result changed while you were reading it. Nothing was accepted."),await bt(y.id,!0);return}P.needsPassword?p({kind:"password",message:P.message}):(U(P.message),p({kind:"main"}))},Ue=async y=>{let G=await e.result(y);if(G===null){U("This task has no finished result to send back.");return}p({kind:"compose",purpose:"revise",id:y,text:"",project:0,runId:G.runId})},Te=y=>ft(y,G=>{G.retry==null?U("Nothing to retry on this task."):p({kind:"retry",task:G,retry:G.retry})}),ae=y=>ft(y,G=>{G.planAsk==null?U("This task can't be planned now."):bA({kind:"plan",id:y,source:G.planAsk.source})}),be=(y,G)=>{if(G===null){U("Nothing is running on this task.");return}bA({kind:"stop",id:y,runId:G})},Zt=(y,G)=>{let K=y.decisions[0],P=K?.options[G];K===void 0||P===void 0||bA({kind:"answer",decision:K.id,option:P.id}).then(MA=>{MA&&p({kind:"main"})})},VA=()=>{H("Opening the browser…"),u.openBrowser().then(y=>{U(y),H(null)})},le=()=>{u.owned()?p({kind:"quit"}):Qt("leave")},Kt=(y,G,K)=>{if(vt.current&&(vt.current=!1,y==="h"||y==="t"))return p({kind:"main"}),!0;if(y==="g")return vt.current=!0,!0;if(y==="/"){let P=KE.find(MA=>MA.keys==="/").tui;return U(typeof P=="string"?null:P.none),!0}return y==="n"?(p({kind:"compose",purpose:"new",id:null,text:"",project:0,runId:null}),!0):y==="w"?(VA(),!0):y==="?"?(p({kind:"help"}),!0):y==="q"?(le(),!0):G===null?!1:y==="a"?(vA(G),!0):y==="s"?(be(G,K),!0):y==="b"?(Ue(G),!0):y==="r"?(Te(G),!0):y==="c"?(bt(G),!0):y==="p"?(ae(G),!0):!1},it=(y,G)=>{if(O===null){if(G.ctrl&&y==="c"){le();return}switch(N.kind){case"main":{if(y==="j"||G.downArrow){v(K=>Math.min(K+1,Math.max(HA.length-1,0)));return}if(y==="k"||G.upArrow){v(K=>Math.max(K-1,0));return}if(G.return&&TA!==void 0){ft(TA.id,K=>p({kind:"task",task:K}));return}if(G.escape){U(null);return}if(y==="s"&&HA.length===0&&I?.sample===!0){bA({kind:"sample"},"Adding the sample project…");return}Kt(y,TA?.id??null,TA?.liveRunId??null);return}case"task":{if(G.escape||G.leftArrow){p({kind:"main"});return}if(/^[1-9]$/.test(y)){Zt(N.task,Number(y)-1);return}Kt(y,N.task.id,N.task.liveRunId);return}case"approve":{if(G.escape||y==="n"){p({kind:"main"}),U("Nothing approved.");return}if(y==="y"){let{task:K}=N;bA({kind:"approve",id:K.id,digest:K.plan.digest,...K.plan.terms===void 0?{}:{terms:K.plan.terms}}).then(P=>{P&&p({kind:"main"})})}return}case"retry":{if(G.escape||y==="n"){p({kind:"main"}),U("Nothing retried.");return}if(y==="y"){let{task:K,retry:P}=N;bA({kind:"retry",id:K.id,runId:P.runId,digest:P.digest}).then(()=>p(MA=>MA.kind==="retry"?{kind:"main"}:MA))}return}case"accept":{let{result:K}=N,P=()=>{p({kind:"main"}),U("Nothing accepted.")};if(G.escape){P();return}if(!K.ready||K.owed!=="exception"){if(y==="w"){VA();return}if(!K.ready){(y==="n"||y==="q")&&P();return}if(y==="n"){P();return}y==="y"&&Dt(K,K.owed==="person-check",null);return}if(G.backspace||G.delete){p({...N,reason:N.reason.slice(0,-1)});return}if(G.return){let tt=N.reason.trim();tt!==""&&Dt(K,!1,tt);return}let MA=sf(y);MA!==""&&p({...N,reason:N.reason+MA});return}case"build":{if(G.escape){p({kind:"main"}),U("Nothing started.");return}if(y==="p"){let{text:K,repo:P}=N;p({kind:"main"}),bA({kind:"new",text:K,repo:P});return}if(G.return){let{preview:K,digest:P}=N.terms;bA({kind:"build",preview:K,digest:P}).then(MA=>{MA&&p({kind:"main"})})}return}case"compose":{if(G.escape){p({kind:"main"});return}let K=E?.projects??[];if(G.tab&&N.purpose==="new"&&K.length>1){p({...N,project:(N.project+1)%K.length});return}if(G.backspace||G.delete){p({...N,text:N.text.slice(0,-1)});return}if(G.return){let MA=N.text.trim();if(MA==="")return;let tt=N.purpose==="new"?{kind:"new",text:MA,repo:K[N.project]??null}:{kind:"revise",id:N.id,text:MA,runId:N.runId};if(p({kind:"main"}),tt.kind==="new"){H("Reading it…"),e.fastTerms(MA,tt.repo).catch(()=>null).then(Vt=>{H(null),Vt===null?bA(tt):p({kind:"build",terms:Vt,text:MA,repo:tt.repo})});return}bA(tt);return}let P=sf(y);P!==""&&p({...N,text:N.text+P});return}case"quit":{y==="s"?Qt("stop"):y==="b"?Qt("keep"):G.escape&&p({kind:"main"});return}case"background":{let K=y==="y"||y==="Y";if(!K&&y!=="n"&&y!=="N"&&!G.return)return;p({kind:"main"}),H(K?"Moving Toolroll to the background…":"Saving…"),u.answerBackground(K).then(P=>{U(P),H(null)});return}default:(G.escape||G.return||y==="q")&&p({kind:"main"})}}},aA=(0,jA.useRef)(it);aA.current=it,OE((0,jA.useCallback)((y,G)=>aA.current(y,G),[]));let jt=O??dA??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)(NA,{bold:!0,children:E.needsYou}):(0,L.jsx)(eA,{dimColor:!0,children:"Nothing needs you"}),E?.learning?(0,L.jsx)(NA,{dimColor:!0,children:E.learning}):null]}),lA(),jt===null?null:(0,L.jsx)(NA,{...O===null&&dA!==null?{bold:!0}:{},children:jt}),(0,L.jsx)(eA,{dimColor:!0,children:V()})]});function V(){switch(N.kind){case"main":return HA.length===0?`${I?.sample===!0?"s sample project · ":""}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${N.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 N.result.ready?N.result.owed==="person-check"?"y yes, it looks right · n no · w open in the browser · Esc cancel":N.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 N.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(N.kind){case"help":return(0,L.jsxs)(CA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Keys"}),Wy.map(y=>(0,L.jsx)(eA,{children:y},y))]});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)(NA,{children:N.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:"}),N.terms.terms.map((y,G)=>(0,L.jsx)(NA,{children:`${y.label}: ${y.words}`},G))]});case"compose":{let y=E?.projects[N.project]??null;return(0,L.jsxs)(CA,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[(0,L.jsx)(eA,{bold:!0,children:N.purpose==="new"?"New task":"What should change?"}),N.purpose==="new"&&y!==null?(0,L.jsx)(NA,{dimColor:!0,children:`In ${y}`}):null,(0,L.jsxs)(eA,{children:[(0,L.jsx)(NA,{children:N.text}),(0,L.jsx)(eA,{inverse:!0,children:" "})]})]})}case"accept":{let{result:y}=N;return(0,L.jsxs)(CA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(NA,{bold:!0,children:`Accept this result? ${y.title}`}),(0,L.jsx)(NA,{dimColor:!0,children:`Build #${y.runId}`}),N.changed?(0,L.jsx)(eA,{bold:!0,children:"This result changed while you were reading it. This is the new one."}):null,y.summary.length===0?null:(0,L.jsx)(CA,{flexDirection:"column",marginTop:1,children:y.summary.map((G,K)=>(0,L.jsx)(NA,{children:G},K))}),(0,L.jsxs)(CA,{flexDirection:"column",marginTop:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Changed files"}),y.files===null?(0,L.jsx)(eA,{children:"The changed files couldn't be read. Press w to see them in the browser."}):y.files.names.length===0?(0,L.jsx)(eA,{children:"None."}):(0,L.jsxs)(L.Fragment,{children:[y.files.names.map(G=>(0,L.jsx)(NA,{children:` ${G}`},G)),y.files.more>0?(0,L.jsx)(eA,{children:` and ${y.files.more} more`}):null]})]}),y.requirements.length===0?null:(0,L.jsxs)(CA,{flexDirection:"column",marginTop:1,children:[(0,L.jsx)(eA,{bold:!0,children:"Requirements"}),y.requirements.map((G,K)=>(0,L.jsx)(NA,{children:` ${G.word}: ${G.statement}`},K))]}),y.checks.length===0?null:(0,L.jsx)(CA,{flexDirection:"column",marginTop:1,children:y.checks.map((G,K)=>(0,L.jsx)(NA,{...K===0?{bold:!0}:{},children:G},K))}),(0,L.jsx)(CA,{flexDirection:"column",marginTop:1,children:y.ready?y.owed==="person-check"?(0,L.jsx)(eA,{bold:!0,children:"Did you check it yourself? (y/n)"}):y.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)(NA,{children:N.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."}),y.blockers.map((G,K)=>(0,L.jsx)(NA,{children:G},K))]})})]})}case"retry":return(0,L.jsxs)(CA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(NA,{bold:!0,children:`Retry build #${N.retry.runId}? ${N.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)(NA,{bold:!0,children:`Approve this plan? ${N.task.title}`}),N.task.plan.lines.map((y,G)=>(0,L.jsx)(NA,{children:y},G))]});case"task":{let y=Ef(N.task,dA!==null),G=y.decisions[0];return(0,L.jsxs)(CA,{flexDirection:"column",borderStyle:"single",paddingX:1,children:[(0,L.jsx)(NA,{bold:!0,children:y.title}),(0,L.jsx)(NA,{children:`${y.status}${y.detail===""?"":` · ${y.detail}`}`}),y.plan===null?null:(0,L.jsx)(eA,{children:"A plan waits for your approval (a)."}),(y.ready?.length??0)===0?null:(0,L.jsx)(CA,{flexDirection:"column",marginTop:1,children:y.ready.map((K,P)=>(0,L.jsx)(NA,{...P===0?{bold:!0}:{},children:K},P))}),G===void 0?null:(0,L.jsxs)(CA,{flexDirection:"column",marginTop:1,children:[(0,L.jsx)(NA,{bold:!0,children:G.question}),G.options.map((K,P)=>(0,L.jsx)(NA,{children:`${P+1} ${K.label}`},K.id))]}),W.length===0?null:(0,L.jsx)(CA,{flexDirection:"column",marginTop:1,children:W.slice(-12).map((K,P)=>(0,L.jsx)(NA,{dimColor:!0,children:K},P))})]})}default:return E===null?(0,L.jsx)(eA,{dimColor:!0,children:"Loading…"}):HA.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((y,G)=>(0,L.jsx)(NA,{children:y},G))]}):(0,L.jsxs)(CA,{children:[(0,L.jsx)(CA,{flexDirection:"column",width:"45%",borderStyle:"single",paddingX:1,children:HA.map((y,G)=>(0,L.jsxs)(jA.Fragment,{children:[G===0||HA[G-1].group!==y.group?(0,L.jsx)(eA,{bold:!0,children:$y(y)}):null,(0,L.jsxs)(eA,{inverse:y===TA,wrap:"truncate-end",children:[y===TA?"> ":" ",(0,L.jsx)(NA,{children:y.title})," ",(0,L.jsx)(NA,{...y.needsYou?{bold:!0}:{dimColor:!0},children:y.status})]})]},y.id))}),(0,L.jsx)(CA,{flexDirection:"column",flexGrow:1,borderStyle:"single",paddingX:1,children:TA===void 0?(0,L.jsx)(eA,{dimColor:!0,children:"Nothing selected"}):(0,L.jsxs)(L.Fragment,{children:[(0,L.jsx)(NA,{bold:!0,wrap:"truncate-end",children:TA.title}),(0,L.jsx)(NA,{children:`${TA.status}${TA.detail===""?"":` · ${TA.detail}`}`}),W.length===0?(0,L.jsx)(eA,{dimColor:!0,children:TA.liveRunId===null?"No agent is working on it now.":"Waiting for output…"}):W.slice(-12).map((y,G)=>(0,L.jsx)(NA,{dimColor:!0,wrap:"truncate-end",children:y},G))]})})]})}}}function cf(){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 Qf=oA(qa(),1);async function t2(e=cf(),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,Qf.jsx)(Bf,{source:e,session:u,onExit:g=>{a=g}}),{exitOnCtrlC:!1}).waitUntilExit(),a}var If=process.argv[1];If!==void 0&&import.meta.url===A2(If).href&&t2().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
71
71
  `),process.exitCode=1});export{t2 as startTui};
72
72
  /*! Bundled license information:
73
73