toolroll 0.9.109 → 0.9.111

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 (155) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +5 -1
  3. package/THIRD_PARTY_NOTICES.md +30 -0
  4. package/dist/agent-detect.js +244 -0
  5. package/dist/agent-fence.js +12 -1
  6. package/dist/agent-said-schema.js +4 -0
  7. package/dist/agent-said.js +23 -0
  8. package/dist/agentconfig.js +2 -2
  9. package/dist/approval-summary.js +375 -0
  10. package/dist/attest.js +2 -2
  11. package/dist/browser/THIRD_PARTY_NOTICES.txt +30 -0
  12. package/dist/browser/workspace.css +2 -2
  13. package/dist/browser/workspace.js +27 -27
  14. package/dist/builder.js +42 -3
  15. package/dist/chat-actions.js +24 -17
  16. package/dist/chat-core.js +3 -1
  17. package/dist/chat-decide.js +101 -46
  18. package/dist/chat-delivery-state.js +2 -0
  19. package/dist/chat-delivery.js +3 -2
  20. package/dist/chat-live.js +2 -1
  21. package/dist/chat-task-actions.js +6 -0
  22. package/dist/check-report.js +1 -1
  23. package/dist/claim.js +28 -13
  24. package/dist/cli-help.js +1 -1
  25. package/dist/cli.js +2 -0
  26. package/dist/codex-limits.js +21 -8
  27. package/dist/console-instance.js +11 -1
  28. package/dist/contracts/console-api.js +13 -7
  29. package/dist/contracts/engine-api.js +283 -0
  30. package/dist/contracts/route.js +1 -0
  31. package/dist/coordinator.js +2 -2
  32. package/dist/discord-api.js +4 -3
  33. package/dist/discord-chat.js +3 -1
  34. package/dist/dispatch.js +1 -1
  35. package/dist/dispose.js +15 -9
  36. package/dist/easy-start-args.js +7 -3
  37. package/dist/easy-start.js +40 -1
  38. package/dist/egress.js +72 -10
  39. package/dist/engine-handoff.js +34 -0
  40. package/dist/engine-reads.js +338 -0
  41. package/dist/eval-world.js +3 -2
  42. package/dist/evidence.js +2 -0
  43. package/dist/fast-start.js +68 -18
  44. package/dist/fast-terms.js +2 -2
  45. package/dist/first-run.js +10 -2
  46. package/dist/flexible-agents.js +234 -0
  47. package/dist/flexible-answers-schema.js +61 -0
  48. package/dist/flexible-answers.js +889 -0
  49. package/dist/flexible-custody.js +494 -0
  50. package/dist/flexible-import.js +782 -0
  51. package/dist/flexible-launch-schema.js +72 -0
  52. package/dist/flexible-launch.js +331 -0
  53. package/dist/flexible-launcher.js +88 -0
  54. package/dist/flexible-levels.js +34 -0
  55. package/dist/flexible-merge-guard.js +47 -0
  56. package/dist/flexible-refs.js +47 -0
  57. package/dist/flexible-relay-cancel.js +19 -0
  58. package/dist/flexible-relay-schema.js +55 -0
  59. package/dist/flexible-relay-upstreams.js +36 -0
  60. package/dist/flexible-relay.js +1032 -0
  61. package/dist/flexible-session.js +732 -0
  62. package/dist/flexible-ship-schema.js +81 -0
  63. package/dist/flexible-ship.js +694 -0
  64. package/dist/flexible-start.js +80 -0
  65. package/dist/flexible-thread.js +175 -25
  66. package/dist/flexible-turns-schema.js +69 -0
  67. package/dist/flexible-turns.js +490 -0
  68. package/dist/flexible.js +10 -1
  69. package/dist/flow-actions.js +6 -4
  70. package/dist/flow-steps.js +1 -1
  71. package/dist/flows-cli.js +2 -1
  72. package/dist/git-views.js +6 -3
  73. package/dist/install-mode.js +225 -0
  74. package/dist/integrations.js +6 -1
  75. package/dist/lead-doors.js +7 -1
  76. package/dist/limits-ui.js +7 -0
  77. package/dist/live-reply.js +6 -0
  78. package/dist/live-terminal.js +425 -29
  79. package/dist/local-owner.js +7 -0
  80. package/dist/model-choices.js +12 -6
  81. package/dist/needs-you.js +2 -0
  82. package/dist/notification-delivery.js +11 -0
  83. package/dist/operate.js +128 -37
  84. package/dist/outbound-privacy.js +204 -0
  85. package/dist/passwordless.js +2 -1
  86. package/dist/phase-routing.js +3 -1
  87. package/dist/plane-review.js +1 -1
  88. package/dist/project-delete.js +14 -0
  89. package/dist/proposal.js +2 -2
  90. package/dist/provider-connection.js +19 -5
  91. package/dist/publish.js +5 -0
  92. package/dist/pull-request-flow.js +26 -7
  93. package/dist/push.js +5 -1
  94. package/dist/release-card.js +11 -3
  95. package/dist/release.js +10 -1
  96. package/dist/route-store.js +3 -3
  97. package/dist/sandbox-launch.js +32 -8
  98. package/dist/sandbox-runtime.js +16 -7
  99. package/dist/sandbox-tools.js +176 -0
  100. package/dist/scope.js +12 -36
  101. package/dist/scout-net.js +7 -2
  102. package/dist/serve.js +62 -13
  103. package/dist/server/chrome.js +3 -1
  104. package/dist/server/console.css +33 -6
  105. package/dist/server/engine-api.js +378 -0
  106. package/dist/server/flows.js +2 -2
  107. package/dist/server/http.js +7 -0
  108. package/dist/server/link-redemption.js +52 -0
  109. package/dist/server/mutation-key.js +21 -7
  110. package/dist/server/pages.js +72 -40
  111. package/dist/server/people-tokens.js +17 -41
  112. package/dist/server/render-chat.js +1 -0
  113. package/dist/server/render-new-task.js +3 -3
  114. package/dist/server/render-results.js +4 -4
  115. package/dist/server/render-tasks.js +133 -139
  116. package/dist/server/route-table.js +32 -1
  117. package/dist/server/settings-section-table.js +6 -0
  118. package/dist/server/settings-sections.js +69 -0
  119. package/dist/server/settings.js +120 -10
  120. package/dist/server/task-views.js +8 -2
  121. package/dist/server/tasks.js +56 -12
  122. package/dist/server/terminals.js +181 -28
  123. package/dist/server/welcome.js +35 -10
  124. package/dist/settings-groups-ui.js +2 -2
  125. package/dist/settings-proofs.js +14 -9
  126. package/dist/slack-api.js +4 -3
  127. package/dist/slack-chat.js +5 -3
  128. package/dist/spend.js +46 -12
  129. package/dist/status-probe.js +343 -0
  130. package/dist/store.js +181 -12
  131. package/dist/task-sizing-schema.js +14 -0
  132. package/dist/task-sizing.js +76 -10
  133. package/dist/teams-api.js +4 -3
  134. package/dist/teams-chat.js +4 -2
  135. package/dist/telegram-lead.js +2 -1
  136. package/dist/telegram-live.js +2 -1
  137. package/dist/telegram-team.js +2 -1
  138. package/dist/telegram.js +17 -5
  139. package/dist/toolroll-update.js +3 -1
  140. package/dist/trusted-path.js +162 -0
  141. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  142. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  143. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  144. package/dist/tui/linux-x64/toolroll-tui +0 -0
  145. package/dist/tui-launch.js +282 -0
  146. package/dist/tui-source.js +5 -3
  147. package/dist/tui.js +1 -1
  148. package/dist/webhooks.js +14 -4
  149. package/dist/welcome-facts.js +22 -15
  150. package/dist/work-index.js +2 -2
  151. package/dist/workspace-ui.js +5 -0
  152. package/package.json +1 -1
  153. package/scripts/crash-canary.mjs +1 -1
  154. package/scripts/pilot.mjs +1 -1
  155. package/scripts/provider-canary.mjs +5 -3
