toolroll 0.9.115 → 0.9.117

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 (145) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +43 -26
  3. package/dist/acp-agents.js +14 -1
  4. package/dist/acp-client.js +19 -1
  5. package/dist/agent-change-check.js +60 -0
  6. package/dist/agent-change-schema.js +19 -0
  7. package/dist/agent-detect.js +11 -1
  8. package/dist/agent-fence.js +39 -10
  9. package/dist/agent-network-request.js +108 -0
  10. package/dist/agent-requests.js +105 -0
  11. package/dist/approval-summary.js +3 -3
  12. package/dist/backup.js +17 -1
  13. package/dist/batch-checks.js +81 -18
  14. package/dist/browser/terminal.js +41 -41
  15. package/dist/browser/workspace.css +2 -2
  16. package/dist/browser/workspace.js +36 -36
  17. package/dist/builder.js +3 -1
  18. package/dist/candidate-materialize.js +119 -0
  19. package/dist/central-enrollment-contract.js +156 -0
  20. package/dist/central-recovery-stage.js +329 -0
  21. package/dist/chat-actions.js +101 -2
  22. package/dist/chat-channel.js +40 -0
  23. package/dist/check-only-standing.js +13 -0
  24. package/dist/check-only.js +25 -13
  25. package/dist/check-recovery-hold.js +199 -0
  26. package/dist/check-recovery-index-schema.js +3 -0
  27. package/dist/check-screenshots.js +83 -0
  28. package/dist/cli.js +125 -6
  29. package/dist/codex-limits.js +4 -0
  30. package/dist/connect-cli.js +257 -11
  31. package/dist/contracts/chat-actions.js +4 -0
  32. package/dist/contracts/console-api.js +15 -4
  33. package/dist/contracts/engine-api.js +344 -2
  34. package/dist/contracts/lead-tools.js +56 -2
  35. package/dist/contracts/provider.js +1 -1
  36. package/dist/contracts/route.js +1 -1
  37. package/dist/contracts/terminal-connection.js +50 -0
  38. package/dist/converse.js +80 -4
  39. package/dist/device-pair.js +280 -0
  40. package/dist/direct-chat-artifacts.js +347 -0
  41. package/dist/direct-chat-catalog.js +311 -0
  42. package/dist/direct-chat-fence.js +96 -0
  43. package/dist/direct-chat-git.js +343 -0
  44. package/dist/direct-chat-laptop.js +19 -0
  45. package/dist/direct-chat-schema.js +181 -0
  46. package/dist/direct-chat-ship.js +861 -0
  47. package/dist/direct-chat-workspace.js +389 -0
  48. package/dist/direct-chat.js +2107 -0
  49. package/dist/doctor.js +1 -1
  50. package/dist/easy-start.js +18 -0
  51. package/dist/egress.js +25 -4
  52. package/dist/engine-chat.js +454 -0
  53. package/dist/engine-reads.js +141 -13
  54. package/dist/exec.js +4 -3
  55. package/dist/flexible-agents.js +8 -16
  56. package/dist/flexible-authority-end.js +2 -0
  57. package/dist/flexible-interactive-schema.js +133 -0
  58. package/dist/flexible-interactive.js +94 -0
  59. package/dist/flexible-session.js +117 -49
  60. package/dist/flexible-ship.js +87 -7
  61. package/dist/flexible-sign-in.js +10 -0
  62. package/dist/flexible-start.js +21 -3
  63. package/dist/flexible-thread.js +2 -3
  64. package/dist/flexible-turns.js +26 -5
  65. package/dist/flexible.js +13 -0
  66. package/dist/flow-triggers.js +13 -4
  67. package/dist/flows-ui.js +54 -20
  68. package/dist/handoff-cli.js +630 -0
  69. package/dist/invoke.js +55 -13
  70. package/dist/lead-contract.js +5 -4
  71. package/dist/lead-doors.js +80 -1
  72. package/dist/lead-progress.js +9 -0
  73. package/dist/lead-tools.js +682 -10
  74. package/dist/lead.js +37 -9
  75. package/dist/live-bus.js +11 -0
  76. package/dist/live-terminal.js +132 -12
  77. package/dist/local-handoff.js +363 -0
  78. package/dist/local-owner-acts.js +264 -2
  79. package/dist/local-owner.js +16 -1
  80. package/dist/multiplayer-handoff.js +528 -0
  81. package/dist/multiplayer-presence.js +471 -0
  82. package/dist/names.js +17 -4
  83. package/dist/needs-you.js +10 -0
  84. package/dist/operate.js +280 -19
  85. package/dist/policy.js +2 -2
  86. package/dist/project-delete-ui.js +18 -11
  87. package/dist/project-delete.js +65 -4
  88. package/dist/project-tools.js +1 -1
  89. package/dist/prompt.js +1 -1
  90. package/dist/provider-connection.js +2 -0
  91. package/dist/provider-home.js +251 -8
  92. package/dist/provider.js +3 -2
  93. package/dist/publish.js +119 -64
  94. package/dist/pull-request-flow.js +35 -14
  95. package/dist/read-executor-worker.js +1 -1
  96. package/dist/read-executor.js +95 -1
  97. package/dist/restore-retirement.js +152 -0
  98. package/dist/result-follow-ups.js +116 -37
  99. package/dist/route-change.js +44 -4
  100. package/dist/scope.js +62 -5
  101. package/dist/serve.js +49 -5
  102. package/dist/server/chat.js +94 -13
  103. package/dist/server/console.css +9 -9
  104. package/dist/server/direct-chat.js +583 -0
  105. package/dist/server/engine-api.js +219 -21
  106. package/dist/server/flows.js +47 -13
  107. package/dist/server/found-repos.js +25 -0
  108. package/dist/server/guards.js +20 -6
  109. package/dist/server/live.js +81 -23
  110. package/dist/server/pages.js +67 -13
  111. package/dist/server/people-tokens.js +47 -6
  112. package/dist/server/remote.js +29 -0
  113. package/dist/server/render-results.js +6 -2
  114. package/dist/server/render-settings.js +4 -2
  115. package/dist/server/render-tasks.js +18 -17
  116. package/dist/server/route-table.js +69 -2
  117. package/dist/server/settings.js +22 -7
  118. package/dist/server/task-views.js +15 -3
  119. package/dist/server/tasks.js +39 -2
  120. package/dist/server/terminals.js +185 -11
  121. package/dist/settings-proofs.js +1 -1
  122. package/dist/spend-report.js +2 -2
  123. package/dist/spend.js +3 -3
  124. package/dist/store.js +600 -59
  125. package/dist/subagent-admin.js +23 -10
  126. package/dist/subagent-backup-schema.js +36 -0
  127. package/dist/subagent-backup.js +92 -0
  128. package/dist/subagent-week.js +2 -2
  129. package/dist/subagent-work.js +70 -47
  130. package/dist/subagents-ui.js +6 -2
  131. package/dist/subagents.js +5 -2
  132. package/dist/subscription-chat.js +36 -5
  133. package/dist/subscription-usage.js +233 -0
  134. package/dist/task-live.js +2 -1
  135. package/dist/teardown-git.js +34 -4
  136. package/dist/terminal-connection.js +159 -0
  137. package/dist/terminal-safety.js +114 -0
  138. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  139. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  140. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  141. package/dist/tui/linux-x64/toolroll-tui +0 -0
  142. package/dist/tui-contract.js +1 -1
  143. package/dist/tui-launch.js +32 -1
  144. package/dist/workspace-identity-schema.js +21 -0
  145. package/package.json +4 -2
