toolroll 0.9.109 → 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 (135) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/agent-detect.js +244 -0
  3. package/dist/agent-fence.js +12 -1
  4. package/dist/agentconfig.js +2 -2
  5. package/dist/approval-summary.js +344 -0
  6. package/dist/attest.js +2 -2
  7. package/dist/browser/workspace.css +2 -2
  8. package/dist/browser/workspace.js +27 -27
  9. package/dist/builder.js +36 -2
  10. package/dist/chat-actions.js +24 -17
  11. package/dist/chat-core.js +3 -1
  12. package/dist/chat-decide.js +101 -46
  13. package/dist/chat-delivery-state.js +2 -0
  14. package/dist/chat-delivery.js +3 -2
  15. package/dist/chat-live.js +2 -1
  16. package/dist/chat-task-actions.js +6 -0
  17. package/dist/check-report.js +1 -1
  18. package/dist/cli.js +2 -0
  19. package/dist/console-instance.js +10 -1
  20. package/dist/contracts/console-api.js +10 -5
  21. package/dist/contracts/engine-api.js +271 -0
  22. package/dist/coordinator.js +2 -2
  23. package/dist/discord-api.js +4 -3
  24. package/dist/discord-chat.js +3 -1
  25. package/dist/easy-start-args.js +7 -3
  26. package/dist/easy-start.js +25 -0
  27. package/dist/egress.js +72 -10
  28. package/dist/engine-handoff.js +34 -0
  29. package/dist/engine-reads.js +261 -0
  30. package/dist/eval-world.js +3 -2
  31. package/dist/evidence.js +2 -0
  32. package/dist/fast-start.js +55 -14
  33. package/dist/fast-terms.js +2 -2
  34. package/dist/first-run.js +10 -2
  35. package/dist/flexible-agents.js +234 -0
  36. package/dist/flexible-answers-schema.js +61 -0
  37. package/dist/flexible-answers.js +889 -0
  38. package/dist/flexible-custody.js +494 -0
  39. package/dist/flexible-import.js +782 -0
  40. package/dist/flexible-launch-schema.js +72 -0
  41. package/dist/flexible-launch.js +331 -0
  42. package/dist/flexible-launcher.js +88 -0
  43. package/dist/flexible-levels.js +34 -0
  44. package/dist/flexible-merge-guard.js +47 -0
  45. package/dist/flexible-refs.js +47 -0
  46. package/dist/flexible-relay-cancel.js +19 -0
  47. package/dist/flexible-relay-schema.js +55 -0
  48. package/dist/flexible-relay-upstreams.js +36 -0
  49. package/dist/flexible-relay.js +1032 -0
  50. package/dist/flexible-session.js +732 -0
  51. package/dist/flexible-ship-schema.js +81 -0
  52. package/dist/flexible-ship.js +694 -0
  53. package/dist/flexible-start.js +80 -0
  54. package/dist/flexible-thread.js +175 -25
  55. package/dist/flexible-turns-schema.js +69 -0
  56. package/dist/flexible-turns.js +490 -0
  57. package/dist/flexible.js +10 -1
  58. package/dist/flow-actions.js +6 -4
  59. package/dist/flow-steps.js +1 -1
  60. package/dist/flows-cli.js +2 -1
  61. package/dist/git-views.js +6 -3
  62. package/dist/install-mode.js +225 -0
  63. package/dist/lead-doors.js +7 -1
  64. package/dist/limits-ui.js +7 -0
  65. package/dist/live-reply.js +6 -0
  66. package/dist/live-terminal.js +425 -29
  67. package/dist/local-owner.js +6 -0
  68. package/dist/model-choices.js +12 -6
  69. package/dist/notification-delivery.js +11 -0
  70. package/dist/operate.js +74 -30
  71. package/dist/outbound-privacy.js +204 -0
  72. package/dist/passwordless.js +2 -1
  73. package/dist/project-delete.js +14 -0
  74. package/dist/provider-connection.js +5 -3
  75. package/dist/publish.js +5 -0
  76. package/dist/pull-request-flow.js +26 -7
  77. package/dist/push.js +5 -1
  78. package/dist/release-card.js +11 -3
  79. package/dist/release.js +10 -1
  80. package/dist/route-store.js +2 -2
  81. package/dist/sandbox-launch.js +32 -8
  82. package/dist/sandbox-runtime.js +16 -7
  83. package/dist/sandbox-tools.js +176 -0
  84. package/dist/scope.js +12 -36
  85. package/dist/scout-net.js +7 -2
  86. package/dist/serve.js +58 -11
  87. package/dist/server/chrome.js +3 -1
  88. package/dist/server/console.css +33 -6
  89. package/dist/server/engine-api.js +378 -0
  90. package/dist/server/flows.js +2 -2
  91. package/dist/server/http.js +7 -0
  92. package/dist/server/link-redemption.js +52 -0
  93. package/dist/server/mutation-key.js +21 -7
  94. package/dist/server/pages.js +69 -40
  95. package/dist/server/people-tokens.js +17 -41
  96. package/dist/server/render-chat.js +1 -0
  97. package/dist/server/render-new-task.js +3 -3
  98. package/dist/server/render-results.js +4 -4
  99. package/dist/server/render-tasks.js +129 -138
  100. package/dist/server/route-table.js +30 -1
  101. package/dist/server/settings-section-table.js +3 -0
  102. package/dist/server/settings-sections.js +33 -0
  103. package/dist/server/settings.js +84 -10
  104. package/dist/server/task-views.js +8 -2
  105. package/dist/server/tasks.js +25 -8
  106. package/dist/server/terminals.js +181 -28
  107. package/dist/server/welcome.js +35 -10
  108. package/dist/settings-groups-ui.js +2 -2
  109. package/dist/settings-proofs.js +13 -9
  110. package/dist/slack-api.js +4 -3
  111. package/dist/slack-chat.js +5 -3
  112. package/dist/spend.js +46 -12
  113. package/dist/status-probe.js +343 -0
  114. package/dist/store.js +102 -5
  115. package/dist/teams-api.js +4 -3
  116. package/dist/teams-chat.js +4 -2
  117. package/dist/telegram-lead.js +2 -1
  118. package/dist/telegram-live.js +2 -1
  119. package/dist/telegram-team.js +2 -1
  120. package/dist/telegram.js +17 -5
  121. package/dist/trusted-path.js +162 -0
  122. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  123. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  124. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  125. package/dist/tui/linux-x64/toolroll-tui +0 -0
  126. package/dist/tui-launch.js +282 -0
  127. package/dist/tui-source.js +5 -3
  128. package/dist/tui.js +1 -1
  129. package/dist/webhooks.js +8 -4
  130. package/dist/welcome-facts.js +22 -15
  131. package/dist/workspace-ui.js +5 -0
  132. package/package.json +1 -1
  133. package/scripts/crash-canary.mjs +1 -1
  134. package/scripts/pilot.mjs +1 -1
  135. package/scripts/provider-canary.mjs +5 -3
