toolroll 0.9.116 → 0.9.118

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 (136) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +43 -26
  3. package/dist/acp-agents.js +14 -1
  4. package/dist/acp-client.js +19 -1
  5. package/dist/agent-change-check.js +60 -0
  6. package/dist/agent-change-schema.js +19 -0
  7. package/dist/agent-detect.js +11 -1
  8. package/dist/agent-fence.js +93 -16
  9. package/dist/agent-network-request.js +108 -0
  10. package/dist/agent-requests.js +105 -0
  11. package/dist/approval-summary.js +3 -3
  12. package/dist/backup.js +17 -1
  13. package/dist/batch-checks.js +81 -18
  14. package/dist/browser/terminal.js +41 -41
  15. package/dist/browser/workspace.css +2 -2
  16. package/dist/browser/workspace.js +36 -36
  17. package/dist/builder.js +12 -2
  18. package/dist/candidate-materialize.js +119 -0
  19. package/dist/central-enrollment-contract.js +156 -0
  20. package/dist/central-recovery-stage.js +329 -0
  21. package/dist/chat-actions.js +101 -2
  22. package/dist/chat-channel.js +40 -0
  23. package/dist/check-only-standing.js +13 -0
  24. package/dist/check-only.js +25 -13
  25. package/dist/check-recovery-hold.js +199 -0
  26. package/dist/check-recovery-index-schema.js +3 -0
  27. package/dist/check-screenshots.js +83 -0
  28. package/dist/cli.js +125 -6
  29. package/dist/codex-limits.js +4 -0
  30. package/dist/coding-context.js +16 -2
  31. package/dist/coding-provider.js +7 -3
  32. package/dist/coding-workspace.js +5 -5
  33. package/dist/connect-cli.js +257 -11
  34. package/dist/contracts/chat-actions.js +4 -0
  35. package/dist/contracts/console-api.js +14 -3
  36. package/dist/contracts/engine-api.js +331 -2
  37. package/dist/contracts/lead-tools.js +56 -2
  38. package/dist/contracts/provider.js +1 -1
  39. package/dist/contracts/route.js +1 -1
  40. package/dist/contracts/terminal-connection.js +50 -0
  41. package/dist/converse.js +80 -4
  42. package/dist/device-pair.js +280 -0
  43. package/dist/direct-chat-artifacts.js +347 -0
  44. package/dist/direct-chat-catalog.js +311 -0
  45. package/dist/direct-chat-fence.js +96 -0
  46. package/dist/direct-chat-git.js +343 -0
  47. package/dist/direct-chat-laptop.js +19 -0
  48. package/dist/direct-chat-schema.js +181 -0
  49. package/dist/direct-chat-ship.js +861 -0
  50. package/dist/direct-chat-workspace.js +389 -0
  51. package/dist/direct-chat.js +2107 -0
  52. package/dist/doctor.js +1 -1
  53. package/dist/easy-start.js +18 -0
  54. package/dist/egress.js +25 -4
  55. package/dist/engine-chat.js +454 -0
  56. package/dist/engine-reads.js +141 -13
  57. package/dist/exec.js +4 -3
  58. package/dist/flexible-agents.js +8 -16
  59. package/dist/flexible-session.js +91 -47
  60. package/dist/flexible-ship.js +87 -7
  61. package/dist/flexible-start.js +4 -1
  62. package/dist/flexible-thread.js +2 -3
  63. package/dist/flexible-turns.js +26 -5
  64. package/dist/flow-triggers.js +13 -4
  65. package/dist/flows-ui.js +54 -20
  66. package/dist/handoff-cli.js +630 -0
  67. package/dist/invoke.js +71 -17
  68. package/dist/lead-contract.js +5 -4
  69. package/dist/lead-doors.js +80 -1
  70. package/dist/lead-progress.js +9 -0
  71. package/dist/lead-tools.js +681 -10
  72. package/dist/lead.js +37 -9
  73. package/dist/live-bus.js +11 -0
  74. package/dist/live-terminal.js +132 -12
  75. package/dist/local-handoff.js +363 -0
  76. package/dist/local-owner-acts.js +264 -2
  77. package/dist/local-owner.js +16 -1
  78. package/dist/multiplayer-handoff.js +528 -0
  79. package/dist/multiplayer-presence.js +471 -0
  80. package/dist/names.js +17 -4
  81. package/dist/needs-you.js +10 -0
  82. package/dist/operate.js +280 -19
  83. package/dist/planner.js +6 -1
  84. package/dist/policy.js +2 -2
  85. package/dist/project-delete-ui.js +18 -11
  86. package/dist/project-delete.js +65 -4
  87. package/dist/project-skills.js +28 -13
  88. package/dist/project-tools.js +1 -1
  89. package/dist/prompt.js +1 -1
  90. package/dist/provider-connection.js +2 -0
  91. package/dist/provider-home.js +251 -8
  92. package/dist/provider.js +3 -2
  93. package/dist/publish.js +119 -64
  94. package/dist/pull-request-flow.js +35 -14
  95. package/dist/read-executor-worker.js +1 -1
  96. package/dist/read-executor.js +95 -1
  97. package/dist/restore-retirement.js +152 -0
  98. package/dist/result-follow-ups.js +116 -37
  99. package/dist/route-change.js +44 -4
  100. package/dist/scope.js +62 -5
  101. package/dist/scout.js +6 -2
  102. package/dist/serve.js +49 -5
  103. package/dist/server/chat.js +94 -13
  104. package/dist/server/direct-chat.js +583 -0
  105. package/dist/server/engine-api.js +219 -21
  106. package/dist/server/flows.js +43 -10
  107. package/dist/server/found-repos.js +25 -0
  108. package/dist/server/guards.js +20 -6
  109. package/dist/server/live.js +81 -23
  110. package/dist/server/pages.js +67 -13
  111. package/dist/server/people-tokens.js +47 -6
  112. package/dist/server/remote.js +29 -0
  113. package/dist/server/render-results.js +6 -2
  114. package/dist/server/render-settings.js +4 -2
  115. package/dist/server/render-tasks.js +18 -17
  116. package/dist/server/route-table.js +69 -2
  117. package/dist/server/settings.js +22 -7
  118. package/dist/server/task-views.js +15 -3
  119. package/dist/server/tasks.js +39 -2
  120. package/dist/server/terminals.js +185 -11
  121. package/dist/settings-proofs.js +1 -1
  122. package/dist/skills-manifest.js +57 -0
  123. package/dist/store.js +499 -56
  124. package/dist/subscription-chat.js +33 -6
  125. package/dist/subscription-usage.js +233 -0
  126. package/dist/task-live.js +2 -1
  127. package/dist/teardown-git.js +34 -4
  128. package/dist/terminal-connection.js +159 -0
  129. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  130. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  131. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  132. package/dist/tui/linux-x64/toolroll-tui +0 -0
  133. package/dist/tui-contract.js +1 -1
  134. package/dist/tui-launch.js +32 -1
  135. package/dist/workspace-identity-schema.js +21 -0
  136. package/package.json +4 -2