@@ -0,0 +1,233 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { resolveExecutable } from "./attest.js";
7
+ import { codingEnvironment } from "./coding-provider.js";
8
+ import { readCodexLimits } from "./codex-limits.js";
9
+ import { claudeLimitsOf } from "./provider-limits.js";
10
+ import { billingOf } from "./spend.js";
11
+ const CLAUDE_STALE_MS = 30 * 60_000;
12
+ const GEMINI_STALE_MS = 15 * 60_000;
13
+ export function subscriptionStatusPath(databaseFile) {
14
+ return join(dirname(databaseFile), ".toolroll-run", "subscription-status.json");
15
+ }
16
+ export function readStoredGeminiStatus(databaseFile) {
17
+ const path = subscriptionStatusPath(databaseFile);
18
+ if (!existsSync(path))
19
+ return null;
20
+ try {
21
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
22
+ if (!parsed || typeof parsed !== "object" || !parsed.gemini)
23
+ return null;
24
+ return parsed.gemini;
25
+ }
26
+ catch {
27
+ return null;
28
+ }
29
+ }
30
+ export function writeStoredGeminiStatus(databaseFile, gemini) {
31
+ const path = subscriptionStatusPath(databaseFile);
32
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
33
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
34
+ writeFileSync(tmp, JSON.stringify({ version: 1, gemini }, null, 2) + "\n", { mode: 0o600 });
35
+ chmodSync(tmp, 0o600);
36
+ renameSync(tmp, path);
37
+ }
38
+ export function readClaudeLimits(options = {}) {
39
+ return new Promise(resolve => {
40
+ const bin = options.command ?? resolveExecutable("claude");
41
+ if (!bin) {
42
+ resolve(null);
43
+ return;
44
+ }
45
+ const env = codingEnvironment();
46
+ for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX"]) {
47
+ delete env[key];
48
+ }
49
+ let settled = false;
50
+ let buffered = "";
51
+ let found = null;
52
+ let child;
53
+ try {
54
+ child = spawn(bin, ["-p", ".", "--model", "haiku", "--max-turns", "1", "--output-format", "stream-json", "--verbose", "--setting-sources", "", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}'], { cwd: tmpdir(), env, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] });
55
+ }
56
+ catch {
57
+ resolve(null);
58
+ return;
59
+ }
60
+ const finish = (reading) => {
61
+ if (settled)
62
+ return;
63
+ settled = true;
64
+ clearTimeout(timer);
65
+ try {
66
+ child.kill("SIGTERM");
67
+ }
68
+ catch { }
69
+ resolve(reading);
70
+ };
71
+ const timer = setTimeout(() => finish(found), options.timeoutMs ?? 15_000);
72
+ child.once("error", () => finish(null));
73
+ child.once("exit", () => finish(found));
74
+ child.stdout?.setEncoding("utf8");
75
+ child.stdout?.on("data", (chunk) => {
76
+ buffered += chunk;
77
+ let nl;
78
+ while ((nl = buffered.indexOf("\n")) !== -1) {
79
+ const line = buffered.slice(0, nl).trim();
80
+ buffered = buffered.slice(nl + 1);
81
+ if (!line)
82
+ continue;
83
+ try {
84
+ const reading = claudeLimitsOf(JSON.parse(line));
85
+ if (reading !== null) {
86
+ found = reading;
87
+ finish(reading);
88
+ return;
89
+ }
90
+ }
91
+ catch { }
92
+ }
93
+ });
94
+ });
95
+ }
96
+ export function readGeminiSubscription(options = {}) {
97
+ const nowIso = (options.now ?? new Date()).toISOString();
98
+ return new Promise(resolve => {
99
+ const bin = options.command ?? resolveExecutable("agy");
100
+ if (!bin) {
101
+ resolve({
102
+ connected: false,
103
+ provider: "antigravity",
104
+ topModel: null,
105
+ modelCount: 0,
106
+ observedAt: nowIso,
107
+ note: "Install Antigravity CLI (agy)",
108
+ });
109
+ return;
110
+ }
111
+ const env = codingEnvironment();
112
+ let child;
113
+ try {
114
+ child = spawn(bin, ["models"], { cwd: tmpdir(), env, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
115
+ }
116
+ catch {
117
+ resolve({ connected: false, provider: "antigravity", topModel: null, modelCount: 0, observedAt: nowIso, note: "Could not start agy" });
118
+ return;
119
+ }
120
+ let settled = false;
121
+ let out = "";
122
+ let err = "";
123
+ const finish = (status) => {
124
+ if (settled)
125
+ return;
126
+ settled = true;
127
+ clearTimeout(timer);
128
+ try {
129
+ child.kill("SIGTERM");
130
+ }
131
+ catch { }
132
+ resolve(status);
133
+ };
134
+ const timer = setTimeout(() => finish({
135
+ connected: false,
136
+ provider: "antigravity",
137
+ topModel: null,
138
+ modelCount: 0,
139
+ observedAt: nowIso,
140
+ note: "Timed out checking Antigravity",
141
+ }), options.timeoutMs ?? 12_000);
142
+ child.stdout?.setEncoding("utf8");
143
+ child.stderr?.setEncoding("utf8");
144
+ child.stdout?.on("data", chunk => { out += chunk; });
145
+ child.stderr?.on("data", chunk => { err += chunk; });
146
+ child.once("error", () => finish({
147
+ connected: false,
148
+ provider: "antigravity",
149
+ topModel: null,
150
+ modelCount: 0,
151
+ observedAt: nowIso,
152
+ note: "Could not run agy",
153
+ }));
154
+ child.once("close", code => {
155
+ const cleaned = out.replace(/\r/g, "\n").replace(/\x1b\[[0-9;]*[A-Za-z]/g, "");
156
+ const modelLines = cleaned.split("\n").map(l => l.trim()).filter(l => /^gemini-/i.test(l));
157
+ const hasNeon = modelLines.some(l => /gemini-4-neon/i.test(l));
158
+ const topModel = hasNeon ? "Gemini 4 Neon" : (modelLines[0]?.split(/\s{2,}/)[1] ?? modelLines[0]?.split(/\s+/)[0] ?? null);
159
+ if (code === 0 && modelLines.length > 0) {
160
+ finish({
161
+ connected: true,
162
+ provider: "antigravity",
163
+ topModel,
164
+ modelCount: modelLines.length,
165
+ observedAt: nowIso,
166
+ note: null,
167
+ });
168
+ }
169
+ else {
170
+ const msg = err.trim().split("\n").pop()?.slice(0, 120) || "Sign in with `agy acp --login`";
171
+ finish({
172
+ connected: false,
173
+ provider: "antigravity",
174
+ topModel: null,
175
+ modelCount: 0,
176
+ observedAt: nowIso,
177
+ note: msg,
178
+ });
179
+ }
180
+ });
181
+ });
182
+ }
183
+ function claudeNeedsRefresh(store, now) {
184
+ if (billingOf("claude") !== "subscription")
185
+ return false;
186
+ const recent = new Date(now.getTime() - 6 * 3_600_000).toISOString();
187
+ if (store.handle.prepare("SELECT 1 AS live FROM run WHERE provider = 'claude' AND outcome IS NULL AND started_at > ? LIMIT 1").get(recent) !== undefined) {
188
+ return false;
189
+ }
190
+ const rows = store.providerLimits().filter(one => one.provider === "claude");
191
+ if (rows.length === 0)
192
+ return true;
193
+ return rows.some(one => {
194
+ const expired = one.resetsAt !== null && Date.parse(one.resetsAt) <= now.getTime();
195
+ const stale = now.getTime() - Date.parse(one.observedAt) > CLAUDE_STALE_MS;
196
+ return expired || stale;
197
+ });
198
+ }
199
+ function geminiNeedsRefresh(databaseFile, now) {
200
+ if (databaseFile === null)
201
+ return false;
202
+ const stored = readStoredGeminiStatus(databaseFile);
203
+ if (stored === null)
204
+ return true;
205
+ return now.getTime() - Date.parse(stored.observedAt) > GEMINI_STALE_MS;
206
+ }
207
+ export async function refreshSubscriptions(store, databaseFile, options = {}) {
208
+ const now = options.now ?? new Date();
209
+ const shouldCodex = options.skipCodex !== true && billingOf("codex") === "subscription";
210
+ const shouldClaude = options.forceClaude === true || claudeNeedsRefresh(store, now);
211
+ const shouldGemini = options.forceGemini === true || geminiNeedsRefresh(databaseFile, now);
212
+ const [codex, claude, gemini] = await Promise.all([
213
+ shouldCodex ? readCodexLimits() : Promise.resolve(null),
214
+ shouldClaude ? readClaudeLimits() : Promise.resolve(null),
215
+ shouldGemini
216
+ ? readGeminiSubscription({ now })
217
+ : Promise.resolve((databaseFile !== null ? readStoredGeminiStatus(databaseFile) : null) ?? {
218
+ connected: false,
219
+ provider: "antigravity",
220
+ topModel: null,
221
+ modelCount: 0,
222
+ observedAt: now.toISOString(),
223
+ note: null,
224
+ }),
225
+ ]);
226
+ if (codex !== null)
227
+ store.recordProviderLimits(codex, now);
228
+ if (claude !== null)
229
+ store.recordProviderLimits(claude, now);
230
+ if (databaseFile !== null && shouldGemini)
231
+ writeStoredGeminiStatus(databaseFile, gemini);
232
+ return { claude, codex, gemini, refreshedAt: now.toISOString() };
233
+ }
package/dist/task-live.js CHANGED
@@ -15,7 +15,8 @@ export function taskFingerprint(store, root, now, livenessMs = DEFAULT_LIVENESS_
15
15
  (SELECT count(*) || ':' || coalesce(max(d.id), 0) || ':' || coalesce(sum(d.state = 'answered'), 0) FROM decision d JOIN run r ON r.id = d.run WHERE r.task_ref IN (SELECT ref FROM family)) AS decisions,
16
16
  (SELECT coalesce(max(c.id), 0) FROM run_checkpoint c WHERE c.task_ref IN (SELECT ref FROM family)) AS progress,
17
17
  (SELECT coalesce(max(a.at), '') FROM run_activity a JOIN run r ON r.id = a.run WHERE r.task_ref IN (SELECT ref FROM family) AND r.outcome IS NULL) AS activity,
18
- (SELECT coalesce(group_concat(w.heartbeat_at > ?2), '') FROM run r JOIN runner w ON w.name = r.runner WHERE r.task_ref IN (SELECT ref FROM family) AND r.outcome IS NULL) AS workers
18
+ (SELECT coalesce(group_concat(w.heartbeat_at > ?2), '') FROM run r JOIN runner w ON w.name = r.runner WHERE r.task_ref IN (SELECT ref FROM family) AND r.outcome IS NULL) AS workers,
19
+ (SELECT coalesce(max(l.id), 0) FROM action_ledger l WHERE l.task_id IN (SELECT ext FROM family)) AS ledger
19
20
  WHERE EXISTS (SELECT 1 FROM family)`).get(root, new Date(now.getTime() - livenessMs).toISOString(), BUILT_IN);
20
21
  return row === undefined ? null : createHash("sha256").update(Object.values(row).map(String).join("|")).digest("hex").slice(0, 16);
21
22
  }
@@ -1008,6 +1008,10 @@ export function checkoutGitSync(cwd, args, options = {}) {
1008
1008
  }
1009
1009
  export function viewedGitSync(cwd, args, options = {}) {
1010
1010
  const gitFile = options.git ?? "git";
1011
+ const write = options.write === true;
1012
+ const writeArgv = write && options.buffer !== true ? syncWriteArgv(args) : null;
1013
+ if (write && writeArgv === null)
1014
+ throw new Error(`git ${args[0] ?? ""} can't run as a synchronous write in that form`);
1011
1015
  const deadline = options.deadline;
1012
1016
  const limit = deadline === undefined ? undefined : () => deadline - Date.now();
1013
1017
  const expire = () => { if (limit !== undefined && limit() <= 0)
@@ -1021,7 +1025,7 @@ export function viewedGitSync(cwd, args, options = {}) {
1021
1025
  if (lfsExtensionIn(cwd, gitFile, limit))
1022
1026
  throw new Error("the checkout's .lfsconfig sets a git-lfs key that can run a command");
1023
1027
  expire();
1024
- const view = gitView(cwd, "read", options.binding, gitFile, limit);
1028
+ const view = gitView(cwd, write ? "write" : "read", options.binding, gitFile, limit, write ? "updating a repository" : undefined);
1025
1029
  try {
1026
1030
  const env = { PATH: process.env["PATH"] ?? "", HOME: process.env["HOME"] ?? "", LANG: "C", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_TERMINAL_PROMPT: "0", ...view.env };
1027
1031
  const timeoutNow = () => { expire(); return limit === undefined ? options.timeoutMs ?? 60_000 : Math.max(1, Math.min(options.timeoutMs ?? 60_000, limit())); };
@@ -1035,14 +1039,15 @@ export function viewedGitSync(cwd, args, options = {}) {
1035
1039
  throw new Error(`the checkout's git config sets ${key}, which can run a command`);
1036
1040
  if (!lazyFetchSupported(gitFile) && lazyFetchSetting(own.stdout) !== null)
1037
1041
  throw new Error(PARTIAL_CLONE_REFUSAL);
1038
- const safeArgs = withoutUnsupportedFlags(args, gitFile);
1042
+ const safeArgs = writeArgv ?? withoutUnsupportedFlags(args, gitFile);
1039
1043
  const command = safeArgs.findIndex(arg => arg === "status" || arg === "diff");
1040
1044
  if (command >= 0 && !safeArgs.includes("--ignore-submodules=all"))
1041
1045
  safeArgs.splice(command + 1, 0, "--ignore-submodules=all");
1042
1046
  if (command >= 0 && safeArgs[command] === "diff")
1043
1047
  safeArgs.splice(command + 1, 0, "--no-ext-diff", "--no-textconv");
1044
1048
  const carried = withoutFilters(carriedSettings(own.stdout));
1045
- const argv = [...TEARDOWN_FLAGS, ...readFlags(gitFile), "-c", "diff.ignoreSubmodules=all", ...carried, ...safeArgs];
1049
+ const flags = write ? [...WRITE_VIEW_FLAGS, ...(lazyFetchSupported(gitFile) ? ["--no-lazy-fetch"] : [])] : readFlags(gitFile);
1050
+ const argv = [...TEARDOWN_FLAGS, ...flags, "-c", "diff.ignoreSubmodules=all", ...carried, ...safeArgs];
1046
1051
  if (options.buffer === true) {
1047
1052
  const ran = spawnSync(gitFile, argv, { ...fixed, timeout: timeoutNow(), encoding: "buffer", ...(options.input === undefined ? {} : { input: options.input, stdio: ["pipe", "pipe", "pipe"] }) });
1048
1053
  const why = view.settle();
@@ -1056,12 +1061,37 @@ export function viewedGitSync(cwd, args, options = {}) {
1056
1061
  if (why !== null)
1057
1062
  throw new Error(why);
1058
1063
  expire();
1059
- return { status: ran.error === undefined ? ran.status : null, stdout: view.restore(ran.stdout ?? "", args) };
1064
+ return { status: ran.error === undefined ? ran.status : null, stdout: view.restore(ran.stdout ?? "", args), stderr: view.restore(ran.stderr ?? "", args) };
1060
1065
  }
1061
1066
  finally {
1062
1067
  view.dispose();
1063
1068
  }
1064
1069
  }
1070
+ function plainBranch(name) {
1071
+ if (name === "" || name === "HEAD" || name.startsWith("-") || name.length > 200 || !/^[A-Za-z0-9._/-]+$/.test(name))
1072
+ return false;
1073
+ return name.split("/").every(part => part !== "" && !part.startsWith(".") && !part.endsWith(".lock") && !part.endsWith(".")) && !name.includes("..");
1074
+ }
1075
+ export function syncWriteArgv(args) {
1076
+ if (args.length === 3 && args[0] === "branch" && args[1] === "-D" && plainBranch(args[2]))
1077
+ return ["branch", "-D", args[2]];
1078
+ if (args.length !== 5 || args[0] !== "fetch" || args[1] !== "--no-tags" || args[2] !== "--no-write-fetch-head")
1079
+ return null;
1080
+ const path = args[3], refspec = args[4];
1081
+ if (!path.startsWith("/") || path.includes("::") || /[\0\n\r]/.test(path))
1082
+ return null;
1083
+ try {
1084
+ if (realpathSync(path) !== path || !lstatSync(path).isDirectory())
1085
+ return null;
1086
+ }
1087
+ catch {
1088
+ return null;
1089
+ }
1090
+ const spec = /^([0-9a-f]{40}|[0-9a-f]{64}):refs\/heads\/(.+)$/.exec(refspec);
1091
+ if (spec === null || !plainBranch(spec[2]))
1092
+ return null;
1093
+ return ["-c", "protocol.file.allow=always", "-c", "transfer.fsckObjects=true", "fetch", "--no-tags", "--no-write-fetch-head", "--", path, refspec];
1094
+ }
1065
1095
  export function hardenedGit(inner = run, mode = "build", binding = {}) {
1066
1096
  const hardened = checkoutGit(inner, mode, binding);
1067
1097
  return (file, args, options) => {
@@ -0,0 +1,159 @@
1
+ import { reproveRemote } from "./operate-remote.js";
2
+ import { adapterPolicy } from "./server/route-policy.js";
3
+ import { engineContractDigest, ENGINE_API_VERSION } from "./contracts/engine-api.js";
4
+ import { DISABLED_TERMINAL_CAPABILITIES, REMOTE_TUI_COMMANDS, TERMINAL_CONNECTION_PROTOCOL, terminalConnectionSchema, } from "./contracts/terminal-connection.js";
5
+ import { RECOVERY_GENERATION_PATTERN, WORKSPACE_ID_PATTERN } from "./workspace-identity-schema.js";
6
+ export const REMOTE_TUI_READ_ROUTES = new Set([
7
+ "work.rows",
8
+ "task.steps",
9
+ "task.diff",
10
+ "agents.live.run",
11
+ "engine.chat",
12
+ ]);
13
+ export function isRemoteTerminalRequest(request) {
14
+ return request.headers["x-toolroll-client"] === "terminal-remote";
15
+ }
16
+ function headerNames(request) {
17
+ return request.rawHeaders.filter((_value, index) => index % 2 === 0).map(name => name.toLowerCase());
18
+ }
19
+ function hasForbiddenBrowserHeaders(names) {
20
+ return names.includes("cookie") || names.includes("origin") || names.includes("referer")
21
+ || names.some(name => name.startsWith("sec-fetch-"));
22
+ }
23
+ export function admitRemoteTerminalRequest(request, store, principal, clock) {
24
+ const names = headerNames(request);
25
+ if (hasForbiddenBrowserHeaders(names)
26
+ || names.filter(name => name === "authorization").length !== 1
27
+ || names.filter(name => name === "x-toolroll-client").length !== 1
28
+ || request.headers["x-toolroll-client"] !== "terminal-remote"
29
+ || names.filter(name => name === "x-toolroll-workspace").length !== 1
30
+ || names.filter(name => name === "x-toolroll-recovery").length !== 1) {
31
+ return { ok: false, status: 400, error: "request" };
32
+ }
33
+ const workspace = request.headers["x-toolroll-workspace"];
34
+ const recovery = request.headers["x-toolroll-recovery"];
35
+ if (typeof workspace !== "string" || !WORKSPACE_ID_PATTERN.test(workspace)
36
+ || typeof recovery !== "string" || !RECOVERY_GENERATION_PATTERN.test(recovery)) {
37
+ return { ok: false, status: 400, error: "request" };
38
+ }
39
+ if (principal === undefined || !/^Bearer so_[a-f0-9]{12}_[A-Za-z0-9_-]{43}$/.test(request.headers.authorization ?? "")) {
40
+ return { ok: false, status: 401, error: "unauthenticated" };
41
+ }
42
+ const live = reproveRemote(store, principal, clock());
43
+ if (!live.ok)
44
+ return { ok: false, status: 401, error: "unauthenticated" };
45
+ const credential = store.apiTokenSecret(principal.tokenId)?.row;
46
+ if (credential?.purpose !== "api")
47
+ return { ok: false, status: 403, error: "credential-purpose" };
48
+ if (!adapterPolicy({ caller: "bearer", capability: live.scope, token: true }, "read").ok) {
49
+ return { ok: false, status: 403, error: "unauthenticated" };
50
+ }
51
+ let identity;
52
+ try {
53
+ identity = store.workspaceIdentity();
54
+ }
55
+ catch {
56
+ return { ok: false, status: 503, error: "workspace-unavailable" };
57
+ }
58
+ if (identity.id !== workspace)
59
+ return { ok: false, status: 409, error: "workspace-mismatch" };
60
+ if (identity.recoveryGeneration !== recovery)
61
+ return { ok: false, status: 409, error: "recovery-changed" };
62
+ return { ok: true, scope: live.scope, identity };
63
+ }
64
+ export function sendTerminalConnectionRefusal(request, response, status, error) {
65
+ request.resume();
66
+ response.writeHead(status, {
67
+ "content-type": "application/json; charset=utf-8",
68
+ "cache-control": "no-store",
69
+ "pragma": "no-cache",
70
+ "x-content-type-options": "nosniff",
71
+ });
72
+ response.end(JSON.stringify({ protocol: TERMINAL_CONNECTION_PROTOCOL, error }));
73
+ }
74
+ export function handleTerminalConnection(request, response, options) {
75
+ const send = (status, value) => {
76
+ response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", "pragma": "no-cache", "x-content-type-options": "nosniff" });
77
+ response.end(JSON.stringify(value));
78
+ };
79
+ const refuse = (status, error) => {
80
+ request.resume();
81
+ send(status, { protocol: TERMINAL_CONNECTION_PROTOCOL, error });
82
+ };
83
+ const names = headerNames(request);
84
+ if (request.method !== "GET" || request.url !== "/engine/connection" || hasForbiddenBrowserHeaders(names)
85
+ || names.filter(name => name === "authorization").length !== 1
86
+ || names.filter(name => name === "x-toolroll-client").length !== 1 || request.headers["x-toolroll-client"] !== "terminal-remote"
87
+ || request.headers["transfer-encoding"] !== undefined || (request.headers["content-length"] !== undefined && request.headers["content-length"] !== "0"))
88
+ return refuse(400, "request");
89
+ if (!/^Bearer so_[a-f0-9]{12}_[A-Za-z0-9_-]{43}$/.test(request.headers.authorization ?? ""))
90
+ return refuse(401, "unauthenticated");
91
+ let principal;
92
+ try {
93
+ principal = options.authenticate(request);
94
+ }
95
+ catch {
96
+ return refuse(503, "contract-unavailable");
97
+ }
98
+ if (principal === null)
99
+ return refuse(401, "unauthenticated");
100
+ const store = options.store;
101
+ try {
102
+ const before = reproveRemote(store, principal, options.clock());
103
+ if (!before.ok)
104
+ return refuse(401, "unauthenticated");
105
+ const credential = store.apiTokenSecret(principal.tokenId)?.row;
106
+ if (credential?.purpose !== "api")
107
+ return refuse(403, "credential-purpose");
108
+ if (!adapterPolicy({ caller: "bearer", capability: before.scope, token: true }, "read").ok)
109
+ return refuse(403, "unauthenticated");
110
+ const budget = options.admit?.(principal);
111
+ if (budget !== undefined && !budget.ok) {
112
+ if (budget.status !== 503)
113
+ response.setHeader("retry-after", String(budget.retryAfter));
114
+ return refuse(budget.status === 503 ? 503 : 429, "request");
115
+ }
116
+ let identity;
117
+ try {
118
+ identity = store.workspaceIdentity();
119
+ }
120
+ catch {
121
+ return refuse(503, "workspace-unavailable");
122
+ }
123
+ const account = store.accountOf(principal.account);
124
+ if (account === null)
125
+ return refuse(401, "unauthenticated");
126
+ const capabilities = {
127
+ ...DISABLED_TERMINAL_CAPABILITIES,
128
+ workRows: true,
129
+ stepCards: true,
130
+ resultDiff: true,
131
+ runLiveWindow: true,
132
+ leadChat: account.role === "approver",
133
+ liveStream: true,
134
+ localCode: true,
135
+ commands: before.scope === "act" && account.role === "approver" ? [...REMOTE_TUI_COMMANDS] : [],
136
+ };
137
+ const candidate = {
138
+ protocol: TERMINAL_CONNECTION_PROTOCOL,
139
+ workspace: { id: identity.id, recoveryGeneration: identity.recoveryGeneration, label: "Toolroll" },
140
+ principal: { account: principal.account, role: account.role, access: before.scope, expiresAt: new Date(credential.expiresAt).toISOString() },
141
+ engine: { version: ENGINE_API_VERSION, contract: engineContractDigest() },
142
+ capabilities,
143
+ };
144
+ const body = terminalConnectionSchema.safeParse(candidate);
145
+ if (!body.success)
146
+ return refuse(503, "contract-unavailable");
147
+ const currentIdentity = store.workspaceIdentity();
148
+ if (currentIdentity.id !== identity.id || currentIdentity.recoveryGeneration !== identity.recoveryGeneration)
149
+ return refuse(503, "workspace-unavailable");
150
+ const after = reproveRemote(store, principal, options.clock()), currentCredential = store.apiTokenSecret(principal.tokenId)?.row;
151
+ if (!after.ok || after.scope !== before.scope || store.accountOf(principal.account)?.role !== account.role
152
+ || currentCredential?.purpose !== "api" || currentCredential.expiresAt !== credential.expiresAt)
153
+ return refuse(401, "unauthenticated");
154
+ send(200, body.data);
155
+ }
156
+ catch {
157
+ return refuse(503, "contract-unavailable");
158
+ }
159
+ }
@@ -0,0 +1,114 @@
1
+ import { StringDecoder } from "node:string_decoder";
2
+ export class TerminalSafetyFilter {
3
+ decoder = new StringDecoder("utf8");
4
+ state = "text";
5
+ sequence = "";
6
+ osc = false;
7
+ ended = false;
8
+ write(bytes) {
9
+ if (this.ended)
10
+ throw new Error("Terminal safety filter already finished");
11
+ return this.parse(this.decoder.write(Buffer.from(bytes)));
12
+ }
13
+ finish() {
14
+ if (this.ended)
15
+ return "";
16
+ const out = this.parse(this.decoder.end());
17
+ this.ended = true;
18
+ this.sequence = "";
19
+ this.state = "text";
20
+ return out;
21
+ }
22
+ parse(text) {
23
+ const out = [];
24
+ for (const char of text) {
25
+ const code = char.codePointAt(0);
26
+ if (this.state === "string" || this.state === "string-escape") {
27
+ if (code === 0x9c || (this.osc && code === 7) || (this.state === "string-escape" && char === "\\")) {
28
+ this.state = "text";
29
+ }
30
+ else
31
+ this.state = char === "\x1b" ? "string-escape" : "string";
32
+ continue;
33
+ }
34
+ if (char === "\x1b") {
35
+ this.state = "escape";
36
+ this.sequence = "";
37
+ continue;
38
+ }
39
+ if ([0x90, 0x98, 0x9d, 0x9e, 0x9f].includes(code)) {
40
+ this.osc = code === 0x9d;
41
+ this.state = "string";
42
+ this.sequence = "";
43
+ continue;
44
+ }
45
+ if (code === 0x9b) {
46
+ this.state = "csi";
47
+ this.sequence = "";
48
+ continue;
49
+ }
50
+ if (code === 0x18 || code === 0x1a) {
51
+ this.state = "text";
52
+ this.sequence = "";
53
+ continue;
54
+ }
55
+ if (this.state === "escape") {
56
+ if (char === "[") {
57
+ this.state = "csi";
58
+ continue;
59
+ }
60
+ if ("]PX^_".includes(char)) {
61
+ this.osc = char === "]";
62
+ this.state = "string";
63
+ continue;
64
+ }
65
+ if (code >= 0x20 && code <= 0x2f) {
66
+ this.state = "escape-intermediate";
67
+ continue;
68
+ }
69
+ if ("78DEM=>".includes(char))
70
+ out.push(`\x1b${char}`);
71
+ this.state = "text";
72
+ continue;
73
+ }
74
+ if (this.state === "escape-intermediate") {
75
+ if (code >= 0x30 && code <= 0x7e)
76
+ this.state = "text";
77
+ continue;
78
+ }
79
+ if (this.state === "csi") {
80
+ if (code >= 0x40 && code <= 0x7e) {
81
+ if (allowedCsi(this.sequence, char))
82
+ out.push(`\x1b[${this.sequence}${char}`);
83
+ this.sequence = "";
84
+ this.state = "text";
85
+ }
86
+ else if (this.sequence.length < 256 && code >= 0x20 && code <= 0x3f) {
87
+ this.sequence += char;
88
+ }
89
+ else {
90
+ this.sequence = "!";
91
+ }
92
+ continue;
93
+ }
94
+ if ((code >= 0x20 && !(code >= 0x7f && code <= 0x9f)) || "\b\t\n\r".includes(char))
95
+ out.push(char);
96
+ }
97
+ return out.join("");
98
+ }
99
+ }
100
+ function allowedCsi(params, final) {
101
+ if (params.length > 256 || params.includes("!"))
102
+ return false;
103
+ if (final === "h" || final === "l") {
104
+ const privateMode = params.startsWith("?");
105
+ const body = privateMode ? params.slice(1) : params;
106
+ const modes = privateMode ? [1, 6, 7, 25, 47, 1000, 1002, 1003, 1004, 1005, 1006, 1047, 1048, 1049, 2004] : [4, 20];
107
+ return /^\d+(;\d+)*$/.test(body) && body.split(";").every(n => modes.includes(Number(n)));
108
+ }
109
+ if (final === "m")
110
+ return /^[\d;:]*$/.test(params);
111
+ if ("ABCDEFGHIZ`adefJKLMPSTXrsu".includes(final))
112
+ return /^[\d;]*$/.test(params);
113
+ return final === "q" && /^[0-6]? $/.test(params);
114
+ }
Binary file
Binary file
Binary file
Binary file
@@ -1,2 +1,2 @@
1
- export const TUI_PAGES = Object.freeze(["flexible", "flexible-sign-in", "project"]);
1
+ export const TUI_PAGES = Object.freeze(["flexible", "flexible-sign-in", "project", "lead-providers", "projects"]);
2
2
  export const isTuiPage = (value) => typeof value === "string" && TUI_PAGES.includes(value);
@@ -6,7 +6,7 @@ import { spawnHoldingLink } from "./engine-handoff.js";
6
6
  import { trustedBinary } from "./trusted-path.js";
7
7
  export { aclVerdictOf, trustedBinary } from "./trusted-path.js";
8
8
  import { isTuiPage } from "./tui-contract.js";
9
- export const TUI_EXIT = { leave: 0, ended: 1, stop: 40, keep: 41, classic: 42, unprotected: 43 };
9
+ export const TUI_EXIT = { leave: 0, ended: 1, stop: 40, keep: 41, classic: 42, unprotected: 43, centralUnavailable: 44 };
10
10
  export const TUI_PACKAGES = Object.freeze({
11
11
  "darwin-arm64": "@toolroll/tui-darwin-arm64", "darwin-x64": "@toolroll/tui-darwin-x64",
12
12
  "linux-x64": "@toolroll/tui-linux-x64", "linux-arm64": "@toolroll/tui-linux-arm64",
@@ -194,6 +194,25 @@ export function chooseTuiBinary(input) {
194
194
  return note({ ok: false, why: "the terminal workbench changed while it was being checked" }, notice);
195
195
  return note({ ok: true, binary, identity }, notice);
196
196
  }
197
+ export function formatCentralBootstrapPayload(input) {
198
+ const payload = JSON.stringify({
199
+ bootstrap: 1,
200
+ kind: "central-token",
201
+ connectionProtocol: 1,
202
+ origin: input.origin,
203
+ binding: {
204
+ kind: "enrolled-person",
205
+ workspaceId: input.workspaceId,
206
+ recoveryGeneration: input.recoveryGeneration,
207
+ account: input.account,
208
+ },
209
+ token: input.token,
210
+ });
211
+ if (payload.includes("\\")) {
212
+ throw new Error("Central bootstrap payload contains characters that require escaping.");
213
+ }
214
+ return payload;
215
+ }
197
216
  export async function runTuiBinary(input) {
198
217
  const args = ["--control-fd", "4", ...(input.session.owned() ? ["--owned"] : []), ...(input.project === null ? [] : ["--project", input.project])];
199
218
  if (!isAbsolute(input.binary))
@@ -249,6 +268,16 @@ export async function runTuiBinary(input) {
249
268
  }
250
269
  continue;
251
270
  }
271
+ if (ask !== null && typeof ask === "object" && ask["want"] === "builder-password") {
272
+ const { task, setup } = ask;
273
+ if (typeof task !== "string" || !/^[A-Za-z0-9_-][A-Za-z0-9_.-]{0,127}$/.test(task) || typeof setup !== "boolean" || !input.session.openBuilderPassword)
274
+ continue;
275
+ void input.session.openBuilderPassword(task, setup).catch(() => "Could not open the browser.").then(said => {
276
+ if ("write" in asks && !child.killed && child.exitCode === null)
277
+ asks.write(`${JSON.stringify({ said })}\n`);
278
+ });
279
+ continue;
280
+ }
252
281
  if (ask !== null && typeof ask === "object" && ask["want"] === "browser") {
253
282
  const page = ask["page"];
254
283
  void (isTuiPage(page) ? input.session.openBrowser(page) : input.session.openBrowser()).catch(() => "The browser couldn't be opened.").then(said => {
@@ -280,6 +309,8 @@ export async function runTuiBinary(input) {
280
309
  return "keep";
281
310
  if (code === TUI_EXIT.ended)
282
311
  return "ended";
312
+ if (code === TUI_EXIT.centralUnavailable)
313
+ return "central-unavailable";
283
314
  if (code === TUI_EXIT.classic || code === TUI_EXIT.unprotected || code === -1)
284
315
  return "classic";
285
316
  return "leave";