@@ -0,0 +1,378 @@
1
+ import { homedir } from "node:os";
2
+ import { randomBytes } from "node:crypto";
3
+ import { boardRunOf } from "../agent-board.js";
4
+ import { checkEngineResponse, DIFF_CONTEXT_MAX, ENGINE_API_VERSION, ENGINE_RESPONSES, engineContractDigest, linkRedemptionRequestSchema } from "../contracts/engine-api.js";
5
+ import { CONSOLE_FORMS, readForm } from "../contracts/console-api.js";
6
+ import { FLEXIBLE_AVAILABLE } from "../flexible-available.js";
7
+ import { FLEXIBLE_UNAVAILABLE } from "../flexible.js";
8
+ import { admitFlexibleThreadOwner, answerFlexibleRequest, closeFlexibleSessions, flexibleThreadChangeOf, flexibleThreadLiveOf, flexibleThreadsOf, FLEXIBLE_WAIT_MS, openFlexibleSessions, recoverFlexibleHolders, startFlexibleThread, tickFlexibleSessions, waitFlexibleThreadChange } from "../flexible-session.js";
9
+ import { createFlexibleLauncher } from "../flexible-launcher.js";
10
+ import { flexibleStartCard } from "../flexible-start.js";
11
+ import { summaryLines } from "../approval-summary.js";
12
+ import { localActNow } from "../local-owner.js";
13
+ import { authenticateApprover } from "../scope.js";
14
+ import { defaultChainOf, installModeNow } from "../install-mode.js";
15
+ import { packageVersion } from "../monitoring.js";
16
+ import { readChildWindow } from "../live-children-read.js";
17
+ import { readMainWindow } from "../live-main-read.js";
18
+ import { runLiveCommands } from "../store.js";
19
+ import { agentsReadOf, resultDiffContextOf, resultDiffFileOf, resultDiffOf, resultRunsOf, stepCardsOf } from "../engine-reads.js";
20
+ import { handlersOf } from "./handler-registry.js";
21
+ import { matchTaskPath, respond } from "./http.js";
22
+ import { rereadBrowser } from "./live.js";
23
+ import { admitLink, saveLinkSession, spendLink } from "./link-redemption.js";
24
+ import { agentInventoryOf } from "./welcome.js";
25
+ import { SESSION_COOKIE, sessionWithinLifetime } from "./session.js";
26
+ const json = (response, status, value) => respond(response, status, "application/json", JSON.stringify(value));
27
+ const sendChecked = (response, status, name, value) => json(response, status, checkEngineResponse(name, value));
28
+ const refusal = (response, status, error) => sendChecked(response, status, "refusal", { error });
29
+ export function readRunLive(runtime, request, who, runId, file, cursor, key) {
30
+ const { store, options } = runtime;
31
+ const allowed = () => {
32
+ if (rereadBrowser(runtime, request, who) === null)
33
+ return false;
34
+ const run = store.getRun(runId);
35
+ const repo = run === null ? null : runtime.taskRepoOf(run.taskRef);
36
+ return run !== null && repo !== null && runtime.runVisible(run) && store.accountCanAccess(who.name, repo);
37
+ };
38
+ if (!allowed())
39
+ return { ok: false };
40
+ const local = () => options.localRunner !== undefined && store.getRun(runId)?.runner === options.localRunner;
41
+ if (!local())
42
+ return allowed() ? { ok: true, run: store.getRun(runId), window: null } : { ok: false };
43
+ const read = { key, commands: runLiveCommands(store, runId) };
44
+ const window = file === "sub" ? readChildWindow(runtime.evidenceRoot, runId, cursor, read) : readMainWindow(runtime.evidenceRoot, runId, cursor, read);
45
+ if (!allowed() || !local())
46
+ return { ok: false };
47
+ return { ok: true, run: store.getRun(runId), window };
48
+ }
49
+ export function liveQueryOf(url) {
50
+ const file = url.searchParams.get("file") ?? "main";
51
+ if ((file !== "main" && file !== "sub") || [...url.searchParams.keys()].some(key => key !== "file" && key !== "cursor")
52
+ || url.searchParams.getAll("file").length > 1 || url.searchParams.getAll("cursor").length > 1)
53
+ return null;
54
+ return { file, cursor: url.searchParams.get("cursor") };
55
+ }
56
+ export function createEngineHandlers(runtime) {
57
+ const { store, clock, evidenceRoot } = runtime;
58
+ const cursorKey = randomBytes(32);
59
+ let contract = null;
60
+ async function hello(ctx) {
61
+ const { url, response } = ctx;
62
+ if ([...url.searchParams.keys()].length > 0)
63
+ return refusal(response, 400, "request");
64
+ contract ??= engineContractDigest();
65
+ const mode = installModeNow(store).mode;
66
+ return sendChecked(response, 200, "hello", { version: ENGINE_API_VERSION, toolroll: packageVersion(), contract, responses: Object.keys(ENGINE_RESPONSES), mode, defaultChain: defaultChainOf(mode) });
67
+ }
68
+ async function agents(ctx) {
69
+ const { url, who, response } = ctx;
70
+ if (who.via !== "cookie")
71
+ return refusal(response, 403, "session");
72
+ if ([...url.searchParams.keys()].length > 0)
73
+ return refusal(response, 400, "request");
74
+ const view = agentInventoryOf(who, store);
75
+ return sendChecked(response, 200, "agents", agentsReadOf(runtime.localAgents, view === "full" ? "full" : "summary", view === "full" ? process.env["HOME"] ?? homedir() : null));
76
+ }
77
+ async function agentsCheck(ctx) {
78
+ const { who, response } = ctx;
79
+ if (who.via !== "cookie")
80
+ return refusal(response, 403, "session");
81
+ if (Date.now() - runtime.leadRecheckedAt > 4_000) {
82
+ runtime.leadRecheckedAt = Date.now();
83
+ let timer;
84
+ await Promise.race([runtime.checkLocalAgents(true), new Promise(done => { timer = setTimeout(done, 8_000); timer.unref?.(); })]).finally(() => clearTimeout(timer));
85
+ }
86
+ const view = agentInventoryOf(who, store);
87
+ return sendChecked(response, 200, "agents", agentsReadOf(runtime.localAgents, view === "full" ? "full" : "summary", view === "full" ? process.env["HOME"] ?? homedir() : null));
88
+ }
89
+ async function liveRun(ctx) {
90
+ const { url, who, request, response } = ctx;
91
+ if (who.via !== "cookie")
92
+ return refusal(response, 403, "session");
93
+ const query = liveQueryOf(url);
94
+ if (query === null)
95
+ return refusal(response, 400, "request");
96
+ const runId = Number(url.pathname.slice("/agents/live/run/".length));
97
+ const read = readRunLive(runtime, request, who, runId, query.file, query.cursor, cursorKey);
98
+ if (!read.ok)
99
+ return refusal(response, 404, "run");
100
+ const ref = store.refForId(read.run.taskRef);
101
+ const body = {
102
+ version: ENGINE_API_VERSION,
103
+ session: { kind: "run", id: read.run.id, task: ref !== null && ref.backend === "built-in" ? ref.externalId : null },
104
+ room: `agent:${boardRunOf(store, read.run.id)}`,
105
+ live: read.run.finishedAt === null,
106
+ file: query.file,
107
+ window: read.window === null ? { ok: false, reason: "off" } : read.window.ok
108
+ ? { ok: true, records: read.window.records, cursor: read.window.cursor, restarted: read.window.restarted, earlier: read.window.earlier,
109
+ quarantined: read.window.quarantined, skipped: read.window.skipped, more: read.window.more }
110
+ : { ok: false, reason: read.window.reason },
111
+ };
112
+ return sendChecked(response, 200, "liveSessionWindow", body);
113
+ }
114
+ const flexible = (() => {
115
+ if (!FLEXIBLE_AVAILABLE)
116
+ return null;
117
+ const opened = openFlexibleSessions(store);
118
+ if (!opened.ok)
119
+ return null;
120
+ void recoverFlexibleHolders(store, opened.sessions).catch(() => { });
121
+ return opened.sessions;
122
+ })();
123
+ const launcher = (() => {
124
+ if (!FLEXIBLE_AVAILABLE || flexible === null)
125
+ return null;
126
+ const made = createFlexibleLauncher(store);
127
+ return "prepare" in made ? made : null;
128
+ })();
129
+ const ownedThread = (request, who, sessions, thread) => {
130
+ if (rereadBrowser(runtime, request, who) === null)
131
+ return null;
132
+ const admitted = admitFlexibleThreadOwner(store, sessions, { thread, viewer: { name: who.name }, canAccess: repo => store.accountCanAccess(who.name, repo) });
133
+ return admitted.ok ? admitted.repo : null;
134
+ };
135
+ const acted = (response, status, outcome, words) => json(response, status, { outcome, words });
136
+ async function liveThread(ctx) {
137
+ const { url, who, request, response } = ctx;
138
+ if (who.via !== "cookie")
139
+ return refusal(response, 403, "session");
140
+ if (!FLEXIBLE_AVAILABLE || flexible === null)
141
+ return refusal(response, 404, "not-available");
142
+ const known = url.searchParams.get("known"), wait = url.searchParams.get("wait");
143
+ const plain = new URL(url.href);
144
+ plain.searchParams.delete("known");
145
+ plain.searchParams.delete("wait");
146
+ const query = url.searchParams.getAll("known").length > 1 || (known !== null && !/^[0-9a-f]{16}$/.test(known))
147
+ || url.searchParams.getAll("wait").length > 1 || (wait !== null && (wait !== "1" || known === null || !url.searchParams.has("cursor"))) ? null : liveQueryOf(plain);
148
+ if (query === null)
149
+ return refusal(response, 400, "request");
150
+ const id = url.pathname.slice("/agents/live/thread/".length);
151
+ if (ownedThread(request, who, flexible, id) === null)
152
+ return refusal(response, 404, "thread");
153
+ const since = flexibleThreadChangeOf(flexible, { thread: id });
154
+ let read = flexibleThreadLiveOf(store, flexible, { thread: id, viewer: { name: who.name }, file: query.file, cursor: query.cursor });
155
+ if (!read.ok || ownedThread(request, who, flexible, id) === null)
156
+ return refusal(response, 404, "thread");
157
+ if (wait === "1" && since.ok && read.facts.version === known && read.window.ok && read.window.records.length === 0 && !read.window.restarted && !read.window.more) {
158
+ const waited = waitFlexibleThreadChange(flexible, { thread: id, since: since.change, ms: FLEXIBLE_WAIT_MS, abandoned: stop => { response.once("close", stop); } });
159
+ if ("then" in waited)
160
+ await waited;
161
+ if (response.destroyed || response.writableEnded)
162
+ return;
163
+ if (ownedThread(request, who, flexible, id) === null)
164
+ return refusal(response, 404, "thread");
165
+ read = flexibleThreadLiveOf(store, flexible, { thread: id, viewer: { name: who.name }, file: query.file, cursor: query.cursor });
166
+ if (!read.ok || ownedThread(request, who, flexible, id) === null)
167
+ return refusal(response, 404, "thread");
168
+ }
169
+ const body = { version: ENGINE_API_VERSION, session: { kind: "thread", id, task: null }, room: `thread:${id}`, live: read.live, file: query.file, window: read.window,
170
+ ...(known === read.facts.version ? {} : { thread: read.facts }) };
171
+ return sendChecked(response, 200, "liveSessionWindow", body);
172
+ }
173
+ async function liveThreads(ctx) {
174
+ const { url, who, request, response } = ctx;
175
+ if (who.via !== "cookie")
176
+ return refusal(response, 403, "session");
177
+ if (!FLEXIBLE_AVAILABLE || flexible === null)
178
+ return refusal(response, 404, "not-available");
179
+ if ([...url.searchParams.keys()].length > 0)
180
+ return refusal(response, 400, "request");
181
+ if (rereadBrowser(runtime, request, who) === null)
182
+ return refusal(response, 403, "session");
183
+ const read = flexibleThreadsOf(store, flexible, { owner: who.name });
184
+ if (!read.ok)
185
+ return refusal(response, 404, "not-available");
186
+ const body = { version: ENGINE_API_VERSION, threads: read.threads.filter(one => store.accountCanAccess(who.name, one.repo))
187
+ .map(one => ({ id: one.id, title: one.title, project: one.project, level: one.level, live: one.live, waiting: one.waiting, costUsd: one.turn?.costUsd ?? null })) };
188
+ return sendChecked(response, 200, "liveThreads", body);
189
+ }
190
+ async function threadAnswer(ctx) {
191
+ const { url, who, request, response, posted } = ctx;
192
+ if (!FLEXIBLE_AVAILABLE || flexible === null)
193
+ return acted(response, 404, "refused", FLEXIBLE_UNAVAILABLE);
194
+ if (who.via !== "cookie")
195
+ return acted(response, 403, "refused", "Only a person signed in here can answer an agent.");
196
+ const id = url.pathname.slice("/agents/live/thread/".length, -"/answer".length);
197
+ if (ownedThread(request, who, flexible, id) === null)
198
+ return acted(response, 404, "refused", "There's no such thread.");
199
+ const body = readForm(posted, CONSOLE_FORMS.threadAnswer);
200
+ const decision = body.get("decision"), question = body.get("question"), answer = body.get("answer");
201
+ const choice = decision === "accept" || decision === "decline" ? { decision } : question !== null && answer !== null && decision === null ? { question, answer } : null;
202
+ if (choice === null)
203
+ return acted(response, 400, "refused", "That answer isn't one Toolroll can read. Nothing was sent.");
204
+ const sessionHash = runtime.sessions.hashOf(who.session);
205
+ const admitted = sessionHash === null ? null : store.webSession(sessionHash);
206
+ if (admitted === null || admitted.account !== who.name)
207
+ return acted(response, 403, "refused", "Only a person signed in here can answer an agent.");
208
+ const held = () => {
209
+ const saved = store.webSession(admitted.idHash), account = store.accountOf(who.name);
210
+ return saved !== null && saved.idHash === admitted.idHash && saved.account === admitted.account && saved.generation === admitted.generation && saved.role === admitted.role
211
+ && saved.authority === admitted.authority && saved.localGeneration === admitted.localGeneration && saved.keyEpoch === admitted.keyEpoch && saved.keyHash === admitted.keyHash
212
+ && saved.createdAt === admitted.createdAt && sessionWithinLifetime(saved, Date.now()) && runtime.sessions.holds(who.session)
213
+ && account !== null && account.revokedAt === null && account.generation === saved.generation && account.generation === who.session.generation && account.role === saved.role
214
+ && admitFlexibleThreadOwner(store, flexible, { thread: id, viewer: { name: who.name }, canAccess: repo => store.accountCanAccess(who.name, repo) }).ok;
215
+ };
216
+ const done = await answerFlexibleRequest(store, flexible, { thread: id, request: body.get("request") ?? "", shownDigest: body.get("card") ?? "",
217
+ by: { kind: "person", name: who.name, generation: who.session.generation }, choice, held });
218
+ return done.ok ? acted(response, 200, "done", "Sent to the agent.") : acted(response, 409, "refused", done.message);
219
+ }
220
+ async function threadStart(ctx) {
221
+ const { who, request, response, posted } = ctx;
222
+ if (!FLEXIBLE_AVAILABLE || flexible === null)
223
+ return acted(response, 404, "refused", FLEXIBLE_UNAVAILABLE);
224
+ if (who.via !== "cookie" || rereadBrowser(runtime, request, who) === null)
225
+ return acted(response, 403, "refused", "Only a person signed in here can start a thread.");
226
+ if (launcher === null)
227
+ return acted(response, 409, "refused", "This console can't give a thread its network, so no thread was started.");
228
+ const body = readForm(posted, CONSOLE_FORMS.threadStart);
229
+ const repo = body.get("repo") ?? "", message = body.get("message") ?? "";
230
+ if (!store.accountCanAccess(who.name, repo))
231
+ return acted(response, 403, "refused", "That project is outside your access.");
232
+ const by = { name: who.name, generation: who.session.generation };
233
+ const made = flexibleStartCard(store, { repo, by, model: body.get("model"), message });
234
+ if (!made.ok)
235
+ return acted(response, 409, "refused", made.message);
236
+ const card = made.card;
237
+ const shown = body.get("terms");
238
+ if (shown === null || shown === "") {
239
+ const rows = [...card.summary.decisions, ...card.summary.differs].map(row => ({ label: row.label, words: row.words, lines: row.lines ?? [] }));
240
+ return json(response, 200, { outcome: "thread-terms", key: card.summary.key, terms: rows, notes: card.summary.warnings.map(note => note.words), lines: summaryLines(card.summary) });
241
+ }
242
+ if (shown !== card.summary.key)
243
+ return acted(response, 409, "refused", "The terms changed since they were shown. Read them again before starting. Nothing was started.");
244
+ const proved = authenticateApprover(store, who.name, body.get("password") ?? "", repo);
245
+ if (!proved.ok || !START_PROOFS.has(proved.method))
246
+ return acted(response, 403, "refused", "Starting a thread needs your password here. Nothing was started.");
247
+ if (proved.method === "local-owner" && localActNow(store, "start-thread") === null)
248
+ return acted(response, 403, "refused", "Starting a thread needs your password here. Nothing was started.");
249
+ const started = await startFlexibleThread(store, flexible, { repo, by, digest: card.digest, message, model: card.model, billing: card.billing, startKey: card.summary.key, launcher,
250
+ freshProof: FRESH_PROOFS.has(proved.method), expectNetwork: card.network });
251
+ if (!started.ok)
252
+ return acted(response, 409, "refused", started.message);
253
+ return acted(response, 200, "done", started.replayed ? "This thread already started." : "The thread started.");
254
+ }
255
+ function familyAt(url, verb) {
256
+ const task = matchTaskPath(url.pathname, `/${verb}$`);
257
+ const family = task === null ? null : runtime.familyOf(task.taskId);
258
+ return family === null || family.problem !== null ? null : family;
259
+ }
260
+ async function taskSteps(ctx) {
261
+ const { url, response, who } = ctx;
262
+ if ([...url.searchParams.keys()].length > 0)
263
+ return refusal(response, 400, "request");
264
+ const family = familyAt(url, "steps");
265
+ if (family === null)
266
+ return refusal(response, 404, "task");
267
+ return sendChecked(response, 200, "stepCards", stepCardsOf({ store, family, now: clock(), access: runtime.workAccess(), evidenceRoot, viewer: who.name }));
268
+ }
269
+ async function taskDiff(ctx) {
270
+ const { url, response } = ctx;
271
+ const params = url.searchParams, runParam = params.get("run"), fileParam = params.get("file"), fromParam = params.get("from"), countParam = params.get("count");
272
+ if ([...params.keys()].some(key => key !== "run" && key !== "file" && key !== "from" && key !== "count")
273
+ || ["run", "file", "from", "count"].some(key => params.getAll(key).length > 1)
274
+ || (runParam !== null && !/^[1-9][0-9]{0,14}$/.test(runParam)) || (fileParam !== null && !/^(0|[1-9][0-9]{0,5})$/.test(fileParam))
275
+ || (fileParam !== null && runParam === null)
276
+ || (fromParam === null) !== (countParam === null) || (fromParam !== null && fileParam === null)
277
+ || (fromParam !== null && !/^[1-9][0-9]{0,6}$/.test(fromParam)) || (countParam !== null && (!/^[1-9][0-9]{0,2}$/.test(countParam) || Number(countParam) > DIFF_CONTEXT_MAX))) {
278
+ return refusal(response, 400, "request");
279
+ }
280
+ const family = familyAt(url, "diff");
281
+ if (family === null)
282
+ return refusal(response, 404, "task");
283
+ const results = resultRunsOf(store, family).filter(run => runtime.runVisible(run));
284
+ const run = runParam === null ? results[0] ?? null : results.find(one => one.id === Number(runParam)) ?? null;
285
+ if (runParam !== null && run === null)
286
+ return refusal(response, 404, "run");
287
+ if (fileParam === null)
288
+ return sendChecked(response, 200, "resultDiff", resultDiffOf(store, evidenceRoot, family.root.id, run));
289
+ if (fromParam !== null && countParam !== null) {
290
+ const context = resultDiffContextOf(store, evidenceRoot, family.root.id, run, Number(fileParam), Number(fromParam), Number(countParam), runtime.taskRepoOf(run.taskRef));
291
+ return context === null ? refusal(response, 404, "file") : sendChecked(response, 200, "resultDiffContext", context);
292
+ }
293
+ const one = resultDiffFileOf(store, evidenceRoot, family.root.id, run, Number(fileParam));
294
+ return one === null ? refusal(response, 404, "file") : sendChecked(response, 200, "resultDiffFile", one);
295
+ }
296
+ async function redeemLink(ctx) {
297
+ const { request, response } = ctx;
298
+ response.setHeader("Pragma", "no-cache");
299
+ const raw = await bodyOf(request, 1024);
300
+ let code = null;
301
+ if (raw !== null) {
302
+ try {
303
+ const read = linkRedemptionRequestSchema.safeParse(JSON.parse(raw));
304
+ code = read.success ? read.data.code : null;
305
+ }
306
+ catch {
307
+ code = null;
308
+ }
309
+ }
310
+ const held = spendLink(runtime, code);
311
+ const refused = (status, error, why) => {
312
+ if (why !== undefined && held !== undefined)
313
+ runtime.recordSignIn(held.account, "sign-in refused", "one-time link (terminal)", why);
314
+ return refusal(response, status, error);
315
+ };
316
+ const headers = request.headers;
317
+ if (headers.origin !== undefined || Object.keys(headers).some(name => name.startsWith("sec-fetch-")))
318
+ return refused(403, "browser", "opened by a browser page");
319
+ if (!/^application\/json(?:;\s*charset=utf-8)?$/i.test(String(headers["content-type"] ?? "")) || headers["x-toolroll-client"] !== "terminal")
320
+ return refused(400, "request");
321
+ if (code === null)
322
+ return refused(400, "request");
323
+ const admitted = admitLink(runtime, request, held, "terminal");
324
+ if (!admitted.ok)
325
+ return refusal(response, admitted.refusal.status, admitted.refusal.why);
326
+ const fields = { keyEpoch: null, keyHash: null };
327
+ const key = runtime.browserKeys.issueForClient(fields, request);
328
+ if (key === null)
329
+ return refused(403, "host", "not this console's own address");
330
+ const id = randomBytes(32).toString("hex"), csrf = randomBytes(32).toString("hex");
331
+ if (!saveLinkSession(runtime, request, admitted.held, "terminal", { id, csrf, keys: fields }))
332
+ return refusal(response, 410, "used");
333
+ const body = { version: ENGINE_API_VERSION, account: admitted.held.account, cookie: { name: SESSION_COOKIE, value: id }, csrf, key, epoch: runtime.keyEpoch };
334
+ return sendChecked(response, 200, "linkRedemption", body);
335
+ }
336
+ return {
337
+ upkeep: () => { if (flexible !== null) {
338
+ try {
339
+ tickFlexibleSessions(store, flexible);
340
+ }
341
+ catch { }
342
+ } },
343
+ close: async () => {
344
+ try {
345
+ if (flexible !== null)
346
+ await closeFlexibleSessions(store, flexible);
347
+ }
348
+ finally {
349
+ await launcher?.close();
350
+ }
351
+ },
352
+ registrations: [
353
+ ...handlersOf("pages", { "engine.hello": hello, "engine.agents": agents, "engine.agents-check": agentsCheck, "agents.live.run": liveRun, "agents.live.thread": liveThread, "agents.live.threads": liveThreads,
354
+ "agents.live.thread.answer": threadAnswer, "agents.live.thread.start": threadStart }),
355
+ ...handlersOf("tasks", { "task.steps": taskSteps, "task.diff": taskDiff }),
356
+ ...handlersOf("people", {}, { "edge.login-link-json": redeemLink }),
357
+ ],
358
+ };
359
+ }
360
+ const START_PROOFS = new Set(["password-now", "sso-now", "fresh-password", "fresh-sso", "session", "local-owner"]);
361
+ const FRESH_PROOFS = new Set(["password-now", "sso-now", "fresh-password", "fresh-sso", "local-owner"]);
362
+ function bodyOf(request, cap) {
363
+ return new Promise(resolve => {
364
+ const chunks = [];
365
+ let size = 0, over = false;
366
+ request.on("data", (chunk) => {
367
+ size += chunk.length;
368
+ if (size > cap) {
369
+ over = true;
370
+ chunks.length = 0;
371
+ return;
372
+ }
373
+ chunks.push(chunk);
374
+ });
375
+ request.on("end", () => resolve(over ? null : Buffer.concat(chunks).toString("utf8")));
376
+ request.on("error", () => resolve(null));
377
+ });
378
+ }
@@ -610,7 +610,7 @@ export function createFlowsHandlers(runtime) {
610
610
  removeLinearKey(dir);
611
611
  return settle("Linear key removed.");
612
612
  }