@@ -1,10 +1,12 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { createRequire } from "node:module";
3
3
  import { execFileSync } from "node:child_process";
4
- import { existsSync, mkdirSync, readlinkSync, realpathSync, statSync } from "node:fs";
4
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
5
5
  import { delimiter, isAbsolute, join } from "node:path";
6
6
  import { codingEnvironment } from "./coding-provider.js";
7
- import { teardownGit, refusal } from "./teardown-git.js";
7
+ import { teardownGit, refusal, recordedCommonDir, TEARDOWN_FLAGS } from "./teardown-git.js";
8
+ import { run } from "./exec.js";
9
+ import { ENV, ENV_ALLOWLIST } from "./remote-main.js";
8
10
  import { sleep } from "./sleep.js";
9
11
  export const TERMINAL_PROGRAMS = ["claude", "codex", "shell"];
10
12
  export const MAX_LIVE_TERMINALS = 8;
@@ -42,6 +44,8 @@ export function loadPtySpawn() {
42
44
  write: data => native.write(data),
43
45
  resize: (cols, rows) => native.resize(cols, rows),
44
46
  kill: signal => native.kill(signal),
47
+ pause: () => native.pause(),
48
+ resume: () => native.resume(),
45
49
  };
46
50
  };
47
51
  }
@@ -63,28 +67,85 @@ export class ScreenMirror {
63
67
  this.serializer = new SerializeAddon();
64
68
  this.terminal.loadAddon(this.serializer);
65
69
  }
66
- write(data) { this.terminal.write(data); }
70
+ pending = 0;
71
+ write(data) {
72
+ const size = data.length;
73
+ this.pending += size;
74
+ try {
75
+ this.terminal.write(data, () => { this.pending -= size; });
76
+ return true;
77
+ }
78
+ catch {
79
+ this.pending -= size;
80
+ return false;
81
+ }
82
+ }
67
83
  resize(cols, rows) { try {
68
84
  this.terminal.resize(cols, rows);
69
85
  }
70
86
  catch { } }