@@ -0,0 +1,363 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { basename, join } from "node:path";
5
+ import { remoteAllows, reproveRemote } from "./operate-remote.js";
6
+ import { adapterPolicy } from "./server/route-policy.js";
7
+ import { resultRunsOf, takeOverRevisionOf } from "./engine-reads.js";
8
+ import { terminalDiffView } from "./result-evidence-readers.js";
9
+ import { scanForSecrets } from "./evidence.js";
10
+ import { teardownGit } from "./teardown-git.js";
11
+ import { verifyApproverStanding } from "./principal.js";
12
+ export const HANDOFF_PROTOCOL = 1;
13
+ export const MAX_HANDOFF_PATCH_BYTES = 4 * 1024 * 1024;
14
+ export const MAX_HANDOFF_BODY_BYTES = MAX_HANDOFF_PATCH_BYTES + 64 * 1024;
15
+ export const MAX_HANDOFF_NOTE_CHARS = 2_000;
16
+ const SHA_PATTERN = /^[0-9a-f]{40,64}$/;
17
+ export function validateHandoffPatch(patch) {
18
+ if (typeof patch !== "string" || patch.trim() === "") {
19
+ return { ok: false, error: "Patch must be a non-empty unified diff." };
20
+ }
21
+ if (Buffer.byteLength(patch, "utf8") > MAX_HANDOFF_PATCH_BYTES) {
22
+ return { ok: false, error: `Patch exceeds the ${MAX_HANDOFF_PATCH_BYTES / (1024 * 1024)} MiB handoff limit.` };
23
+ }
24
+ if (patch.includes("\u0000")) {
25
+ return { ok: false, error: "Patch contains NUL bytes and cannot be accepted." };
26
+ }
27
+ if (scanForSecrets(patch).length > 0) {
28
+ return { ok: false, error: "Patch looks like it contains a secret or credential and was refused." };
29
+ }
30
+ const files = [];
31
+ for (const line of patch.split("\n")) {
32
+ if (/^(?:new|old) file mode 120000\b/.test(line)) {
33
+ return { ok: false, error: "Symlink additions or modifications are refused in local handoff patches." };
34
+ }
35
+ const header = /^(?:diff --git a\/(.+?) b\/(.+)|(?:\+\+\+|---) [ab]\/(.+))$/.exec(line);
36
+ if (header === null)
37
+ continue;
38
+ const candidates = [header[1], header[2], header[3]].filter((one) => typeof one === "string");
39
+ for (const raw of candidates) {
40
+ const cleaned = raw.replace(/^"(.*)"$/, "$1").trim();
41
+ if (cleaned === "" || cleaned === "/dev/null")
42
+ continue;
43
+ if (cleaned.startsWith("/") || cleaned.startsWith("\\") || /^[A-Za-z]:/.test(cleaned)) {
44
+ return { ok: false, error: `Unsafe absolute path in patch: ${cleaned}` };
45
+ }
46
+ const segments = cleaned.split(/[\\/]+/);
47
+ if (segments.some(seg => seg === ".." || seg === "." || seg.toLowerCase() === ".git")) {
48
+ return { ok: false, error: `Unsafe path segment in patch: ${cleaned}` };
49
+ }
50
+ if (!files.includes(cleaned))
51
+ files.push(cleaned);
52
+ }
53
+ }
54
+ if (files.length === 0) {
55
+ return { ok: false, error: "Patch contains no valid file headers." };
56
+ }
57
+ return { ok: true, files };
58
+ }
59
+ function sendJson(response, status, value) {
60
+ response.writeHead(status, {
61
+ "content-type": "application/json; charset=utf-8",
62
+ "cache-control": "no-store",
63
+ "pragma": "no-cache",
64
+ "x-content-type-options": "nosniff",
65
+ });
66
+ response.end(JSON.stringify(value));
67
+ }
68
+ function readJsonBody(request, cap) {
69
+ return new Promise(resolve => {
70
+ const chunks = [];
71
+ let size = 0;
72
+ let settled = false;
73
+ const finish = (value) => {
74
+ if (settled)
75
+ return;
76
+ settled = true;
77
+ resolve(value);
78
+ };
79
+ request.on("data", (chunk) => {
80
+ size += chunk.length;
81
+ if (size > cap) {
82
+ request.resume();
83
+ finish(null);
84
+ return;
85
+ }
86
+ chunks.push(chunk);
87
+ });
88
+ request.on("end", () => {
89
+ try {
90
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
91
+ finish(parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null);
92
+ }
93
+ catch {
94
+ finish(null);
95
+ }
96
+ });
97
+ request.on("error", () => finish(null));
98
+ });
99
+ }
100
+ function taskIdFromPath(url, suffix) {
101
+ const prefix = "/api/handoff/task/";
102
+ if (!url.pathname.startsWith(prefix) || !url.pathname.endsWith(suffix))
103
+ return null;
104
+ const raw = url.pathname.slice(prefix.length, suffix === "" ? undefined : -suffix.length);
105
+ if (raw === "" || raw.includes("/"))
106
+ return null;
107
+ try {
108
+ const decoded = decodeURIComponent(raw);
109
+ return /^[A-Za-z0-9_.-]{1,128}$/.test(decoded) ? decoded : null;
110
+ }
111
+ catch {
112
+ return null;
113
+ }
114
+ }
115
+ function authenticateHandoff(request, response, options, needScope) {
116
+ const names = request.rawHeaders.filter((_v, idx) => idx % 2 === 0).map(n => n.toLowerCase());
117
+ if (names.includes("cookie") || names.includes("origin") || names.includes("referer")
118
+ || names.some(n => n.startsWith("sec-fetch-"))
119
+ || names.filter(n => n === "authorization").length !== 1) {
120
+ request.resume();
121
+ sendJson(response, 400, { protocol: HANDOFF_PROTOCOL, ok: false, error: "request", message: "Invalid handoff request headers." });
122
+ return null;
123
+ }
124
+ if (!/^Bearer so_[a-f0-9]{12}_[A-Za-z0-9_-]{43}$/.test(request.headers.authorization ?? "")) {
125
+ request.resume();
126
+ sendJson(response, 401, { protocol: HANDOFF_PROTOCOL, ok: false, error: "unauthenticated", message: "Authenticate with a person API token." });
127
+ return null;
128
+ }
129
+ const principal = options.authenticate(request);
130
+ if (principal === null) {
131
+ request.resume();
132
+ sendJson(response, 401, { protocol: HANDOFF_PROTOCOL, ok: false, error: "unauthenticated", message: "Your API token is invalid or expired." });
133
+ return null;
134
+ }
135
+ const live = reproveRemote(options.store, principal, options.clock());
136
+ if (!live.ok) {
137
+ request.resume();
138
+ sendJson(response, 401, { protocol: HANDOFF_PROTOCOL, ok: false, error: "unauthenticated", message: "Your sign-in changed. Reconnect." });
139
+ return null;
140
+ }
141
+ const cred = options.store.apiTokenSecret(principal.tokenId)?.row;
142
+ if (cred?.purpose !== "api") {
143
+ request.resume();
144
+ sendJson(response, 403, { protocol: HANDOFF_PROTOCOL, ok: false, error: "credential-purpose", message: "Use an ordinary API token for code handoff." });
145
+ return null;
146
+ }
147
+ if (!adapterPolicy({ caller: "bearer", capability: live.scope, token: true }, needScope).ok || (needScope === "act" && live.scope !== "act")) {
148
+ request.resume();
149
+ sendJson(response, 403, { protocol: HANDOFF_PROTOCOL, ok: false, error: "forbidden", message: "Uploading a local candidate requires an act API token." });
150
+ return null;
151
+ }
152
+ const budget = options.admit?.(principal);
153
+ if (budget !== undefined && !budget.ok) {
154
+ if (budget.status !== 503)
155
+ response.setHeader("retry-after", String(budget.retryAfter));
156
+ request.resume();
157
+ sendJson(response, budget.status === 503 ? 503 : 429, { protocol: HANDOFF_PROTOCOL, ok: false, error: "rate-limited", message: "Too many requests. Try again shortly." });
158
+ return null;
159
+ }
160
+ let identity;
161
+ try {
162
+ identity = options.store.workspaceIdentity();
163
+ }
164
+ catch {
165
+ request.resume();
166
+ sendJson(response, 503, { protocol: HANDOFF_PROTOCOL, ok: false, error: "workspace-unavailable", message: "Workspace identity unavailable." });
167
+ return null;
168
+ }
169
+ const pinnedWorkspace = request.headers["x-toolroll-workspace"];
170
+ const pinnedRecovery = request.headers["x-toolroll-recovery"];
171
+ if (pinnedWorkspace !== undefined && pinnedWorkspace !== identity.id) {
172
+ request.resume();
173
+ sendJson(response, 409, { protocol: HANDOFF_PROTOCOL, ok: false, error: "workspace-mismatch", message: "This central server does not match your saved workspace identity." });
174
+ return null;
175
+ }
176
+ if (pinnedRecovery !== undefined && pinnedRecovery !== identity.recoveryGeneration) {
177
+ request.resume();
178
+ sendJson(response, 409, { protocol: HANDOFF_PROTOCOL, ok: false, error: "recovery-changed", message: "This workspace was restored or rotated. Reconnect before pushing." });
179
+ return null;
180
+ }
181
+ return { principal, scope: live.scope, identity };
182
+ }
183
+ export async function handleHandoffPull(request, response, url, options) {
184
+ const auth = authenticateHandoff(request, response, options, "read");
185
+ if (auth === null)
186
+ return;
187
+ const taskId = taskIdFromPath(url, "");
188
+ if (taskId === null)
189
+ return sendJson(response, 400, { protocol: HANDOFF_PROTOCOL, ok: false, error: "request", message: "Invalid task id." });
190
+ const { store, evidenceRoot } = options;
191
+ const allowedRepos = auth.principal.projects === null
192
+ ? null
193
+ : auth.principal.projects.filter(repo => store.accountCanAccess(auth.principal.account, repo));
194
+ const family = store.taskFamilyOf(taskId, allowedRepos, false);
195
+ if (family === null || family.problem !== null || family.root.repo === null || !remoteAllows(store, auth.principal, family.root.repo)) {
196
+ return sendJson(response, 404, { protocol: HANDOFF_PROTOCOL, ok: false, error: "not-found", message: "No such task in your projects." });
197
+ }
198
+ const repo = family.root.repo;
199
+ const results = resultRunsOf(store, family);
200
+ const latest = results[0] ?? null;
201
+ let patch = "";
202
+ let patchTruncated = false;
203
+ const patchChain = [];
204
+ if (latest !== null) {
205
+ const view = terminalDiffView(store.artifactsFor(latest.id), evidenceRoot);
206
+ if (view?.patch !== null && view?.patch !== undefined && !("problem" in view.patch)) {
207
+ patch = view.patch.text;
208
+ patchTruncated = view.patch.truncated;
209
+ }
210
+ let totalChainBytes = 0;
211
+ const chronological = [...results].reverse().slice(-20);
212
+ for (const run of chronological) {
213
+ if (!run.baseRevision || !run.headRevision || !SHA_PATTERN.test(run.baseRevision) || !SHA_PATTERN.test(run.headRevision))
214
+ continue;
215
+ const rv = terminalDiffView(store.artifactsFor(run.id), evidenceRoot);
216
+ if (rv?.patch && !("problem" in rv.patch) && !rv.patch.truncated && rv.patch.text.trim() !== "") {
217
+ totalChainBytes += Buffer.byteLength(rv.patch.text, "utf8");
218
+ if (totalChainBytes <= MAX_HANDOFF_PATCH_BYTES) {
219
+ patchChain.push({ parentCommit: run.baseRevision, headCommit: run.headRevision, patch: rv.patch.text });
220
+ }
221
+ }
222
+ }
223
+ }
224
+ let baseCommit = latest?.headRevision ?? latest?.baseRevision ?? null;
225
+ const parentCommit = latest?.baseRevision ?? null;
226
+ if (baseCommit === null && existsSync(join(repo, ".git"))) {
227
+ const git = teardownGit();
228
+ const head = await git(repo, ["rev-parse", "HEAD"]).catch(() => null);
229
+ if (head !== null && head.code === 0 && SHA_PATTERN.test(head.stdout.trim())) {
230
+ baseCommit = head.stdout.trim();
231
+ }
232
+ }
233
+ const headCommit = latest === null ? null : takeOverRevisionOf(latest);
234
+ const after = reproveRemote(store, auth.principal, options.clock());
235
+ if (!after.ok || !remoteAllows(store, auth.principal, repo)) {
236
+ return sendJson(response, 401, { protocol: HANDOFF_PROTOCOL, ok: false, error: "unauthenticated", message: "Your access changed." });
237
+ }
238
+ return sendJson(response, 200, {
239
+ protocol: HANDOFF_PROTOCOL,
240
+ ok: true,
241
+ workspaceId: auth.identity.id,
242
+ recoveryGeneration: auth.identity.recoveryGeneration,
243
+ taskId: family.current.id,
244
+ rootId: family.root.id,
245
+ title: family.current.title,
246
+ projectName: basename(repo),
247
+ runId: latest?.id ?? null,
248
+ baseCommit,
249
+ parentCommit,
250
+ headCommit,
251
+ branch: latest?.branch ?? null,
252
+ patch,
253
+ patchTruncated,
254
+ patchChain,
255
+ });
256
+ }
257
+ export async function handleHandoffPush(request, response, url, options) {
258
+ const auth = authenticateHandoff(request, response, options, "act");
259
+ if (auth === null)
260
+ return;
261
+ const taskId = taskIdFromPath(url, "/candidate");
262
+ if (taskId === null)
263
+ return sendJson(response, 400, { protocol: HANDOFF_PROTOCOL, ok: false, error: "request", message: "Invalid task id." });
264
+ const body = await readJsonBody(request, MAX_HANDOFF_BODY_BYTES);
265
+ if (body === null) {
266
+ return sendJson(response, 400, { protocol: HANDOFF_PROTOCOL, ok: false, error: "request", message: "Expected a bounded JSON object { patch, baseCommit?, note? }." });
267
+ }
268
+ const patch = typeof body["patch"] === "string" ? body["patch"] : "";
269
+ const baseCommit = typeof body["baseCommit"] === "string" && SHA_PATTERN.test(body["baseCommit"]) ? body["baseCommit"] : null;
270
+ const note = typeof body["note"] === "string" ? body["note"].trim() : "";
271
+ if (note.length > MAX_HANDOFF_NOTE_CHARS) {
272
+ return sendJson(response, 400, { protocol: HANDOFF_PROTOCOL, ok: false, error: "request", message: `Note exceeds ${MAX_HANDOFF_NOTE_CHARS} characters.` });
273
+ }
274
+ if (note !== "" && scanForSecrets(note).length > 0) {
275
+ return sendJson(response, 400, { protocol: HANDOFF_PROTOCOL, ok: false, error: "secret-refused", message: "Note looks like it contains a secret and was refused." });
276
+ }
277
+ const checked = validateHandoffPatch(patch);
278
+ if (!checked.ok) {
279
+ return sendJson(response, 400, { protocol: HANDOFF_PROTOCOL, ok: false, error: "invalid-patch", message: checked.error });
280
+ }
281
+ const { store, evidenceRoot } = options;
282
+ const allowedRepos = auth.principal.projects === null
283
+ ? null
284
+ : auth.principal.projects.filter(repo => store.accountCanAccess(auth.principal.account, repo));
285
+ const family = store.taskFamilyOf(taskId, allowedRepos, false);
286
+ if (family === null || family.problem !== null || family.root.repo === null || !remoteAllows(store, auth.principal, family.root.repo)) {
287
+ return sendJson(response, 404, { protocol: HANDOFF_PROTOCOL, ok: false, error: "not-found", message: "No such task in your projects." });
288
+ }
289
+ const repo = family.root.repo;
290
+ if (existsSync(join(repo, ".git"))) {
291
+ const git = teardownGit();
292
+ const scratch = mkdtempSync(join(tmpdir(), "so-handoff-verify-"));
293
+ const worktree = join(scratch, "wt");
294
+ const patchFile = join(scratch, "candidate.patch");
295
+ try {
296
+ writeFileSync(patchFile, patch, { mode: 0o600 });
297
+ const target = baseCommit ?? "HEAD";
298
+ const added = await git(repo, ["worktree", "add", "--detach", "--", worktree, target]);
299
+ if (added.code !== 0) {
300
+ return sendJson(response, 409, { protocol: HANDOFF_PROTOCOL, ok: false, error: "base-mismatch", message: `Could not check out base commit ${target} on the central repository.` });
301
+ }
302
+ const applied = await git(worktree, ["apply", "--check", "--", patchFile]);
303
+ if (applied.code !== 0) {
304
+ return sendJson(response, 409, { protocol: HANDOFF_PROTOCOL, ok: false, error: "patch-conflict", message: "Patch does not apply cleanly to the central base commit. Rebase locally and try again." });
305
+ }
306
+ }
307
+ finally {
308
+ await git(repo, ["worktree", "remove", "--force", "--", worktree]).catch(() => { });
309
+ rmSync(scratch, { recursive: true, force: true });
310
+ }
311
+ }
312
+ const now = options.clock();
313
+ const after = reproveRemote(store, auth.principal, now);
314
+ if (!after.ok || after.scope !== "act" || !remoteAllows(store, auth.principal, repo)) {
315
+ return sendJson(response, 401, { protocol: HANDOFF_PROTOCOL, ok: false, error: "unauthenticated", message: "Your access changed before upload finalized." });
316
+ }
317
+ const sha256 = createHash("sha256").update(patch, "utf8").digest("hex");
318
+ const candidateId = `cand-${randomBytes(8).toString("hex")}`;
319
+ const outDir = join(evidenceRoot, "handoff-candidates", family.root.id);
320
+ mkdirSync(outDir, { recursive: true, mode: 0o700 });
321
+ writeFileSync(join(outDir, `${candidateId}.patch`), patch, { mode: 0o600 });
322
+ writeFileSync(join(outDir, `${candidateId}.json`), JSON.stringify({
323
+ id: candidateId,
324
+ taskId: family.current.id,
325
+ rootId: family.root.id,
326
+ author: auth.principal.account,
327
+ createdAt: now.toISOString(),
328
+ baseCommit: baseCommit ?? null,
329
+ files: checked.files,
330
+ note,
331
+ patchSha256: sha256,
332
+ trust: "unverified",
333
+ promotedAt: null,
334
+ promotedBy: null,
335
+ }, null, 2), { mode: 0o600 });
336
+ const provenance = `Local code handoff candidate ${candidateId} uploaded by ${auth.principal.account} (${checked.files.length} file${checked.files.length === 1 ? "" : "s"}, sha256:${sha256.slice(0, 12)}, unverified — requires central checks/review).${note ? ` Note: ${note}` : ""}`;
337
+ store.recordAction({
338
+ at: now.toISOString(),
339
+ actor: auth.principal.account,
340
+ repo,
341
+ taskId: family.current.id,
342
+ runId: null,
343
+ action: "handoff.candidate",
344
+ source: "api",
345
+ outcome: "accepted",
346
+ detail: provenance,
347
+ });
348
+ const standing = verifyApproverStanding(store, auth.principal.account, auth.principal.generation, [repo]);
349
+ if (standing.ok) {
350
+ store.fileSteerNote(family.current.id, standing.who.name, provenance, now);
351
+ }
352
+ store.bumpWake();
353
+ return sendJson(response, 201, {
354
+ protocol: HANDOFF_PROTOCOL,
355
+ ok: true,
356
+ candidateId,
357
+ taskId: family.current.id,
358
+ sha256,
359
+ files: checked.files,
360
+ trust: "unverified",
361
+ message: provenance,
362
+ });
363
+ }
@@ -1,6 +1,13 @@
1
1
  import { PLAN_AGAIN_ACTIONS, planAgain, refArchived, requeueEligibility } from "./store.js";