613
- if (!authenticateApprover(who, body.get("password") ?? "").ok)
613
+ if (!authenticateCredential(who, body.get("password") ?? "").ok)
614
614
  return answer(403, { ok: false, said: "Enter your Toolroll password to save a key." });
615
615
  const saved = saveLinearKey(dir, body.get("key") ?? "");
616
616
  return saved.ok ? settle("Linear key saved on this computer.") : answer(400, { ok: false, said: saved.message });
@@ -632,7 +632,7 @@ export function createFlowsHandlers(runtime) {
632
632
  return revokeUnattended(store, flow.id, who.name, now) ? settle("It no longer runs on its own. New cards wait for you.") : answer(409, { ok: false, said: "It wasn't running on its own." });
633
633
  }
634
634
  if (action === "browser") {
635
- const proved = authenticateApprover(who, body.get("password") ?? "", flow.repo);
635
+ const proved = authenticateCredential(who, body.get("password") ?? "", flow.repo);
636
636
  if (!proved.ok)
637
637
  return answer(403, { ok: false, said: "That password isn't right. Nothing was approved." });
638
638
  const signed = signFlowBrowser(store, { flow: flow.id, signer: who.name, proof: proved.method, sawDigest: body.get("digest") ?? "", console: { generation: who.via === "cookie" ? who.session.generation : -1 } }, now);
@@ -20,6 +20,7 @@ import {} from "../toolroll-update.js";
20
20
  import { timingSafeEqual } from "node:crypto";
21
21
  import {} from "node:http";
22
22
  import { SIGN_IN_LINK_PATH } from "./session.js";
23
+ import { requestContext } from "./request-context.js";
23
24
  import { matchRoute } from "./route-table.js";
24
25
  import {} from "../folder-look.js";
25
26
  import {} from "../project-identity.js";
@@ -243,3 +244,9 @@ export function refusalNext(method, url) {
243
244
  export function answersInPlace(request) {
244
245
  return request?.headers["x-toolroll-act"] === "in-place";
245
246
  }
247
+ export function refusedInPlace(response, status, words) {
248
+ if (requestContext.getStore()?.terminalAct !== true || status < 400 || response.headersSent)
249
+ return false;
250
+ respond(response, status, "application/json; charset=utf-8", JSON.stringify({ outcome: "refused", words }));
251
+ return true;
252
+ }
@@ -0,0 +1,52 @@
1
+ import { localOwnerBinding } from "../store.js";
2
+ import { FULL_SESSION } from "./session.js";
3
+ const CODE = /^[A-Za-z0-9_-]{43}$/;
4
+ export function spendLink(runtime, code) {
5
+ if (code === null || !CODE.test(code))
6
+ return undefined;
7
+ const key = runtime.linkKey(code);
8
+ const held = runtime.signInLinks.get(key);
9
+ if (held !== undefined)
10
+ runtime.signInLinks.delete(key);
11
+ return held;
12
+ }
13
+ export function admitLink(runtime, request, held, road) {
14
+ const refuse = (status, why) => ({ ok: false, refusal: { status, why } });
15
+ if (!runtime.fromThisComputer(request)) {
16
+ runtime.recordSignIn(held?.account ?? "unknown account", "sign-in refused", road === "terminal" ? "one-time link (terminal)" : "one-time link", "opened from another device");
17
+ return refuse(403, "elsewhere");
18
+ }
19
+ if (held === undefined || held.expires < Date.now())
20
+ return refuse(410, "used");
21
+ if (road === "terminal" && held.kind !== "local-owner")
22
+ return refuse(403, "local-owner");
23
+ const account = runtime.store.accountOf(held.account);
24
+ if (account === null || account.role !== "approver" || account.revokedAt !== null)
25
+ return refuse(403, "account");
26
+ if (!runtime.passwordAllowed(held.account))
27
+ return refuse(403, "provider");
28
+ return { ok: true, held };
29
+ }
30
+ export function saveLinkSession(runtime, request, held, road, made) {
31
+ const { store, sessions } = runtime;
32
+ const at = Date.now();
33
+ const base = { ...runtime.arrival(request), name: held.account, csrf: made.csrf, role: "approver", createdAt: at, lastSeen: at, sawBoardAt: null,
34
+ project: runtime.defaultProject, projectRevision: 1 };
35
+ const saved = store.transact(() => {
36
+ if (held.kind === "local-owner") {
37
+ const now = localOwnerBinding(store);
38
+ if (now === null || now.account !== held.account || now.localGeneration !== held.localGeneration || now.accountGeneration !== held.accountGeneration)
39
+ return false;
40
+ sessions.set(made.id, { ...base, generation: now.accountGeneration, authority: "local-owner", localGeneration: now.localGeneration, ...made.keys });
41
+ return true;
42
+ }
43
+ const now = store.accountOf(held.account);
44
+ if (now === null || now.role !== "approver" || now.revokedAt !== null || !now.passwordSet || now.generation !== held.accountGeneration)
45
+ return false;
46
+ sessions.set(made.id, { ...base, generation: held.accountGeneration, ...FULL_SESSION, ...made.keys });
47
+ return true;
48
+ });
49
+ if (saved)
50
+ runtime.recordSignIn(held.account, "signed in", road === "terminal" ? "local link (terminal)" : held.kind === "local-owner" ? "local link" : "one-time link");
51
+ return saved;
52
+ }
@@ -1,6 +1,9 @@
1
1
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
2
2
  import { html, htmlString, scriptElement } from "../html.js";
3
3
  import { HANDOFF_STYLE } from "./http.js";
4
+ export const TERMINAL_EPOCH = "terminal:";
5
+ const terminalSession = (session) => typeof session.keyEpoch === "string" && session.keyEpoch.startsWith(TERMINAL_EPOCH);
6
+ const epochOf = (session) => session.keyEpoch === null ? null : terminalSession(session) ? session.keyEpoch.slice(TERMINAL_EPOCH.length) : session.keyEpoch;
4
7
  export const KEY_HEADER = "x-toolroll-key";
5
8
  export const KEY_FIELD = "toolroll-key";
6
9
  export const KEY_PROTOCOL = "toolroll";
@@ -48,20 +51,27 @@ export function keyMatches(presented, hash) {
48
51
  export function createBrowserKeys(deps) {
49
52
  const canonicalHost = () => deps.enabled ? deps.protectedHost() : null;
50
53
  const required = () => canonicalHost() !== null;
54
+ const keyed = (who) => who.via === "cookie" && (required() || (deps.enabled && terminalSession(who.session)));
55
+ const mint = (session, terminal) => {
56
+ const key = randomBytes(32).toString("hex");
57
+ session.keyHash = keyHashOf(key);
58
+ session.keyEpoch = terminal ? `${TERMINAL_EPOCH}${deps.epoch}` : deps.epoch;
59
+ return key;
60
+ };
51
61
  const reconnectOf = (who, back = "/") => who.authority === "full"
52
62
  ? { kind: "password", href: back === "/" ? "/login/rekey" : `/login/rekey?return=${encodeURIComponent(back)}` }
53
63
  : { kind: "command", command: "toolroll --web" };
54
64
  const stale = (who, back) => {
55
- if (!required() || who.via !== "cookie")
65
+ if (!keyed(who))
56
66
  return null;
57
67
  const session = who.session;
58
- return session.keyEpoch !== deps.epoch || session.keyHash === null ? reconnectOf(who, back) : null;
68
+ return epochOf(session) !== deps.epoch || session.keyHash === null ? reconnectOf(who, back) : null;
59
69
  };
60
70
  return {
61
71
  required,
62
72
  canonicalHost,
63
73
  check(who, request, body) {
64
- if (!required() || who.via !== "cookie")
74
+ if (!keyed(who))
65
75
  return null;
66
76
  const local = who.authority !== "full";
67
77
  const reconnect = reconnectOf(who);
@@ -77,10 +87,14 @@ export function createBrowserKeys(deps) {
77
87
  const canonical = canonicalHost();
78
88
  if (canonical === null || request.headers.host !== canonical)
79
89
  return null;
80
- const key = randomBytes(32).toString("hex");
81
- session.keyHash = keyHashOf(key);
82
- session.keyEpoch = deps.epoch;
83
- return key;
90
+ return mint(session, false);
91
+ },
92
+ issueForClient(session, request) {
93
+ const host = request.headers.host;
94
+ const port = deps.servedPort?.() ?? null;
95
+ if (!deps.enabled || port === null || (host !== `127.0.0.1:${port}` && host !== `[::1]:${port}`))
96
+ return null;
97
+ return mint(session, true);
84
98
  },
85
99
  deliver(response, key, to, cookies = []) {
86
100
  const nonce = randomBytes(16).toString("base64");