71
87
  snapshot(done) {
72
- this.terminal.write("", () => { let screen = ""; try {
73
- screen = this.serializer.serialize({ scrollback: this.lines });
74
- }
75
- catch {
76
- screen = "";
77
- } done(screen); });
88
+ this.terminal.write("", () => {
89
+ let screen = "";
90
+ for (let lines = this.lines;; lines = Math.floor(lines / 2)) {
91
+ try {
92
+ screen = this.serializer.serialize({ scrollback: lines });
93
+ }
94
+ catch {
95
+ screen = "";
96
+ }
97
+ if (screen.length <= SNAPSHOT_MAX_CHARS || lines === 0)
98
+ break;
99
+ }
100
+ done(screen.length <= SNAPSHOT_MAX_CHARS ? screen : "");
101
+ });
78
102
  }
79
103
  dispose() { try {
80
104
  this.terminal.dispose();
81
105
  }
82
106
  catch { } }
83
107
  }
108
+ export const VIEWER_PAUSE_BYTES = 1024 * 1024;
109
+ export const VIEWER_RESUME_BYTES = 256 * 1024;
110
+ export const MIRROR_PAUSE_CHARS = 4 * 1024 * 1024;
111
+ export const MIRROR_RESUME_CHARS = 1024 * 1024;
112
+ export const ATTACH_HOLD_BYTES = 4 * 1024 * 1024;
113
+ export const SNAPSHOT_MAX_CHARS = 8 * 1024 * 1024;
114
+ export const SENSITIVE_EARLY_BYTES = 256 * 1024;
115
+ export const SENSITIVE_ATTACH_MS = 30_000;
116
+ export const MAX_AGENT_PANES = 1;
117
+ export const DROPPED_WORDS = "\r\n[Toolroll: earlier output was dropped]\r\n";
84
118
  const NO_LEDGER = { reserve() { }, running() { }, release() { }, forget() { } };
85
119
  export class TerminalError extends Error {
86
120
  constructor(message) { super(message); this.name = "TerminalError"; }
87
121
  }
122
+ export const COPY_CONFIG = "[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n\tlogallrefupdates = true\n";
123
+ export const TAKE_OVER_ENV = ["HOME", "USER", "LOGNAME", "SHELL", "PATH", "LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES", "TMPDIR", "TZ"];
124
+ export function takeOverEnvironment(from, buildWritable = []) {
125
+ const env = {};
126
+ for (const key of TAKE_OVER_ENV)
127
+ if (typeof from[key] === "string")
128
+ env[key] = from[key];
129
+ if (env["PATH"] !== undefined)
130
+ env["PATH"] = trustedPath(env["PATH"], buildWritable);
131
+ return env;
132
+ }
133
+ export function trustedPath(path, buildWritable) {
134
+ const real = (p) => { try {
135
+ return realpathSync(p);
136
+ }
137
+ catch {
138
+ return null;
139
+ } };
140
+ const roots = buildWritable.flatMap(root => [root, real(root)]).filter((one) => one !== null && one !== "");
141
+ const inside = (p) => roots.some(root => p === root || p.startsWith(root.endsWith("/") ? root : `${root}/`));
142
+ return path.split(delimiter).filter(entry => {
143
+ if (entry === "" || !isAbsolute(entry) || entry.split("/").includes(".."))
144
+ return false;
145
+ const resolved = real(entry);
146
+ return !inside(entry) && (resolved === null || !inside(resolved));
147
+ }).join(delimiter);
148
+ }
88
149
  const clamp = (value, range) => Math.min(range.max, Math.max(range.min, Math.trunc(value)));
