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
@@ -1,16 +1,22 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { STATUS_CODES } from "node:http";
3
3
  import { dirname, join } from "node:path";
4
- import { KEY_PROTOCOL } from "./mutation-key.js";
4
+ import { KEY_PROTOCOL, TERMINAL_EPOCH } from "./mutation-key.js";
5
5
  import { WebSocketServer } from "ws";
6
6
  import { readForm, CONSOLE_FORMS } from "../contracts/console-api.js";
7
7
  import { html, htmlString } from "../html.js";
8
8
  import { openTerminalLedger } from "../terminal-catalog.js";
9
9
  import { loadPtySpawn, MAX_FRAME_BYTES, TerminalHost, MAX_VIEWERS, parseTerminalFrame, TERMINAL_PROGRAMS, TerminalError } from "../live-terminal.js";
10
10
  import { logEvent } from "../log.js";
11
- import { passwordlessOn } from "../passwordless.js";
11
+ import { sessionStandsIn, soloNow } from "../install-mode.js";
12
+ import { localOwnerStandsNow } from "../local-owner.js";
13
+ import { resultRunsOf } from "../engine-reads.js";
14
+ import { checkEngineResponse } from "../contracts/engine-api.js";
12
15
  import { projectName, rowVisible } from "../project.js";
13
16
  import { transportOf } from "../public-access.js";
17
+ import { agentSetupOf } from "../agent-detect.js";
18
+ import { excludedFolders, launchPath, resolveLaunch, statusEnvironment } from "../status-probe.js";
19
+ import { boundedAcl } from "../trusted-path.js";
14
20
  import { handlersOf } from "./handler-registry.js";
15
21
  import { respond } from "./http.js";
16
22
  import { rereadBrowser } from "./live.js";
@@ -30,7 +36,8 @@ export function terminalHostFor(store, options) {
30
36
  if (spawn === null)
31
37
  return { host: null, problem: "This install has no terminal support (the optional @lydell/node-pty package didn't load). Reinstall Toolroll to add it." };
32
38
  const ledger = openTerminalLedger(store.raw());
33
- return { host: new TerminalHost({ spawn, worktreeRoot: join(dirname(database), "live-worktrees"), ...(ledger === null ? {} : { ledger }) }), problem: null };
39
+ const buildWritable = () => [dirname(database), ...store.knownRepos()];
40
+ return { host: new TerminalHost({ spawn, worktreeRoot: join(dirname(database), "live-worktrees"), buildWritable, ...(ledger === null ? {} : { ledger }) }), problem: null };
34
41
  }
35
42
  export function createTerminalHandlers(runtime, deps) {
36
43
  const { store, codingActorAllowed, codingProjectAllowed, liveCeiling } = runtime;
@@ -39,14 +46,42 @@ export function createTerminalHandlers(runtime, deps) {
39
46
  const sockets = new Set();
40
47
  const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME_BYTES, perMessageDeflate: false,
41
48
  handleProtocols: protocols => protocols.has(KEY_PROTOCOL) ? KEY_PROTOCOL : false });
42
- const operatorOf = (who) => who?.via === "cookie" && who.authority === "full" && who.role === "approver" && !store.isDemo() && codingActorAllowed({ name: who.name, generation: who.session.generation }) ? who : null;
49
+ const localOwnerNow = (who) => {
50
+ const hash = runtime.sessions.hashOf(who.session);
51
+ return who.session.localGeneration !== null && hash !== null && soloNow(store)
52
+ && localOwnerStandsNow(store, { account: who.name, localGeneration: who.session.localGeneration, accountGeneration: who.session.generation,
53
+ transport: "browser", act: "take-over", sessionHash: hash, request: null });
54
+ };
55
+ const operatorOf = (who) => {
56
+ if (who?.via !== "cookie" || who.role !== "approver" || store.isDemo() || !codingActorAllowed({ name: who.name, generation: who.session.generation }))
57
+ return null;
58
+ if (who.authority === "full")
59
+ return who;
60
+ return who.authority === "local-owner" && localOwnerNow(who) ? who : null;
61
+ };
43
62
  const projectAllowed = (name, repo) => rowVisible(liveCeiling(), repo) && store.accountCanAccess(name, repo) && codingProjectAllowed(repo);