2
- import { LOCAL_OWNER_LAPSED, localActNow } from "./local-owner.js";
3
- import { approverStanding, localWorkEligible, personApprovalOf } from "./scope.js";
2
+ import { asLocalOwner, LOCAL_OWNER_LAPSED, localActNow } from "./local-owner.js";
3
+ import { agentChangeToolsUnchanged, approve, approverStanding, localWorkEligible, personApprovalOf } from "./scope.js";
4
+ import { agentOnlyChange } from "./agent-change-check.js";
5
+ import { agentChoicesFor, routeOfTask } from "./agentconfig.js";
6
+ import { legOf, routeFromJson } from "./phase-routing.js";
7
+ import { providerName } from "./provider-auth.js";
8
+ import { requestTaskStop } from "./task-control.js";
9
+ import { activeRemote } from "./remote-run.js";
10
+ import { currentActor } from "./actor.js";
4
11
  import { plannerContractOf, plannerSourceDigest } from "./planner-source.js";
5
12
  import { scopeApprovedForDispatch } from "./dispatch.js";
6
13
  export const LOCAL_PLAN_ACTION = "task plan (local owner)";
@@ -209,3 +216,258 @@ function withdrawPlanAuthorization(store, taskId, repo, account, now, why) {
209
216
  action: "unchanged plan pre-authorization withdrawn", outcome: "withdrawn",
210
217
  detail: JSON.stringify({ v: 1, signedBy: String(armed["signed_by"]), basis: String(armed["basis"]), why }) });