89
150
  export function onPath(name, env = process.env) {
90
151
  if (isAbsolute(name))
@@ -133,8 +194,8 @@ export class TerminalHost {
133
194
  this.processes = options.processes ?? readProcessTable;
134
195
  }
135
196
  summary(session) {
136
- const { id, owner, generation, repo, program, branch, worktree, startedAt, endedAt, exit, endedBy, cleanup } = session;
137
- return { id, owner, generation, repo, program, branch, worktree, startedAt, endedAt, exit, endedBy, cleanup };
197
+ const { id, owner, generation, localGeneration, task, run, agent, repo, program, branch, worktree, startedAt, endedAt, exit, endedBy, cleanup } = session;
198
+ return { id, owner, generation, localGeneration, task, run, agent: agent === null ? null : { ...agent }, repo, program, branch, worktree, startedAt, endedAt, exit, endedBy, cleanup };
138
199
  }
139
200
  list(owner) {
140
201
  return [...this.sessions.values()].filter(one => one.owner === owner).map(one => this.summary(one)).reverse();
@@ -144,18 +205,23 @@ export class TerminalHost {
144
205
  return session === undefined ? null : this.summary(session);
145
206
  }
146
207
  running() {
147
- return [...this.sessions.values()].filter(one => one.endedAt === null).length;
208
+ return [...this.sessions.values()].filter(one => one.endedAt === null && one.agent === null).length;
209
+ }
210
+ kept() {
211
+ return [...this.sessions.values()].filter(one => one.agent === null).length;
148
212
  }
149
- async start({ name: owner, generation }, repoPath, program, size = { cols: 100, rows: 30 }, admit = () => null) {
213
+ startingAgents = 0;
214
+ async start({ name: owner, generation, localGeneration = null }, repoPath, program, size = { cols: 100, rows: 30 }, admit = () => null, from = null) {
150
215
  if (this.stopped)
151
216
  throw new TerminalError("The console is stopping.");
152
217
  if (!TERMINAL_PROGRAMS.includes(program))
153
218
  throw new TerminalError("Choose Claude, Codex or a shell.");
154
219
  if (this.running() + this.starting >= (this.options.maxSessions ?? MAX_LIVE_TERMINALS))
155
220
  throw new TerminalError(`At most ${this.options.maxSessions ?? MAX_LIVE_TERMINALS} terminals can run at once. Close one first.`);
156
- if (this.sessions.size + this.starting >= MAX_KEPT_TERMINALS)
221
+ if (this.kept() + this.starting >= MAX_KEPT_TERMINALS)
157
222
  throw new TerminalError(`${MAX_KEPT_TERMINALS} terminals are kept already. Remove an ended one first.`);
158
- const env = { ...this.env(), TERM: "xterm-256color", COLORTERM: "truecolor" };
223
+ const roots = [this.options.worktreeRoot, ...(this.options.buildWritable?.() ?? []), ...this.moreBuildWritable.flatMap(more => more())];
224
+ const env = { ...(from === null ? this.env() : takeOverEnvironment(this.env(), roots)), TERM: "xterm-256color", COLORTERM: "truecolor" };
159
225
  const command = this.options.programs?.[program] ?? defaultProgram(program, env);
160
226
  if (command === null)
161
227
  throw new TerminalError(`${program === "claude" ? "Claude Code" : "Codex"} isn't installed on this computer (\`${program}\` is not on PATH).`);
@@ -186,11 +252,19 @@ export class TerminalHost {
186
252
  };
187
253
  if (realpathSync(await git(["rev-parse", "--show-toplevel"])) !== repo)
188
254
  throw new TerminalError("Choose the root of a Git project.");
189
- const base = await git(["rev-parse", "--verify", "HEAD^{commit}"]);
255
+ if (from !== null && !/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(from.revision))
256
+ throw new TerminalError("This build has no saved commit to open a terminal on.");
257
+ const base = from === null ? await git(["rev-parse", "--verify", "HEAD^{commit}"])
258
+ : await git(["--no-replace-objects", "rev-parse", "--verify", "--end-of-options", `${from.revision}^{commit}`]).catch(() => "");
259
+ if (from !== null && base !== from.revision)
260
+ throw new TerminalError("This build's saved commit isn't in the project any more, so there is nothing to open a terminal on.");
190
261
  const branch = `toolroll/live-${id.slice(0, 12)}`;
191
262
  const worktree = join(this.options.worktreeRoot, id);
192
263
  mkdirSync(this.options.worktreeRoot, { recursive: true, mode: 0o700 });
193
- await git(["worktree", "add", "-b", branch, "--", worktree, base]);
264
+ if (from === null)
265
+ await git(["worktree", "add", "-b", branch, "--", worktree, base]);
266
+ else
267
+ await this.copyAt(repo, worktree, branch, base);
194
268
  const cols = clamp(size.cols, COLS), rows = clamp(size.rows, ROWS);
195
269
  let pty;
196
270
  try {
@@ -202,14 +276,18 @@ export class TerminalHost {
202
276
  pty = this.options.spawn(command.file, command.args, { cwd: worktree, env, cols, rows });
203
277
  }
204
278
  catch (error) {
205
- await git(["worktree", "remove", "--force", "--", worktree]).catch(() => { });
206
- await git(["branch", "-D", "--", branch]).catch(() => { });
279
+ if (from !== null)
280
+ rmSync(worktree, { recursive: true, force: true });
281
+ else {
282
+ await git(["worktree", "remove", "--force", "--", worktree]).catch(() => { });
283
+ await git(["branch", "-D", "--", branch]).catch(() => { });
284
+ }
207
285
  throw error instanceof TerminalError ? error : new TerminalError(`The program couldn't start: ${error instanceof Error ? error.message : String(error)}`);
208
286
  }
209
287
  let resolveExited;
210
- const session = { id, owner, generation, repo, program, branch, worktree, startedAt: this.clock().toISOString(), endedAt: null, exit: null, endedBy: null, cleanup: null,
211
- pty, leader: pty.pid, tty: pty.tty, known: new Map(), exitedAt: null, worktreeReal: realpathSync(worktree), startedMs: Date.now(), residentsOnly: false, residentsSeen: new Map(), cols, rows, screen: new ScreenMirror(cols, rows, this.options.scrollbackLines), viewers: new Set(), closing: null,
212
- exited: new Promise(resolve => { resolveExited = resolve; }) };
288
+ const session = { id, owner, generation, localGeneration, task: from?.task ?? null, run: from?.run ?? null, agent: null, base: from === null ? null : base, repo, program, branch, worktree, startedAt: this.clock().toISOString(), endedAt: null, exit: null, endedBy: null, cleanup: null,
289
+ pty, leader: pty.pid, tty: pty.tty, known: new Map(), exitedAt: null, worktreeReal: realpathSync(worktree), startedMs: Date.now(), residentsOnly: false, residentsSeen: new Map(), cols, rows, screen: new ScreenMirror(cols, rows, this.options.scrollbackLines), paused: false, flowTimer: null, attaching: 0, viewers: new Set(), closing: null,
290
+ exited: new Promise(resolve => { resolveExited = resolve; }), sensitive: false, attachedOnce: false, early: [], earlyBytes: 0, dropped: false, attachTimer: null };
213
291
  this.sessions.set(id, session);
214
292
  this.ledger.running(id);
215
293
  reserved = false;
@@ -217,16 +295,27 @@ export class TerminalHost {
217
295
  pty.onData(data => {
218
296
  this.noteSoon();
219
297
  const chunk = Buffer.from(data, "utf8");
220
- session.screen.write(data);
298
+ if (!session.screen.write(data))
299
+ for (const viewer of session.viewers) {
300
+ try {
301
+ viewer.overflow?.();
302
+ }
303
+ catch { }
304
+ }
221
305
  for (const viewer of session.viewers) {
222
306
  try {
223
307
  viewer.output(chunk);
224
308
  }
225
309
  catch { }
226
310
  }
311
+ this.flow(session);
227
312
  });
228
313
  pty.onExit(({ exitCode, signal }) => {
229
314
  session.pty = null;
315
+ if (session.flowTimer !== null) {
316
+ clearInterval(session.flowTimer);
317
+ session.flowTimer = null;
318
+ }
230
319
  session.exitedAt = Date.now();
231
320
  session.endedAt = this.clock().toISOString();
232
321
  session.exit = { code: exitCode ?? null, signal: signal || null };
@@ -250,26 +339,222 @@ export class TerminalHost {
250
339
  this.ledger.release(id, null);
251
340
  }
252
341
  }
342
+ async startCommand({ name: owner, generation, localGeneration = null }, agent, command, env, size = { cols: 100, rows: 30 }, admit = () => null, exited = () => { }) {
343
+ if (this.stopped)
344
+ throw new TerminalError("The console is stopping.");
345
+ const open = [...this.sessions.values()].filter(one => one.agent !== null).length;
346
+ if (open + this.startingAgents >= MAX_AGENT_PANES)
347
+ throw new TerminalError("A sign-in or install is already open. Finish it (or close it) first.");
348
+ const id = randomBytes(16).toString("hex");
349
+ this.startingAgents += 1;
350
+ let reserved = false;
351
+ try {
352
+ try {
353
+ this.ledger.reserve(id);
354
+ reserved = true;
355
+ }
356
+ catch (error) {
357
+ throw error instanceof TerminalError ? error : new TerminalError(error instanceof Error ? error.message : "No terminal can start right now.");
358
+ }
359
+ mkdirSync(this.options.worktreeRoot, { recursive: true, mode: 0o700 });
360
+ const folder = join(this.options.worktreeRoot, `agent-${id}`);
361
+ mkdirSync(folder, { recursive: false, mode: 0o700 });
362
+ const cols = clamp(size.cols, COLS), rows = clamp(size.rows, ROWS);
363
+ let pty;
364
+ try {
365
+ if (this.stopped)
366
+ throw new TerminalError("The console is stopping.");
367
+ const refused = admit();
368
+ if (refused !== null)
369
+ throw new TerminalError(refused);
370
+ pty = this.options.spawn(command.file, [...command.args], { cwd: folder, env: { ...env, TERM: "xterm-256color", COLORTERM: "truecolor" }, cols, rows });
371
+ }
372
+ catch (error) {
373
+ rmSync(folder, { recursive: true, force: true });
374
+ throw error instanceof TerminalError ? error : new TerminalError(`The program couldn't start: ${error instanceof Error ? error.message : String(error)}`);
375
+ }
376
+ let resolveExited;
377
+ const session = { id, owner, generation, localGeneration, task: null, run: null, agent: { ...agent }, base: null, repo: "", program: "shell", branch: "", worktree: folder, startedAt: this.clock().toISOString(), endedAt: null, exit: null, endedBy: null, cleanup: null,
378
+ pty, leader: pty.pid, tty: pty.tty, known: new Map(), exitedAt: null, worktreeReal: realpathSync(folder), startedMs: Date.now(), residentsOnly: false, residentsSeen: new Map(), cols, rows, screen: new ScreenMirror(cols, rows, 0), paused: false, flowTimer: null, attaching: 0, viewers: new Set(), closing: null,
379
+ exited: new Promise(resolve => { resolveExited = resolve; }), sensitive: true, attachedOnce: false, early: [], earlyBytes: 0, dropped: false, attachTimer: null };
380
+ this.wire(session, () => { resolveExited(); try {
381
+ exited();
382
+ }
383
+ catch { } });
384
+ this.sessions.set(id, session);
385
+ this.ledger.running(id);
386
+ reserved = false;
387
+ this.noteCustody();
388
+ session.attachTimer = setTimeout(() => {
389
+ session.attachTimer = null;
390
+ if (session.attachedOnce)
391
+ return;
392
+ this.forgetScreen(session);
393
+ void this.close(session.id, "console").then(() => this.drop(session));
394
+ }, this.options.sensitiveAttachMs ?? SENSITIVE_ATTACH_MS);
395
+ session.attachTimer.unref?.();
396
+ this.options.record?.("start", this.summary(session));
397
+ return this.summary(session);
398
+ }
399
+ finally {
400
+ this.startingAgents -= 1;
401
+ if (reserved)
402
+ this.ledger.release(id, null);
403
+ }
404
+ }
405
+ drop(session) {
406
+ if (this.sessions.get(session.id) !== session)
407
+ return;
408
+ if (session.attachTimer !== null) {
409
+ clearTimeout(session.attachTimer);
410
+ session.attachTimer = null;
411
+ }
412
+ this.sessions.delete(session.id);
413
+ this.ledger.forget(session.id);
414
+ session.viewers.clear();
415
+ this.forgetScreen(session);
416
+ session.screen.dispose();
417
+ rmSync(session.worktree, { recursive: true, force: true });
418
+ this.options.record?.("remove", this.summary(session));
419
+ }
420
+ heldBytes(id) { return this.sessions.get(id)?.earlyBytes ?? 0; }
421
+ wire(session, onExited) {
422
+ const pty = session.pty;
423
+ pty.onData(data => {
424
+ this.noteSoon();
425
+ const chunk = Buffer.from(data, "utf8");
426
+ if (session.sensitive) {
427
+ if (!session.attachedOnce) {
428
+ if (session.earlyBytes + chunk.byteLength <= SENSITIVE_EARLY_BYTES && !session.dropped) {
429
+ session.early.push(chunk);
430
+ session.earlyBytes += chunk.byteLength;
431
+ }
432
+ else {
433
+ session.early = [];
434
+ session.earlyBytes = 0;
435
+ session.dropped = true;
436
+ }
437
+ }
438
+ }
439
+ else if (!session.screen.write(data))
440
+ for (const viewer of session.viewers) {
441
+ try {
442
+ viewer.overflow?.();
443
+ }
444
+ catch { }
445
+ }
446
+ for (const viewer of session.viewers) {
447
+ try {
448
+ viewer.output(chunk);
449
+ }
450
+ catch { }
451
+ }
452
+ this.flow(session);
453
+ });
454
+ pty.onExit(({ exitCode, signal }) => {
455
+ session.pty = null;
456
+ if (session.flowTimer !== null) {
457
+ clearInterval(session.flowTimer);
458
+ session.flowTimer = null;
459
+ }
460
+ session.exitedAt = Date.now();
461
+ session.endedAt = this.clock().toISOString();
462
+ session.exit = { code: exitCode ?? null, signal: signal || null };
463
+ for (const viewer of session.viewers) {
464
+ try {
465
+ viewer.control({ t: "exit", code: session.exit.code, signal: session.exit.signal });
466
+ }
467
+ catch { }
468
+ }
469
+ this.options.record?.("exit", this.summary(session));
470
+ if (session.sensitive)
471
+ this.forgetScreen(session);
472
+ onExited();
473
+ if (session.closing === null)
474
+ session.closing = this.sweep(session);
475
+ if (session.agent !== null)
476
+ void session.closing.then(() => this.drop(session));
477
+ });
478
+ }
479
+ async copyAt(repo, folder, branch, revision) {
480
+ let source;
481
+ try {
482
+ source = realpathSync(recordedCommonDir(repo));
483
+ }
484
+ catch {
485
+ throw new TerminalError("Toolroll couldn't read this project's own git folder, so it won't open a copy of the build.");
486
+ }
487
+ for (const borrowed of ["alternates", "http-alternates"]) {
488
+ if (existsSync(join(source, "objects", "info", borrowed)))
489
+ throw new TerminalError("This project's git reads objects from another folder (alternates), so Toolroll won't copy a build from it.");
490
+ }
491
+ const template = join(this.options.worktreeRoot, ".empty-template");
492
+ mkdirSync(template, { recursive: true, mode: 0o700 });
493
+ if (readdirSync(template).length > 0 || lstatSync(template).isSymbolicLink())
494
+ throw new TerminalError("Toolroll's terminal folder isn't as it left it.");
495
+ const git = async (cwd, args, refused = "Git couldn't make a copy of this build for the terminal.") => {
496
+ const result = await (this.options.copyGit ?? run)("git", [...TEARDOWN_FLAGS, ...args], { cwd, envAllowlist: ENV_ALLOWLIST, env: { ...ENV }, timeoutMs: 300_000, maxBuffer: 16 * 1024 * 1024 });
497
+ if (result.code !== 0)
498
+ throw new TerminalError(refused);
499
+ return result;
500
+ };
501
+ mkdirSync(folder, { recursive: false, mode: 0o700 });
502
+ try {
503
+ await git(folder, ["init", "--quiet", `--template=${template}`, "-b", branch]);
504
+ writeFileSync(join(folder, ".git", "config"), COPY_CONFIG, { mode: 0o600 });
505
+ await git(folder, ["-c", "protocol.file.allow=always", "-c", "fetch.fsckObjects=true", "-c", "transfer.fsckObjects=true", "-c", "uploadpack.allowAnySHA1InWant=true",
506
+ "fetch", "--quiet", "--no-tags", "--no-recurse-submodules", "--depth", "1", "--", source, revision], "This build's saved commit didn't copy whole (an object in the project's git isn't what its name says), so Toolroll won't open it.");
507
+ await git(folder, ["reset", "--quiet", "--hard", revision]);
508
+ const head = (await git(folder, ["rev-parse", "--verify", "HEAD^{commit}"])).stdout.trim();
509
+ if (head !== revision)
510
+ throw new TerminalError("The copy of this build isn't at its saved commit.");
511
+ }
512
+ catch (error) {
513
+ rmSync(folder, { recursive: true, force: true });
514
+ throw error instanceof TerminalError ? error : new TerminalError("Git couldn't make a copy of this build for the terminal.");
515
+ }
516
+ }
253
517
  attach(id, viewer) {
254
518
  const session = this.sessions.get(id);
255
519
  if (session === undefined)
256
520
  throw new TerminalError("No such terminal.");
521
+ if (session.sensitive)
522
+ return this.attachOnce(session, viewer);
257
523
  if (session.viewers.size >= MAX_VIEWERS)
258
524
  throw new TerminalError(`This terminal is open in ${MAX_VIEWERS} places already. Close one of them.`);
259
525
  const held = [];
260
- let live = false;
526
+ let live = false, heldBytes = 0, attaching = true;
527
+ const done = () => { if (attaching) {
528
+ attaching = false;
529
+ session.attaching -= 1;
530
+ this.flow(session);
531
+ } };
261
532
  const gate = {
262
- output: data => { if (live)
263
- viewer.output(data);
264
- else
265
- held.push({ output: data }); },
533
+ output: data => {
534
+ if (live)
535
+ return viewer.output(data);
536
+ heldBytes += data.byteLength;
537
+ if (heldBytes > ATTACH_HOLD_BYTES) {
538
+ held.length = 0;
539
+ session.viewers.delete(gate);
540
+ done();
541
+ viewer.overflow?.();
542
+ return;
543
+ }
544
+ held.push({ output: data });
545
+ },
266
546
  control: message => { if (live)
267
547
  viewer.control(message);
268
548
  else
269
549
  held.push({ control: message }); },
550
+ backlog: () => viewer.backlog?.() ?? 0,
551
+ overflow: () => viewer.overflow?.(),
270
552
  };
271
553
  session.viewers.add(gate);
554
+ session.attaching += 1;
555
+ this.flow(session);
272
556
  session.screen.snapshot(screen => {
557
+ done();
273
558
  if (!session.viewers.has(gate))
274
559
  return;
275
560
  try {
@@ -289,8 +574,86 @@ export class TerminalHost {
289
574
  held.length = 0;
290
575
  live = true;
291
576
  });
292
- return () => { session.viewers.delete(gate); };
577
+ return () => { session.viewers.delete(gate); done(); this.flow(session); };
578
+ }
579
+ attachOnce(session, viewer) {
580
+ if (session.attachedOnce)
581
+ throw new TerminalError("This sign-in is open in one place only.");
582
+ session.attachedOnce = true;
583
+ if (session.attachTimer !== null) {
584
+ clearTimeout(session.attachTimer);
585
+ session.attachTimer = null;
586
+ }
587
+ session.viewers.add(viewer);
588
+ const early = session.early;
589
+ session.early = [];
590
+ session.earlyBytes = 0;
591
+ try {
592
+ viewer.control({ t: "hello", cols: session.cols, rows: session.rows, program: session.program, ended: session.endedAt !== null });
593
+ if (session.dropped)
594
+ viewer.output(Buffer.from(DROPPED_WORDS, "utf8"));
595
+ for (const chunk of early)
596
+ viewer.output(chunk);
597
+ if (session.exit !== null)
598
+ viewer.control({ t: "exit", code: session.exit.code, signal: session.exit.signal });
599
+ }
600
+ catch { }
601
+ early.length = 0;
602
+ this.flow(session);
603
+ return () => {
604
+ session.viewers.delete(viewer);
605
+ void this.close(session.id, "owner").then(() => this.drop(session));
606
+ };
607
+ }
608
+ forgetScreen(session) {
609
+ session.early = [];
610
+ session.earlyBytes = 0;
611
+ session.screen.dispose();
612
+ session.screen = new ScreenMirror(session.cols, session.rows, 0);
613
+ }
614
+ replay(id) {
615
+ const session = this.sessions.get(id);
616
+ if (session === undefined || session.sensitive)
617
+ return Promise.resolve("");
618
+ return new Promise(done => session.screen.snapshot(done));
619
+ }
620
+ flow(session) {
621
+ const pty = session.pty;
622
+ if (pty === null)
623
+ return;
624
+ const backlogs = [...session.viewers].map(one => { try {
625
+ return one.backlog?.() ?? 0;
626
+ }
627
+ catch {
628
+ return 0;
629
+ } });
630
+ const over = session.attaching > 0 || session.screen.pending > MIRROR_PAUSE_CHARS || backlogs.some(n => n > VIEWER_PAUSE_BYTES);
631
+ const under = session.attaching === 0 && session.screen.pending <= MIRROR_RESUME_CHARS && backlogs.every(n => n <= VIEWER_RESUME_BYTES);
632
+ if (over && !session.paused) {
633
+ session.paused = true;
634
+ try {
635
+ pty.pause?.();
636
+ }
637
+ catch { }
638
+ session.flowTimer ??= setInterval(() => this.flow(session), 25);
639
+ session.flowTimer.unref?.();
640
+ }
641
+ else if (under && session.paused) {
642
+ session.paused = false;
643
+ try {
644
+ pty.resume?.();
645
+ }
646
+ catch { }
647
+ if (session.flowTimer !== null) {
648
+ clearInterval(session.flowTimer);
649
+ session.flowTimer = null;
650
+ }
651
+ }
293
652
  }
653
+ moreBuildWritable = [];
654
+ alsoBuildWritable(roots) { this.moreBuildWritable.push(roots); }
655
+ paused(id) { return this.sessions.get(id)?.paused ?? false; }
656
+ mirrorPending(id) { return this.sessions.get(id)?.screen.pending ?? 0; }
294
657
  viewerCount(id) { return this.sessions.get(id)?.viewers.size ?? 0; }
295
658
  input(id, data) {
296
659
  const pty = this.sessions.get(id)?.pty;
@@ -478,6 +841,11 @@ export class TerminalHost {
478
841
  throw busy;
479
842
  if ([...session.residentsSeen].some(([pid, started]) => table.get(pid)?.started === started))
480
843
  throw busy;
844
+ if (session.base !== null) {
845
+ const own = await this.copyHasWork(session.worktree, session.base);
846
+ if (own !== null)
847
+ throw new TerminalError(own);
848
+ }
481
849
  this.sessions.delete(id);
482
850
  this.ledger.forget(id);
483
851
  for (const viewer of session.viewers) {
@@ -488,6 +856,11 @@ export class TerminalHost {
488
856
  }
489
857
  session.viewers.clear();
490
858
  session.screen.dispose();
859
+ if (session.base !== null || session.agent !== null) {
860
+ rmSync(session.worktree, { recursive: true, force: true });
861
+ this.options.record?.("remove", this.summary(session));
862
+ return;
863
+ }
491
864
  const result = await (this.options.git ?? teardownGit())(session.repo, ["worktree", "remove", "--force", "--", session.worktree]);
492
865
  this.options.record?.("remove", this.summary(session));
493
866
  if (result.code !== 0 && existsSync(session.worktree)) {
@@ -495,6 +868,29 @@ export class TerminalHost {
495
868
  throw new TerminalError(`The terminal is gone, but its worktree stays${why === null ? "" : ` (${why})`}. Remove it with \`git worktree remove\`.`);
496
869
  }
497
870
  }
871
+ async copyHasWork(folder, base) {
872
+ const read = async (args) => (this.options.copyGit ?? run)("git", [...TEARDOWN_FLAGS, ...args], { cwd: folder, envAllowlist: ENV_ALLOWLIST, env: { ...ENV }, timeoutMs: 60_000, maxBuffer: 16 * 1024 * 1024 });
873
+ const stays = (what) => `This copy holds ${what} that exist nowhere else, so it stays at ${folder}. Copy what you need out of it, then delete the folder.`;
874
+ try {
875
+ const own = await read(["rev-list", "--all", "--reflog", "--not", base, "--"]);
876
+ const status = await read(["status", "--porcelain", "--untracked-files=all", "--ignore-submodules=all"]);
877
+ if (own.code !== 0 || status.code !== 0)
878
+ return stays("work (its git couldn't be read)");
879
+ const commits = own.stdout.split("\n").filter(line => /^[0-9a-f]{40,64}$/.test(line));
880
+ const lost = [];
881
+ if (commits.length > 0) {
882
+ const named = await read(["log", "--no-walk=unsorted", "--format=%h %s", ...commits.slice(0, 5), "--"]);
883
+ const list = named.code === 0 ? named.stdout.trim().split("\n").map(line => line.slice(0, 80)).join("; ") : commits.slice(0, 5).map(one => one.slice(0, 12)).join(", ");
884
+ lost.push(`${commits.length} commit${commits.length === 1 ? "" : "s"} (${list}${commits.length > 5 ? "; …" : ""})`);
885
+ }
886
+ if (status.stdout.trim() !== "")
887
+ lost.push("changes not committed");
888
+ return lost.length === 0 ? null : stays(lost.join(" and "));
889
+ }
890
+ catch {
891
+ return stays("work (its git couldn't be read)");
892
+ }
893
+ }
498
894
  get admitting() { return !this.stopped; }
499
895
  async stop() {
500
896
  this.stopped = true;
@@ -30,6 +30,13 @@ export const LOCAL_OWNER_ACTS = Object.freeze([
30
30
  "request-plan",
31
31
  "retry-build",
32
32
  "view-preference",
33
+ "take-over",
34
+ "start-thread",
35
+ "check-agents",
36
+ "agent-sign-in",
37
+ "agent-install",
38
+ "change-models",
39
+ "task-sizing-switch",
33
40
  ]);
34
41
  const ACT_SET = new Set(LOCAL_OWNER_ACTS);
35
42
  export function localOwnerAct(value) {