44
- const owned = (who, terminal) => terminal !== null && terminal.owner === who.name && terminal.generation === who.session.generation;
63
+ const owned = (who, terminal) => terminal !== null && terminal.owner === who.name && terminal.generation === who.session.generation
64
+ && terminal.localGeneration === (who.authority === "full" ? null : who.session.localGeneration);
65
+ const reachable = (who, terminal, request) => owned(who, terminal) && (terminal.agent !== null ? workbenchNow(request, who) : projectAllowed(who.name, terminal.repo));
66
+ const workbenchNow = (request, who) => {
67
+ if (who?.via !== "cookie" || who.authority !== "local-owner")
68
+ return false;
69
+ const epoch = `${TERMINAL_EPOCH}${runtime.keyEpoch}`;
70
+ if (who.session.keyEpoch !== epoch)
71
+ return false;
72
+ const hash = runtime.sessions.hashOf(who.session);
73
+ if (hash === null || store.webSession(hash)?.keyEpoch !== epoch)
74
+ return false;
75
+ return soloNow(store) && runtime.fromThisComputer(request) && operatorOf(who) !== null;
76
+ };
45
77
  const record = (event, who, terminal) => logEvent("info", `terminal.${event}`, { actor: who, terminal: terminal.id, repo: terminal.repo, program: terminal.program });
46
78
  const json = (ctx, status, value) => respond(ctx.response, status, "application/json", JSON.stringify(value));