211
218
  }
219
+ export const TASK_RUNNING_NOW = "This task is running right now.";
220
+ export const AGENTS_PICK_AGAIN = "The plan changed since you picked — pick again.";
221
+ export const AGENTS_DRIFTED = "Your model setup changed since you approved — approve again.";
222
+ export const AGENTS_TOOLS_CHANGED = "The project's tools changed since you approved — approve again to use them.";
223
+ export const LOCAL_AGENT_CHANGE_ACTION = "task agents (local owner)";
224
+ export const LOCAL_AGENT_PENDING_ACTION = "task agents pending (local owner)";
225
+ class Unpicked extends Error {
226
+ result;
227
+ constructor(result) {
228
+ super(result.message);
229
+ this.result = result;
230
+ }
231
+ }
232
+ const ROLE_NOUN = { plan: "planner", build: "builder" };
233
+ const agentNamed = (one) => `${providerName(one.provider)} ${one.model}`;
234
+ const UNAVAILABLE = { ok: false, status: 404, message: "That task is unavailable in your projects." };
235
+ export function pendingAgentChangeOf(store, taskRef) {
236
+ const row = store.handle.prepare("SELECT phase, provider, model, apply_when, by, at, problem FROM pending_agent_change WHERE task_ref = ?").get(taskRef);
237
+ if (row === undefined)
238
+ return null;
239
+ return { phase: row["phase"] === "plan" ? "plan" : "build", provider: String(row["provider"]), model: String(row["model"]), when: row["apply_when"] === "restart" ? "restart" : "next-run",
240
+ by: String(row["by"]), at: String(row["at"]), problem: row["problem"] == null ? null : String(row["problem"]) };
241
+ }
242
+ function pickConfiguredProblem(store, taskId, ref, pick, now) {
243
+ const routed = routeOfTask(store, taskId, ref, now);
244
+ const offered = agentChoicesFor(store, ref.repo, routed?.kind === "route" ? routed.route : null)[pick.phase].filter(one => one.selectable);
245
+ if (offered.some(one => one.provider === pick.provider && one.model === pick.model))
246
+ return null;
247
+ return offered.length === 0 ? `No configured agent can be the ${ROLE_NOUN[pick.phase]} for this task right now.`
248
+ : `${agentNamed(pick)} isn't one of the configured ${ROLE_NOUN[pick.phase]}s right now. Pick again.`;
249
+ }
250
+ function currentAgentOf(store, taskId, phase) {
251
+ const route = routeFromJson(store.getScope(taskId)?.proposedRouteJson ?? null);
252
+ return route === null ? null : { provider: legOf(route, phase).provider, model: legOf(route, phase).model };
253
+ }
254
+ function pickProblem(store, account, taskId, ref, pick, now) {
255
+ if (store.getTask(taskId)?.state === "cancelled")
256
+ return { ok: false, status: 409, message: "This task was cancelled." };
257
+ const eligible = localWorkEligible(store, account, taskId, { act: "agents" });
258
+ if (!eligible.ok)
259
+ return { ok: false, status: 403, message: eligible.message };
260
+ const scope = store.getScope(taskId);
261
+ if (scope === null || scope.digest !== pick.sawDigest)
262
+ return { ok: false, status: 409, message: AGENTS_PICK_AGAIN };
263
+ const configured = pickConfiguredProblem(store, taskId, ref, pick, now);
264
+ return configured === null ? null : { ok: false, status: 400, message: configured };
265
+ }
266
+ function carryRefusalWords(result) {
267
+ if (!result.ok && "message" in result && typeof result.message === "string")
268
+ return result.message;
269
+ return !result.ok && result.reason === "second-approver" ? "This task needs a second person's yes, so its models weren't changed." : "Your approval couldn't carry over to the new model, so nothing changed.";
270
+ }
271
+ function applyPickInside(store, local, taskId, pick, how, now) {
272
+ const ref = store.lookupRef(taskId);
273
+ if (ref === null || store.getTask(taskId) === null || !approverStanding(store, local.account, ref.repo).ok)
274
+ return UNAVAILABLE;
275
+ if (refArchived(store, ref.id))
276
+ return { ok: false, status: 409, message: "This task is put away. Restore it first." };
277
+ if (store.hasLiveClaim(ref.id, now))
278
+ return { ok: false, status: 409, message: TASK_RUNNING_NOW };
279
+ const problem = pickProblem(store, local.account, taskId, ref, pick, now);
280
+ if (problem !== null)
281
+ return problem;
282
+ const role = ROLE_NOUN[pick.phase], to = { provider: pick.provider, model: pick.model };
283
+ const from = currentAgentOf(store, taskId, pick.phase);
284
+ if (from !== null && from.provider === to.provider && from.model === to.model) {
285
+ store.handle.prepare("DELETE FROM pending_agent_change WHERE task_ref = ?").run(ref.id);
286
+ return { ok: true, outcome: "kept", words: `${agentNamed(to)} is already the ${role}.`, sealed: null };
287
+ }
288
+ const before = store.getScope(taskId);
289
+ const edited = store.editTaskRoute(ref.id, {
290
+ by: local.account,
291
+ authenticate: () => approverStanding(store, local.account, ref.repo).ok ? { ok: true } : { ok: false, reason: "That task is unavailable in your projects." },
292
+ override: { phase: pick.phase, provider: pick.provider, model: pick.model },
293
+ expectDigest: pick.sawDigest,
294
+ configured: true,
295
+ }, now);
296
+ if (!edited.ok) {
297
+ return edited.reason === "changed" ? { ok: false, status: 409, message: AGENTS_PICK_AGAIN }
298
+ : edited.reason === "live-claim" ? { ok: false, status: 409, message: TASK_RUNNING_NOW }
299
+ : edited.reason === "unauthenticated" || edited.reason === "no-task" ? UNAVAILABLE
300
+ : { ok: false, status: 400, message: edited.detail };
301
+ }
302
+ let outcome = "changed", sealed = null, toolsMoved = false;
303
+ if (edited.replanned)
304
+ outcome = "replanned";
305
+ else if (edited.staled) {
306
+ const refiled = store.getScope(taskId);
307
+ const ownYes = before.approvedBy === local.account && (before.approvalBasis === "password" || before.approvalBasis === "chat");
308
+ const only = refiled === null ? null : agentOnlyChange({ routeJson: refiled.approvedRouteJson, profile: refiled.approvedProfile, chainJson: refiled.approvedChainJson }, { routeJson: refiled.proposedRouteJson, profile: refiled.profile, chainJson: refiled.proposedChainJson }, provider => store.agentsFor([provider])[0]?.billing ?? null);
309
+ if (!ownYes)
310
+ outcome = "approve-again";
311
+ else if (refiled === null || only === null || !only.ok || only.phase !== pick.phase)
312
+ outcome = "drifted";
313
+ else if (before.approvedDigest === null || !agentChangeToolsUnchanged(store, taskId, before.approvedDigest)) {
314
+ outcome = "drifted";
315
+ toolsMoved = true;
316
+ }
317
+ else {
318
+ const carried = approve(store, taskId, local.account, now, refiled.digest, "");
319
+ if (!carried.ok)
320
+ throw new Unpicked({ ok: false, status: 409, message: carryRefusalWords(carried) });
321
+ outcome = "resealed";
322
+ sealed = refiled.digest;
323
+ }
324
+ }
325
+ const after = store.getScope(taskId);
326
+ if (after !== null)
327
+ store.recordScopeAuthor(taskId, after.digest, local.account, now);
328
+ store.handle.prepare("DELETE FROM pending_agent_change WHERE task_ref = ?").run(ref.id);
329
+ store.recordAction({ at: now.toISOString(), actor: `operator:${local.account}`, repo: ref.repo, taskId, runId: null, action: LOCAL_AGENT_CHANGE_ACTION, outcome, source: "request",
330
+ detail: JSON.stringify({ v: 1, phase: pick.phase, from, to, sealed, act: "change-task-agents", how, via: local.transport }) });
331
+ const changed = `The ${role} is now ${agentNamed(to)}.`;
332
+ const words = outcome === "resealed" ? `${changed} Still approved.`
333
+ : outcome === "replanned" ? `${changed} A new plan is coming; approve it when it's ready.`
334
+ : outcome === "approve-again" ? `${changed} Approve it again to build with it.`
335
+ : outcome === "drifted" ? `${changed} ${toolsMoved ? AGENTS_TOOLS_CHANGED : AGENTS_DRIFTED}`
336
+ : changed;
337
+ return { ok: true, outcome, words, sealed };
338
+ }
339
+ function liveAttemptOf(store, taskRef, now) {
340
+ const lease = store.currentLiveLease(taskRef, now);
341
+ if (lease === null)
342
+ return null;
343
+ const row = store.handle.prepare(`SELECT r.id AS id FROM run r WHERE r.task_ref = ? AND r.lease_id = ? AND r.outcome IS NULL
344
+ AND (r.parent_run IS NULL OR NOT EXISTS (SELECT 1 FROM run p WHERE p.id = r.parent_run AND p.lease_id = r.lease_id)) ORDER BY r.id LIMIT 1`).get(taskRef, lease);
345
+ return row === undefined ? null : Number(row["id"]);
346
+ }
347
+ export function localOwnerChangeAgents(store, taskId, pick, when, now) {
348
+ let signal = null;
349
+ try {
350
+ const result = store.transact(() => {
351
+ const local = localActNow(store, "change-task-agents");
352
+ if (local === null)
353
+ return { ok: false, status: 403, message: LOCAL_OWNER_LAPSED };
354
+ const ref = store.lookupRef(taskId);
355
+ if (ref === null || store.getTask(taskId) === null || !approverStanding(store, local.account, ref.repo).ok)
356
+ return UNAVAILABLE;
357
+ if (refArchived(store, ref.id))
358
+ return { ok: false, status: 409, message: "This task is put away. Restore it first." };
359
+ if (!store.hasLiveClaim(ref.id, now))
360
+ return applyPickInside(store, local, taskId, pick, "now", now);
361
+ if (when === "now")
362
+ return { ok: false, status: 409, message: TASK_RUNNING_NOW };
363
+ const problem = pickProblem(store, local.account, taskId, ref, pick, now);
364
+ if (problem !== null)
365
+ return problem;
366
+ const run = liveAttemptOf(store, ref.id, now);
367
+ if (when === "restart") {
368
+ if (run === null)
369
+ return { ok: false, status: 409, message: TASK_RUNNING_NOW };
370
+ const asked = requestTaskStop(store, { taskId, runId: run, by: local.account, via: local.transport === "terminal" ? "cli" : "web", deferSignal: one => { signal = one; } }, now);
371
+ if (!asked.ok)
372
+ throw new Unpicked({ ok: false, status: 409, message: `${TASK_RUNNING_NOW} It can't be stopped: ${asked.detail}.` });
373
+ }
374
+ store.handle.prepare(`INSERT INTO pending_agent_change (task_ref, phase, provider, model, apply_when, saw_digest, run, by, local_generation, account_generation, transport, at, problem)
375
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)
376
+ ON CONFLICT (task_ref) DO UPDATE SET phase = excluded.phase, provider = excluded.provider, model = excluded.model, apply_when = excluded.apply_when,
377
+ saw_digest = excluded.saw_digest, run = excluded.run, by = excluded.by, local_generation = excluded.local_generation,
378
+ account_generation = excluded.account_generation, transport = excluded.transport, at = excluded.at, problem = NULL`)
379
+ .run(ref.id, pick.phase, pick.provider, pick.model, when, pick.sawDigest, run, local.account, local.localGeneration, local.accountGeneration, local.transport, now.toISOString());
380
+ store.recordAction({ at: now.toISOString(), actor: `operator:${local.account}`, repo: ref.repo, taskId, runId: run, action: LOCAL_AGENT_PENDING_ACTION, outcome: when, source: "request",
381
+ detail: JSON.stringify({ v: 1, phase: pick.phase, to: { provider: pick.provider, model: pick.model }, sawDigest: pick.sawDigest, via: local.transport }) });
382
+ const words = when === "restart" ? `Stopping the run; it starts again on ${agentNamed(pick)}.` : `Switches to ${agentNamed(pick)} when this run ends.`;
383
+ return { ok: true, outcome: "pending", words, sealed: null };
384
+ });
385
+ if (result.ok)
386
+ signal?.();
387
+ return result;
388
+ }
389
+ catch (error) {
390
+ if (error instanceof Unpicked)
391
+ return error.result;
392
+ if (error instanceof Error && error.message === LOCAL_OWNER_LAPSED)
393
+ return { ok: false, status: 403, message: LOCAL_OWNER_LAPSED };
394
+ throw error;
395
+ }
396
+ }
397
+ export function applyPendingAgentChanges(store, now) {
398
+ if (activeRemote() !== null || currentActor() !== null)
399
+ return 0;
400
+ const rows = store.handle.prepare(`SELECT p.*, r.external_id AS task_id FROM pending_agent_change p JOIN task_ref r ON r.id = p.task_ref WHERE p.problem IS NULL ORDER BY p.at`).all();
401
+ let applied = 0;
402
+ for (const row of rows) {
403
+ const taskRef = Number(row["task_ref"]), taskId = String(row["task_id"]);
404
+ if (store.getTask(taskId)?.state === "cancelled" || refArchived(store, taskRef)) {
405
+ store.handle.prepare("DELETE FROM pending_agent_change WHERE task_ref = ?").run(taskRef);
406
+ continue;
407
+ }
408
+ if (store.hasLiveClaim(taskRef, now))
409
+ continue;
410
+ const run = row["run"] == null ? null : Number(row["run"]);
411
+ const when = row["apply_when"] === "restart" ? "restart" : "next-run";
412
+ if (when === "restart" && run !== null) {
413
+ const stop = store.stopOf(run);
414
+ if (stop !== null && stop.resumedAt === null && (stop.settledAt === null || store.getRun(run)?.outcome == null))
415
+ continue;
416
+ }
417
+ const pending = {
418
+ taskRef, taskId, when, run, at: String(row["at"]),
419
+ pick: { phase: row["phase"] === "plan" ? "plan" : "build", provider: String(row["provider"]), model: String(row["model"]), sawDigest: String(row["saw_digest"]) },
420
+ principal: { account: String(row["by"]), localGeneration: Number(row["local_generation"]), accountGeneration: Number(row["account_generation"]),
421
+ transport: row["transport"] === "terminal" ? "terminal" : "browser", act: "change-task-agents", sessionHash: null, request: null },
422
+ };
423
+ let done;
424
+ try {
425
+ done = asLocalOwner(pending.principal, () => applyPendingAsOwner(store, pending, now));
426
+ }
427
+ catch (error) {
428
+ done = { ok: false, status: 500, message: `This change couldn't be applied: ${error instanceof Error ? error.message : String(error)}` };
429
+ }
430
+ if (done === "wait")
431
+ continue;
432
+ if (done.ok) {
433
+ applied++;
434
+ continue;
435
+ }
436
+ const words = done.message.slice(0, 500);
437
+ store.transact(() => store.handle.prepare("UPDATE pending_agent_change SET problem = ? WHERE task_ref = ? AND at = ? AND problem IS NULL").run(words, taskRef, pending.at));
438
+ }
439
+ return applied;
440
+ }
441
+ function applyPendingAsOwner(store, pending, now) {
442
+ try {
443
+ return store.transact(() => {
444
+ const local = localActNow(store, "change-task-agents");
445
+ if (local === null || local.account !== pending.principal.account)
446
+ throw new Unpicked({ ok: false, status: 403, message: LOCAL_OWNER_LAPSED });
447
+ const still = store.handle.prepare("SELECT 1 AS hit FROM pending_agent_change WHERE task_ref = ? AND at = ? AND problem IS NULL").get(pending.taskRef, pending.at);
448
+ if (still === undefined)
449
+ return "wait";
450
+ if (store.hasLiveClaim(pending.taskRef, now))
451
+ return "wait";
452
+ const stop = pending.when === "restart" && pending.run !== null ? store.stopOf(pending.run) : null;
453
+ if (stop !== null && stop.resumedAt === null && (stop.settledAt === null || store.getRun(pending.run)?.outcome == null))
454
+ return "wait";
455
+ const done = applyPickInside(store, local, pending.taskId, pending.pick, pending.when, now);
456
+ if (!done.ok)
457
+ throw new Unpicked(done);
458
+ if (stop !== null && stop.resumedAt === null) {
459
+ const resumed = store.resumeRunStop({ runId: pending.run, taskRef: pending.taskRef, by: local.account, via: local.transport === "terminal" ? "cli" : "web" }, now);
460
+ if (!resumed.ok)
461
+ throw new Unpicked({ ok: false, status: 409, message: `The stopped run can't start again yet: ${resumed.detail}.` });
462
+ }
463
+ return done;
464
+ });
465
+ }
466
+ catch (error) {
467
+ if (error instanceof Unpicked)
468
+ return error.result;
469
+ if (error instanceof Error && error.message === LOCAL_OWNER_LAPSED)
470
+ return { ok: false, status: 403, message: LOCAL_OWNER_LAPSED };
471
+ throw error;
472
+ }
473
+ }
@@ -47,8 +47,19 @@ export const LOCAL_OWNER_ACTS = Object.freeze([
47
47
  "flexible-sign-in-check",
48
48
  "flexible-sign-in-clear",
49
49
  "project-flexible",
50
+ "project-network",
51
+ "project-live-view",
52
+ "change-task-agents",
53
+ "trigger-pause",
54
+ "trigger-resume",
55
+ "trigger-run",
56
+ "direct-chat-start",
57
+ "direct-chat-send",
58
+ "direct-chat-stop",
59
+ "direct-chat-manage",
60
+ "direct-chat-ship",
50
61
  ]);
51
- export const LOCAL_PASSWORD_ACTS = new Set(["flexible-switch", "flexible-sign-in-save", "flexible-sign-in-check", "project-flexible"]);
62
+ export const LOCAL_PASSWORD_ACTS = new Set(["flexible-switch", "flexible-sign-in-save", "flexible-sign-in-check", "project-flexible", "project-network", "project-live-view"]);
52
63
  const ACT_SET = new Set(LOCAL_OWNER_ACTS);
53
64
  export function localOwnerAct(value) {
54
65
  return typeof value === "string" && ACT_SET.has(value);
@@ -144,6 +155,10 @@ export const CHAT_ACTION_LOCAL_ACTS = Object.freeze({
144
155
  task_cancel: "stop-run",
145
156
  task_resume: "resume-run",
146
157
  task_start: "build-now",
158
+ direct_chat_start: "direct-chat-start",
159
+ direct_chat_reply: "direct-chat-send",
160
+ direct_chat_promote: "file-task",
161
+ direct_chat_ship: "direct-chat-ship",
147
162
  });
148
163
  export const CHAT_TASK_ACTION_LOCAL_ACTS = Object.freeze({
149
164
  stop: "stop-run",