79
+ const checked = (ctx, status, name, value) => json(ctx, status, checkEngineResponse(name, value));
80
+ const WORKBENCH_ONLY = "Sign in to agents from your own terminal: run toolroll there";
81
+ const LOCAL_TEAM = "Taking over works while you're the only person using this Toolroll. Set a password (run `toolroll password set`) and sign in with it.";
47
82
  const refusal = (ctx) => {
48
83
  if (operatorOf(ctx.who) === null)
49
- return "Terminals are for installation-wide operators signed in with a browser.";
84
+ return ctx.who?.via === "cookie" && ctx.who.authority === "local-owner" ? LOCAL_TEAM : "Terminals are for installation-wide operators signed in with a browser.";
50
85
  if (deps.host === null)
51
86
  return deps.problem ?? "Terminals aren't available on this install.";
52
87
  return null;
@@ -58,7 +93,7 @@ export function createTerminalHandlers(runtime, deps) {
58
93
  const id = TERMINAL_ID.exec(url.pathname)?.[1] ?? "";
59
94
  const nonce = randomBytes(16).toString("base64");
60
95
  const host = request.headers.host ?? "";
61
- const document = html `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content"><meta name="theme-color" content="#0C0E12"><meta name="apple-mobile-web-app-capable" content="yes"><title>Terminals — Toolroll</title><link rel="icon" href="/icon.svg"><link rel="manifest" href="/manifest.webmanifest"><link rel="stylesheet" href="/assets/terminal.css"></head><body><div id="so-term"></div><div id="so-term-boot" hidden data-csrf="${who.session.csrf}" data-session="${id}" data-passwordless="${passwordlessOn(store) ? "1" : ""}"></div><script type="module" src="/assets/terminal.js" nonce="${nonce}"></script></body></html>`;
96
+ const document = html `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content"><meta name="theme-color" content="#0C0E12"><meta name="apple-mobile-web-app-capable" content="yes"><title>Terminals — Toolroll</title><link rel="icon" href="/icon.svg"><link rel="manifest" href="/manifest.webmanifest"><link rel="stylesheet" href="/assets/terminal.css"></head><body><div id="so-term"></div><div id="so-term-boot" hidden data-csrf="${who.session.csrf}" data-session="${id}" data-passwordless="${sessionStandsIn(store) || who.authority === "local-owner" ? "1" : ""}"></div><script type="module" src="/assets/terminal.js" nonce="${nonce}"></script></body></html>`;
62
97
  response.writeHead(200, {
63
98
  "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer",
64
99
  "Content-Security-Policy": `default-src 'none'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self'; manifest-src 'self'; script-src 'nonce-${nonce}'; connect-src 'self' ws://${host} wss://${host}; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
@@ -68,63 +103,176 @@ export function createTerminalHandlers(runtime, deps) {
68
103
  async function state(ctx) {
69
104
  const who = operatorOf(ctx.who);
70
105
  if (who === null)
71
- return json(ctx, 403, { error: "operator" });
72
- const sessions = deps.host === null ? [] : deps.host.list(who.name).filter(one => owned(who, one) && projectAllowed(who.name, one.repo));
73
- return json(ctx, 200, {
106
+ return checked(ctx, 403, "refusal", { error: "operator" });
107
+ const sessions = deps.host === null ? [] : deps.host.list(who.name).filter(one => one.agent === null && owned(who, one) && projectAllowed(who.name, one.repo));
108
+ return checked(ctx, 200, "termState", {
74
109
  available: deps.host !== null, problem: deps.host === null ? deps.problem ?? "Terminals aren't available on this install." : null,
75
- programs: TERMINAL_PROGRAMS,
110
+ programs: [...TERMINAL_PROGRAMS],
76
111
  projects: runtime.consoleProjects().filter(repo => projectAllowed(who.name, repo)).map(path => ({ path, name: projectName(path) })),
77
- sessions: sessions.map(one => ({ id: one.id, repo: one.repo, project: projectName(one.repo), program: one.program, branch: one.branch, startedAt: one.startedAt, endedAt: one.endedAt, exit: one.exit, cleanup: one.cleanup })),
112
+ sessions: sessions.map(one => ({ id: one.id, repo: one.repo, project: projectName(one.repo), program: one.program, branch: one.branch, startedAt: one.startedAt, endedAt: one.endedAt,
113
+ exit: one.exit, cleanup: one.cleanup, task: one.task, run: one.run })),
78
114
  });
79
115
  }
116
+ const takeOverOf = (taskId, runId) => {
117
+ const family = runtime.familyOf(taskId);
118
+ if (family === null || family.problem !== null)
119
+ return "No such task.";
120
+ const run = resultRunsOf(store, family).filter(one => runtime.runVisible(one)).find(one => one.id === runId) ?? null;
121
+ if (run === null)
122
+ return "This build has no saved result yet. Wait for it to finish (or stop it), then take over.";
123
+ const revision = run.headRevision;
124
+ if (revision === null || !/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(revision))
125
+ return "This build has no saved commit to open a terminal on.";
126
+ const repo = runtime.taskRepoOf(run.taskRef);
127
+ if (repo === null)
128
+ return "This build's project isn't known here.";
129
+ return { repo, revision };
130
+ };
80
131
  async function start(ctx) {
132
+ const answer = (status, value) => checked(ctx, status, "termStarted", value);
81
133
  const refused = refusal(ctx);
82
134
  if (refused !== null)
83
- return json(ctx, 403, { ok: false, error: refused });
135
+ return answer(403, { ok: false, error: refused });
84
136
  const who = ctx.who;
85
137
  const body = readForm(ctx.posted, CONSOLE_FORMS.term);
86
138
  if ([...new Set(body.keys())].some(key => body.sent.getAll(key).length !== 1))
87
- return json(ctx, 400, { ok: false, error: "Submit one value for each field." });
88
- const repo = body.get("repo") ?? "", program = body.get("program") ?? "";
139
+ return answer(400, { ok: false, error: "Submit one value for each field." });
140
+ const program = body.get("program") ?? "";
89
141
  if (!TERMINAL_PROGRAMS.includes(program))
90
- return json(ctx, 400, { ok: false, error: "Choose Claude Code, Codex or a shell." });
142
+ return answer(400, { ok: false, error: "Choose Claude Code, Codex or a shell." });
143
+ const taskField = body.get("task"), runField = body.get("run");
144
+ if ((taskField === null) !== (runField === null))
145
+ return answer(400, { ok: false, error: "Name the task and its build." });
146
+ let from = null, repo;
147
+ if (taskField !== null && runField !== null) {
148
+ if (body.get("repo") !== null || !/^[1-9][0-9]{0,14}$/.test(runField) || taskField === "" || taskField.length > 200)
149
+ return answer(400, { ok: false, error: "Name the task and its build." });
150
+ const found = takeOverOf(taskField, Number(runField));
151
+ if (typeof found === "string")
152
+ return answer(404, { ok: false, error: found });
153
+ from = { revision: found.revision, task: taskField, run: Number(runField) };
154
+ repo = found.repo;
155
+ }
156
+ else
157
+ repo = body.get("repo") ?? "";
91
158
  if (!runtime.consoleProjects().includes(repo) || !projectAllowed(who.name, repo))
92
- return json(ctx, 403, { ok: false, error: "Choose a project available to your account." });
159
+ return answer(403, { ok: false, error: "Choose a project available to your account." });
93
160
  if (program !== "shell") {
94
161
  const stopped = store.sessionPolicyRefusal(program, null, "live terminals");
95
162
  if (stopped !== null)
96
- return json(ctx, 403, { ok: false, error: stopped });
163
+ return answer(403, { ok: false, error: stopped });
97
164
  }
98
- if (!runtime.authenticateApprover(who, body.get("password") ?? "").ok)
99
- return json(ctx, 403, { ok: false, error: "Enter your Toolroll password to start a terminal." });
165
+ const proved = runtime.authenticateApprover(who, body.get("password") ?? "");
166
+ if (!proved.ok)
167
+ return answer(403, { ok: false, error: "Enter your Toolroll password to start a terminal." });
168
+ if ((proved.method === "local-owner") !== (who.authority !== "full"))
169
+ return answer(403, { ok: false, error: "Your access changed. Sign in again." });
100
170
  const stillAllowed = () => {
101
171
  const again = rereadBrowser(runtime, ctx.request, who);
102
172
  if (again === null || operatorOf(again) === null)
103
173
  return "Your access changed. Sign in again.";
104
- return projectAllowed(who.name, repo) && runtime.consoleProjects().includes(repo) ? null : "That project is no longer available to your account.";
174
+ if (proved.method === "session" && !sessionStandsIn(store))
175
+ return "This install's sign-in rules changed. Enter your Toolroll password to start a terminal.";
176
+ if (proved.method === "local-owner" && (again.authority !== "local-owner" || again.session.localGeneration !== who.session.localGeneration))
177
+ return "Your access changed. Sign in again.";
178
+ if (!projectAllowed(who.name, repo) || !runtime.consoleProjects().includes(repo))
179
+ return "That project is no longer available to your account.";
180
+ if (from !== null) {
181
+ const now = takeOverOf(from.task, from.run);
182
+ if (typeof now === "string" || now.repo !== repo || now.revision !== from.revision)
183
+ return "This build changed. Look again.";
184
+ }
185
+ return null;
105
186
  };
106
187
  try {
107
- const terminal = await deps.host.start({ name: who.name, generation: who.session.generation }, repo, program, undefined, stillAllowed);
188
+ const owner = { name: who.name, generation: who.session.generation, localGeneration: who.authority === "full" ? null : who.session.localGeneration };
189
+ const terminal = await deps.host.start(owner, repo, program, undefined, stillAllowed, from);
108
190
  const after = stillAllowed();
109
191
  if (after !== null) {
110
192
  await deps.host.close(terminal.id);
111
193
  await deps.host.remove(terminal.id).catch(() => { });
112
- return json(ctx, 403, { ok: false, error: after });
194
+ return answer(403, { ok: false, error: after });
113
195
  }
114
196
  record("start", who.name, terminal);
115
- return json(ctx, 200, { ok: true, id: terminal.id });
197
+ return answer(200, { ok: true, id: terminal.id });
116
198
  }
117
199
  catch (error) {
118
- return json(ctx, 409, { ok: false, error: error instanceof TerminalError ? error.message : "The terminal didn't start." });
200
+ return answer(409, { ok: false, error: error instanceof TerminalError ? error.message : "The terminal didn't start." });
119
201
  }
120
202
  }
203
+ const agentStart = (kind) => async (ctx) => {
204
+ const answer = (status, value) => checked(ctx, status, "termStarted", value);
205
+ const refused = refusal(ctx);
206
+ if (refused !== null)
207
+ return answer(403, { ok: false, error: refused });
208
+ const who = ctx.who;
209
+ if (!workbenchNow(ctx.request, who))
210
+ return answer(403, { ok: false, error: WORKBENCH_ONLY });
211
+ const body = readForm(ctx.posted, CONSOLE_FORMS.termAgent);
212
+ if ([...new Set(body.keys())].some(key => body.sent.getAll(key).length !== 1))
213
+ return answer(400, { ok: false, error: "Submit one value for each field." });
214
+ const agentId = body.get("agent") ?? "";
215
+ const setup = agentSetupOf(agentId);
216
+ if (setup === null)
217
+ return answer(400, { ok: false, error: "Choose an agent Toolroll supports." });
218
+ const run = kind === "sign-in" ? setup.signInRun : setup.installRun;
219
+ const shown = kind === "sign-in" ? setup.signIn : setup.install;
220
+ if (run === null || shown === null)
221
+ return answer(409, { ok: false, error: kind === "sign-in" ? "This agent signs in another way: its screen says how." : "Toolroll doesn't run this agent's installer: run the command shown in your own terminal." });
222
+ if (kind === "install" && body.get("confirm") !== shown)
223
+ return answer(409, { ok: false, error: "Confirm the exact install command first." });
224
+ if (agentId === "claude" || agentId === "codex") {
225
+ const stopped = store.sessionPolicyRefusal(agentId, null, "live terminals");
226
+ if (stopped !== null)
227
+ return answer(403, { ok: false, error: stopped });
228
+ }
229
+ const proved = runtime.authenticateApprover(who, body.get("password") ?? "");
230
+ if (!proved.ok)
231
+ return answer(403, { ok: false, error: "Enter your Toolroll password to start a terminal." });
232
+ if ((proved.method === "local-owner") !== (who.authority !== "full"))
233
+ return answer(403, { ok: false, error: "Your access changed. Sign in again." });
234
+ const source = (deps.agentEnv ?? (() => process.env))();
235
+ const untrusted = await excludedFolders({ store });
236
+ if (untrusted === null)
237
+ return answer(409, { ok: false, error: "Toolroll couldn't read its own records, so it won't start a program." });
238
+ const trust = { path: source["PATH"] ?? "", uid: process.getuid?.(), untrusted, acl: boundedAcl(Date.now() + 3_000) };
239
+ const program = run.binary;
240
+ const found = resolveLaunch(program, trust);
241
+ if (!found.ok)
242
+ return answer(409, { ok: false, error: found.missing ? `\`${program}\` isn't installed on this computer.` : `Toolroll won't run \`${program}\`: ${found.why}.` });
243
+ const env = { ...statusEnvironment(source, trust), PATH: launchPath(found, trust) };
244
+ const stillAllowed = () => {
245
+ const again = rereadBrowser(runtime, ctx.request, who);
246
+ if (again === null || operatorOf(again) === null)
247
+ return "Your access changed. Sign in again.";
248
+ if (proved.method === "session" && !sessionStandsIn(store))
249
+ return "This install's sign-in rules changed. Enter your Toolroll password to start a terminal.";
250
+ if (proved.method === "local-owner" && (again.authority !== "local-owner" || again.session.localGeneration !== who.session.localGeneration))
251
+ return "Your access changed. Sign in again.";
252
+ if (!workbenchNow(ctx.request, again))
253
+ return WORKBENCH_ONLY;
254
+ const now = resolveLaunch(program, { ...trust, acl: boundedAcl(Date.now() + 3_000) });
255
+ if (!now.ok || now.real !== found.real || now.file !== found.file)
256
+ return `\`${program}\` changed while it was being checked. Try again.`;
257
+ return null;
258
+ };
259
+ try {
260
+ const owner = { name: who.name, generation: who.session.generation, localGeneration: who.authority === "full" ? null : who.session.localGeneration };
261
+ const terminal = await deps.host.startCommand(owner, { id: agentId, kind }, { file: found.file, args: [...found.args, ...run.args] }, env, undefined, stillAllowed, () => { void runtime.checkLocalAgents(true); });
262
+ record(`agent-${kind}`, who.name, terminal);
263
+ return answer(200, { ok: true, id: terminal.id });
264
+ }
265
+ catch (error) {
266
+ return answer(409, { ok: false, error: error instanceof TerminalError ? error.message : "The terminal didn't start." });
267
+ }
268
+ };
121
269
  const act = (verb) => async (ctx) => {
122
270
  const refused = refusal(ctx);
123
271
  if (refused !== null)
124
272
  return json(ctx, 403, { ok: false, error: refused });
125
273
  const who = ctx.who;
126
274
  const terminal = deps.host.get(TERMINAL_ID.exec(ctx.url.pathname)?.[1] ?? "");
127
- if (!owned(who, terminal) || !projectAllowed(who.name, terminal.repo))
275
+ if (!reachable(who, terminal, ctx.request))
128
276
  return json(ctx, 404, { ok: false, error: "No such terminal." });
129
277
  try {
130
278
  if (verb === "close")
@@ -207,7 +355,7 @@ export function createTerminalHandlers(runtime, deps) {
207
355
  return true;
208
356
  }
209
357
  const terminal = deps.host?.get(id) ?? null;
210
- if (!owned(who, terminal) || !projectAllowed(who.name, terminal.repo)) {
358
+ if (!reachable(who, terminal, request)) {
211
359
  refuseUpgrade(socket, 404, "No such terminal.");
212
360
  return true;
213
361
  }
@@ -239,7 +387,7 @@ export function createTerminalHandlers(runtime, deps) {
239
387
  };
240
388
  const prove = () => {
241
389
  const again = rereadBrowser(runtime, request, who);
242
- const ok = again !== null && operatorOf(again) !== null && owned(who, host.get(terminal.id)) && projectAllowed(who.name, terminal.repo);
390
+ const ok = again !== null && operatorOf(again) !== null && reachable(again, host.get(terminal.id), request);
243
391
  if (ok)
244
392
  provedAt = Date.now();
245
393
  return ok;
@@ -264,6 +412,8 @@ export function createTerminalHandlers(runtime, deps) {
264
412
  return shut(4401, "signed out");
265
413
  ws.send(JSON.stringify(message));
266
414
  },
415
+ backlog: () => closed ? 0 : ws.bufferedAmount,
416
+ overflow: () => shut(4008, "fell behind"),
267
417
  };
268
418
  ws.on("message", (data, isBinary) => {
269
419
  if (closed)
@@ -301,6 +451,7 @@ export function createTerminalHandlers(runtime, deps) {
301
451
  reprovers.add(reprove);
302
452
  record("attach", who.name, terminal);
303
453
  }
454
+ deps.host?.alsoBuildWritable?.(runtime.consoleProjects);
304
455
  deps.server.on("upgrade", (request, socket, head) => {
305
456
  if (!upgrade(request, socket, head))
306
457
  socket.destroy();
@@ -311,6 +462,8 @@ export function createTerminalHandlers(runtime, deps) {
311
462
  "term.session": async (ctx) => page(ctx),
312
463
  "term.state": state,
313
464
  "term.start": start,
465
+ "term.agent-sign-in": agentStart("sign-in"),
466
+ "term.agent-install": agentStart("install"),
314
467
  "term.close": act("close"),
315
468
  "term.remove": act("remove"),
316
469
  "term.socket": socketWithoutUpgrade,
@@ -5,6 +5,7 @@ import { firstTaskSuggestions, SAMPLE_FIRST_TASKS, SAMPLE_PROJECT_NAME, welcomeM
5
5
  import { html, joinHtml, postForm } from "../html.js";
6
6
  import { START_BUILDER_HREF } from "../needs-you.js";
7
7
  import { addSampleProject } from "../sample-project.js";
8
+ import { firstTaskRouted } from "../welcome-facts.js";
8
9
  import { resolveCeiling } from "../project.js";
9
10
  import { readProjectRegistryNow } from "../repos.js";
10
11
  import { refuse, screen } from "./chrome.js";
@@ -12,6 +13,7 @@ import { handlersOf } from "./handler-registry.js";
12
13
  import { redirect } from "./http.js";
13
14
  import { rereadBrowser } from "./live.js";
14
15
  import { btn, chip, codeLine, dock, note, notice, pageHeader, settingsRecord } from "./kit.js";
16
+ import { NO_AGENT_YET } from "../agent-detect.js";
15
17
  export const SAMPLE_PROBLEMS = {
16
18
  "no-root": "There's no project folder to put the sample in. Add a folder instead.",
17
19
  exists: `A folder named ${SAMPLE_PROJECT_NAME} is already there and wasn't made here, so nothing was changed.`,
@@ -24,9 +26,9 @@ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
24
26
  const AGENT_WORDS = { "signed-in": "Signed in", "signed-out": "Not signed in", "not-installed": "Not installed", checking: "Checking…" };
25
27
  const PROJECTS_SHOWN = 3;
26
28
  const ADD_FOLDER = "/projects?return=%2Fwelcome";
27
- function step(key, index, title, done, body) {
29
+ function step(key, index, title, done, body, filed = false) {
28
30
  return html `<section class="k-sec welcome-step" id="welcome-${key}" data-step="${key}" data-done="${done ? "1" : "0"}" aria-labelledby="welcome-${key}-h">\
29
- <div class="k-secthead"><h3 id="welcome-${key}-h">${index}. ${title}</h3>${done ? chip("Done", "done") : ""}</div>${body}</section>`;
31
+ <div class="k-secthead"><h3 id="welcome-${key}-h">${index}. ${title}</h3>${filed ? chip("Filed", "", { dot: false }) : done ? chip("Done", "done") : ""}</div>${body}</section>`;
30
32
  }
31
33
  const useForm = (agent, button) => postForm("/settings/lead/on", button, { hidden: { agent, return: "/welcome" } });
32
34
  function agentRow(agent, leads) {
@@ -37,17 +39,33 @@ function agentRow(agent, leads) {
37
39
  : "";
38
40
  return settingsRecord({ title: agent.name, sub, action, attrs: { "data-agent": agent.id, "data-state": agent.state } });
39
41
  }
42
+ const OTHER_WORDS = { "signed-in": "Signed in", "signed-out": "Not signed in", unknown: "Installed", "not-installed": "Not installed" };
43
+ const withCode = (text) => joinHtml(text.split("`").map((part, index) => index % 2 === 1 ? html `<code class="k-mono">${part}</code>` : html `${part}`));
44
+ function otherRow(agent) {
45
+ const sub = agent.state !== "signed-in" && agent.signIn !== null
46
+ ? html `${OTHER_WORDS[agent.state]}. To sign in, run this on the computer running Toolroll:${codeLine(agent.signIn)}`
47
+ : agent.next !== null ? html `${OTHER_WORDS[agent.state]}. ${withCode(agent.next)}` : OTHER_WORDS[agent.state];
48
+ return settingsRecord({ title: agent.name, sub, action: "", attrs: { "data-agent": agent.id, "data-state": agent.state } });
49
+ }
40
50
  export function welcomeBody(model, options) {
41
- const lead = model.next;
42
51
  let primary = null;
43
- const agentLead = lead === "agent" ? model.agent.agents.find(one => one.canUse) ?? null : null;
52
+ const inventory = options.inventory ?? "full";
53
+ const blind = inventory === "none";
54
+ const agentDone = blind ? false : model.agent.done;
55
+ const lead = !blind || model.next !== "agent" ? model.next : !model.project.done ? "project" : !model.task.done ? "task" : null;
56
+ const left = blind ? [false, model.project.done, model.task.done].filter(done => !done).length : model.left;
57
+ const agentLead = lead === "agent" && inventory === "full" ? model.agent.agents.find(one => one.canUse) ?? null : null;
44
58
  if (agentLead !== null)
45
59
  primary = useForm(agentLead.id, btn(`Use ${agentLead.name}`, { variant: "primary", type: "submit" }));
46
- const agentNote = model.agent.checking ? note("Checking for a signed-in agent on this computer…")
47
- : !model.agent.done ? note("Sign in to one of these, then come back to this page.")
48
- : model.agent.buildsWith !== null ? note(html `Tasks are built with ${model.agent.buildsWith}. <a class="k-link" href="/settings/models">Change</a>`) : "";
49
- const agent = step("agent", 1, "Agent", model.agent.done, html `<p class="k-note">The AI coding agent that plans and builds your tasks.</p>\
50
- <div class="welcome-rows">${model.agent.agents.map(one => agentRow(one, agentLead?.id === one.id))}</div>${agentNote}`);
60
+ const firstTaskNote = model.agent.firstTask !== null ? note(`Your first task goes to ${model.agent.firstTask}.`) : "";
61
+ const agentNote = inventory === "none" ? ""
62
+ : inventory === "summary" ? model.agent.firstTask !== null ? firstTaskNote : note(model.agent.checking ? "Checking for a signed-in agent on this computer…" : NO_AGENT_YET)
63
+ : model.agent.checking ? note("Checking for a signed-in agent on this computer…")
64
+ : !model.agent.done ? note("Sign in to one of these, then come back to this page.")
65
+ : model.agent.buildsWith !== null ? note(html `Tasks are built with ${model.agent.buildsWith}. <a class="k-link" href="/settings/models">Change</a>`)
66
+ : firstTaskNote;
67
+ const rows = inventory !== "full" ? "" : html `<div class="welcome-rows">${model.agent.agents.map(one => agentRow(one, agentLead?.id === one.id))}${model.agent.others.map(otherRow)}</div>`;
68
+ const agent = step("agent", 1, "Agent", agentDone, html `<p class="k-note">The AI coding agent that plans and builds your tasks.</p>${rows}${agentNote}`);
51
69
  const projects = model.project.projects;
52
70
  const listed = projects.slice(0, PROJECTS_SHOWN).map(one => settingsRecord({ title: one.name, sub: html `<span class="k-mono">${one.path}</span>`, attrs: { "data-project": "" } }));
53
71
  const more = projects.length > PROJECTS_SHOWN ? note(html `And ${plural(projects.length - PROJECTS_SHOWN, "more project", "more projects")} in <a class="k-link" href="/projects">Projects</a>.`) : "";
@@ -75,16 +93,22 @@ ${listed.length === 0 ? "" : html `<div class="welcome-rows">${listed}</div>`}${
75
93
  const taskLeads = lead === "task";
76
94
  if (taskLeads)
77
95
  primary = btn("Write a task", { variant: "primary", href: "/tasks/new" });
78
- const taskBody = model.task.done ? !model.agent.done && !model.agent.checking ? html `<p class="k-note">Filed. It starts by itself once an agent is signed in (step 1).</p>`
79
- : html `<p class="k-note">Filed. Its plan waits for your approval in <a class="k-link" href="/tasks">Tasks</a>.</p>`
96
+ const waitsForAgent = !blind && model.task.done && !model.agent.done && !model.agent.checking;
97
+ const taskBody = model.task.done ? waitsForAgent ? html `<p class="k-note">It starts by itself once an agent is signed in (step 1).</p>`
98
+ : html `<p class="k-note">Filed. Its plan waits for your approval in <a class="k-link" href="/">Work</a>.</p>`
80
99
  : !model.task.open ? html `<p class="k-note">Add a project first.</p>`
81
100
  : html `<p class="k-note">Describe a change in a sentence or two. Nothing starts until you approve its plan.</p>\
82
101
  ${model.task.starters.length === 0 ? "" : html `<div class="k-ideas" aria-label="Ideas to start from" data-starters>${model.task.starters.map(one => html `<a class="k-btn k-btn-outline k-idea" href="${one.href}">${one.label}</a>`)}</div>`}\
83
102
  <div class="k-acts">${btn("Write a task", { sm: true, href: "/tasks/new", ...(taskLeads ? { variant: "primary", docked: true } : {}) })}</div>`;
84
- const task = step("task", 3, "First task", model.task.done, taskBody);
85
- const hello = html `<div class="k-hello"><h2>Get to your first result.</h2><p>${model.left === 0 ? "Setup is done." : `${plural(model.left, "step", "steps")} left.`}</p></div>`;
103
+ const task = step("task", 3, "First task", model.task.done, taskBody, waitsForAgent);
104
+ const hello = html `<div class="k-hello"><h2>Get to your first result.</h2><p>${left === 0 ? "Setup is done." : `${plural(left, "step", "steps")} left.`}</p></div>`;
86
105
  return { body: html `${hello}${agent}${project}${task}`, primary };
87
106
  }
107
+ export function agentInventoryOf(who, store) {
108
+ if (who.via !== "cookie")
109
+ return "none";
110
+ return store.isInstanceOperator(who.name) ? "full" : "summary";
111
+ }
88
112
  export function welcomePage(chrome, model, options) {
89
113
  const { body, primary } = welcomeBody(model, options);
90
114
  return screen("Welcome", html `${pageHeader("Welcome")}<div class="k-doc welcome" data-welcome>${body}</div>${dock(primary)}`, { chrome });
@@ -106,8 +130,10 @@ export function createWelcomeHandlers(runtime) {
106
130
  const states = runtime.localSignIn?.states ?? null;
107
131
  const build = resolvePhaseAgent(store, "build", repo, {});
108
132
  const approver = who.via === "cookie" && who.role === "approver";
133
+ const routed = firstTaskRouted(store, repo);
109
134
  const model = welcomeModel({
110
135
  agents: { claude: states?.claude ?? null, codex: states?.codex ?? null },
136
+ others: runtime.localAgents?.agents ?? null, routed,
111
137
  inUse: AGENT_OF[store.getChatConfig()?.provider ?? ""] ?? null,
112
138
  buildsOn: build.ok ? build.spec.provider : null,
113
139
  canChoose: approver,
@@ -117,7 +143,7 @@ export function createWelcomeHandlers(runtime) {
117
143
  starters, platform: options.platform ?? process.platform,
118
144
  });
119
145
  const asked = url.searchParams.get("sample");
120
- return sendScreen(response, 200, welcomePage(chrome, model, { problem: isSampleProblem(asked) ? asked : null, canAdd: approver && !store.isDemo() }));
146
+ return sendScreen(response, 200, welcomePage(chrome, model, { problem: isSampleProblem(asked) ? asked : null, canAdd: approver && !store.isDemo(), inventory: agentInventoryOf(who, store) }));
121
147
  }
122
148
  async function addSample(ctx) {
123
149
  const { who, response, now, posted, request } = ctx;