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
@@ -102,6 +102,12 @@ export function runDirProblem(dir, uid = process.getuid?.() ?? -1, mustExist = t
102
102
  return `${dir} is open to other users — Toolroll uses it only when it is yours alone (chmod 700)`;
103
103
  return null;
104
104
  }
105
+ export function instanceSocketTooLong(databaseFile) {
106
+ const needs = Buffer.byteLength(join(instanceRunDir(databaseFile), "0123456789abcdef.sock"));
107
+ if (needs <= SOCKET_PATH_MAX)
108
+ return null;
109
+ return `the database's folder is too deep for Toolroll's socket (${needs} of at most ${SOCKET_PATH_MAX} bytes), so nothing can find a console started on it — move it to a shorter folder (for example ~/.toolroll) or start with --db at a shorter path`;
110
+ }
105
111
  export function socketPathProblem(path) {
106
112
  if (!SOCKET_NAME.test(basename(path)))
107
113
  return `${path} isn't a console socket`;
@@ -151,6 +157,9 @@ export function askSocket(socketPath, request, timeoutMs = 2_000, connect = path
151
157
  });
152
158
  }
153
159
  export async function openInstanceSocket(databaseFile, facts, secret, link) {
160
+ const tooLong = instanceSocketTooLong(databaseFile);
161
+ if (tooLong !== null)
162
+ return { ok: false, problem: tooLong };
154
163
  const dir = instanceRunDir(databaseFile);
155
164
  const problem = prepareRunDir(dir);
156
165
  if (problem !== null)
@@ -306,7 +315,7 @@ export async function proveLiveConsole(databaseFile, store, build, seams = {}) {
306
315
  const restart = "stop it and run `toolroll up` again";
307
316
  const read = readInstanceState(store);
308
317
  if (read.state === "none")
309
- return { ok: false, state: "none", message: "no console is running" };
318
+ return { ok: false, state: "none", message: instanceSocketTooLong(databaseFile) ?? "no console is running" };
310
319
  if (read.state === "invalid")
311
320
  return { ok: false, state: "refused", message: `the console's record can't be read — ${restart}` };
312
321
  const record = read.record;
@@ -49,9 +49,14 @@ export const CONSOLE_FORMS = {
49
49
  sweep: formContract("POST /sweeps/<sweep>/cancel-rest", ["confirm", "snapshot"]),
50
50
  passwordless: formContract("POST /settings/passwordless", ["action", "password"]),
51
51
  localModeOff: formContract("POST /settings/local-mode/off", ["password"]),
52
+ justMe: formContract("POST /settings/install-mode/solo", ["password"]),
52
53
  releaseApproval: formContract("POST /settings/release-approval", ["repo", "action", "password"]),
53
54
  projectFlexible: formContract("POST /settings/project/flexible", ["repo", "action", "max", "digest", "password"]),
54
- term: formContract("POST /term/start, /term/<terminal>/close, /term/<terminal>/remove", ["repo", "program", "password"]),
55
+ threadAnswer: formContract("POST /agents/live/thread/<id>/answer", ["request", "card", "decision", "question", "answer"]),
56
+ threadStart: formContract("POST /agents/live/thread", ["repo", "message", "model", "terms", "password"]),
57
+ term: formContract("POST /term/start, /term/<terminal>/close, /term/<terminal>/remove", ["repo", "program", "password", "task", "run"]),
58
+ termAgent: formContract("POST /term/agent/sign-in, /term/agent/install", ["agent", "password", "confirm"]),
59
+ agentsCheck: formContract("POST /engine/agents/check", []),
55
60
  skillsRevise: formContract("POST /settings/skills/revise", ["run", "repo", "feedback", "nonce"]),
56
61
  skillsChange: formContract("POST /settings/skills/import, /settings/skills/change", ["repo", "identity", "revision", "method", "content", "files", "url", "action", "sha", "sample", "nonce", "restore"]),
57
62
  kit: formContract("POST /kits/<kit>/<act>", ["repo", "password"]),
@@ -112,10 +117,10 @@ export const CONSOLE_FORMS = {
112
117
  pullRequestsCheck: formContract("POST /settings/pull-requests/check", ["repo"]),
113
118
  connectionCheck: formContract("POST /settings/connection/check", ["provider", "auth-mode", "value", "return"]),
114
119
  modelsRefresh: formContract("POST /control/models-refresh", ["repo", "nonce", "fingerprint", "token", "provider", "model", "command", "seconds", "task"]),
115
- providerKey: formContract("POST /settings/provider-key, /settings/provider-key-clear", ["provider", "auth-mode", "value"]),
116
- telegramToken: formContract("POST /settings/telegram-token", ["token"]),
117
- email: formContract("POST /settings/email, /settings/email-test, /settings/email-read-test", ["host", "port", "secure", "user", "from", "password", "imapHost", "imapPort"]),
118
- google: formContract("POST /settings/google, /settings/google/disconnect", ["clientId", "clientSecret"]),
120
+ providerKey: formContract("POST /settings/provider-key, /settings/provider-key-clear", ["provider", "auth-mode", "value", "password"]),
121
+ telegramToken: formContract("POST /settings/telegram-token", ["token", "password"]),
122
+ email: formContract("POST /settings/email, /settings/email-test, /settings/email-read-test", ["host", "port", "secure", "user", "from", "password", "imapHost", "imapPort", "token"]),
123
+ google: formContract("POST /settings/google, /settings/google/disconnect", ["clientId", "clientSecret", "password"]),
119
124
  projectsSelect: formContract("POST /projects/select", ["path", "return"]),
120
125
  projectsRemove: formContract("POST /projects/remove", ["repo"]),
121
126
  projectsOpen: formContract("POST /projects/open", ["path", "return", "via", "password"]),
@@ -0,0 +1,271 @@
1
+ import { createHash } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { parseContract } from "./contract.js";
4
+ export const ENGINE_API_VERSION = 1;
5
+ const version = z.literal(ENGINE_API_VERSION);
6
+ const iso = z.string();
7
+ const liveRecordSchema = z.union([
8
+ z.object({ k: z.literal("open"), at: iso, detail: z.enum(["base", "commands"]), s: z.number().int().optional() }),
9
+ z.object({ k: z.literal("start"), at: iso, s: z.number().int().optional() }),
10
+ z.object({ k: z.literal("say"), at: iso, t: z.array(z.string()), s: z.number().int().optional() }),
11
+ z.object({ k: z.literal("step"), at: iso, id: z.string(), kind: z.string(), target: z.string().optional(), once: z.literal(true).optional(), s: z.number().int().optional() }),
12
+ z.object({ k: z.literal("done"), at: iso, id: z.string(), ok: z.boolean().nullable(), out: z.array(z.string()).optional(), s: z.number().int().optional() }),
13
+ z.object({ k: z.literal("cut"), at: iso, s: z.number().int().optional() }),
14
+ z.object({ k: z.literal("cap"), at: iso.optional(), s: z.number().int().optional() }),
15
+ z.object({ k: z.literal("child"), s: z.number().int(), at: iso.optional(), parent: z.string().nullable(), via: z.number().int().optional(), desc: z.string().optional() }),
16
+ z.object({ k: z.literal("end"), s: z.number().int(), at: iso.optional(), ok: z.boolean().nullable() }),
17
+ z.object({ k: z.literal("over") }),
18
+ ]);
19
+ export const liveSessionRefSchema = z.discriminatedUnion("kind", [
20
+ z.object({ kind: z.literal("run"), id: z.number().int().positive(), task: z.string().nullable() }),
21
+ z.object({ kind: z.literal("thread"), id: z.string().regex(/^[0-9a-f]{32}$/), task: z.null() }),
22
+ ]);
23
+ const hex32 = z.string().regex(/^[0-9a-f]{32}$/);
24
+ const flexibleLevelSchema = z.enum(["supervised", "auto", "full"]);
25
+ const answerStateSchema = z.enum(["pending", "decided", "sending", "sent", "delivered", "not-sent", "uncertain", "withdrawn"]);
26
+ const threadQuestionSchema = z.object({
27
+ request: hex32,
28
+ kind: z.enum(["permission", "question"]),
29
+ title: z.string(),
30
+ detail: z.string().nullable(),
31
+ tool: z.string().nullable(),
32
+ complete: z.boolean(),
33
+ digest: z.string().regex(/^[0-9a-f]{64}$/),
34
+ state: answerStateSchema,
35
+ answerable: z.boolean(),
36
+ parts: z.array(z.object({ id: z.string(), question: z.string(), options: z.array(z.string()) })),
37
+ });
38
+ export const threadFactsSchema = z.object({
39
+ version: z.string().regex(/^[0-9a-f]{16}$/),
40
+ title: z.string(),
41
+ project: z.string().nullable(),
42
+ level: flexibleLevelSchema.nullable(),
43
+ agent: z.object({ provider: z.string(), model: z.string() }).nullable(),
44
+ turn: z.object({ seq: z.number().int(), status: z.string(), costUsd: z.number().nullable(), costBasis: z.enum(["measured", "estimated", "unknown"]).nullable() }).nullable(),
45
+ questions: z.array(threadQuestionSchema),
46
+ });
47
+ export const liveSessionWindowSchema = z.object({
48
+ version,
49
+ session: liveSessionRefSchema,
50
+ room: z.string(),
51
+ live: z.boolean(),
52
+ file: z.enum(["main", "sub"]),
53
+ window: z.discriminatedUnion("ok", [
54
+ z.object({ ok: z.literal(true), records: z.array(liveRecordSchema), cursor: z.string(), restarted: z.boolean(), earlier: z.boolean(),
55
+ quarantined: z.number().int(), skipped: z.number().int(), more: z.boolean() }),
56
+ z.object({ ok: z.literal(false), reason: z.enum(["missing", "unavailable", "off"]) }),
57
+ ]),
58
+ thread: threadFactsSchema.optional(),
59
+ });
60
+ export const liveThreadsSchema = z.object({
61
+ version,
62
+ threads: z.array(z.object({ id: hex32, title: z.string(), project: z.string().nullable(), level: flexibleLevelSchema.nullable(), live: z.boolean(), waiting: z.number().int(),
63
+ costUsd: z.number().nullable() })),
64
+ });
65
+ const workAskSchema = z.enum(["release", "approve", "answer", "flow", "wrong", "review", "setup", "other"]);
66
+ const needRowSchema = z.object({
67
+ id: z.string(), title: z.string(), href: z.string(), project: z.string().nullable(), age: z.string(),
68
+ state: z.enum(["needs", "running", "queued", "done"]),
69
+ ask: workAskSchema.nullable(),
70
+ group: z.enum(["decide", "review", "unblock"]).optional(),
71
+ reason: z.string().nullable(), line: z.string().nullable(),
72
+ action: z.object({ label: z.string(), href: z.string() }).nullable(),
73
+ question: z.object({ id: z.number().int(), text: z.string(), recap: z.string(),
74
+ options: z.array(z.object({ id: z.string(), label: z.string(), consequence: z.string(), recommended: z.boolean() })) }).nullable(),
75
+ });
76
+ const workRowSchema = z.object({
77
+ id: z.string(), title: z.string(), href: z.string(), project: z.string().nullable(), age: z.string(),
78
+ status: z.object({ label: z.string(), tone: z.string(), token: z.string() }),
79
+ word: z.object({ word: z.string(), tone: z.string() }),
80
+ ask: z.string().nullable(),
81
+ chip: z.string().nullable(),
82
+ group: z.string(),
83
+ rank: z.number().int(),
84
+ detail: z.string().nullable(),
85
+ problem: z.string().nullable(),
86
+ need: needRowSchema.nullable(),
87
+ });
88
+ export const workRowsSchema = z.object({
89
+ version,
90
+ project: z.string().nullable(),
91
+ projectName: z.string(),
92
+ needsCount: z.number().int(),
93
+ groups: z.array(z.object({ key: z.string(), label: z.string(), count: z.number().int() })).nullable(),
94
+ rows: z.array(workRowSchema),
95
+ needs: z.array(z.object({ key: z.enum(["decide", "review", "unblock"]), label: z.string(), count: z.number().int(), rows: z.array(needRowSchema) })),
96
+ next: z.string().nullable(),
97
+ room: z.literal("workspace"),
98
+ spend: z.object({ todayUsd: z.number(), planPercent: z.number().int().nullable() }).nullable(),
99
+ });
100
+ export const stepCardSchema = z.object({
101
+ key: z.enum(["plan", "approve", "build", "checks", "review", "ready"]),
102
+ label: z.string(),
103
+ state: z.enum(["done", "current", "stuck", "skipped", "todo"]),
104
+ mark: z.enum(["done", "needs", "live", "wait", "stuck", "skipped", "todo"]),
105
+ sentence: z.string(),
106
+ at: iso.nullable(),
107
+ needsYou: z.boolean(),
108
+ inChain: z.boolean(),
109
+ agent: z.object({ provider: z.string(), model: z.string().nullable() }).nullable(),
110
+ startedAt: iso.nullable(),
111
+ finishedAt: iso.nullable(),
112
+ costUsd: z.number().nullable(),
113
+ runs: z.array(z.number().int()),
114
+ terms: z.object({
115
+ key: z.string(),
116
+ revision: z.string().nullable(),
117
+ rows: z.array(z.object({ label: z.string(), words: z.string(), lines: z.array(z.string()) })),
118
+ warnings: z.array(z.string()),
119
+ usualLabel: z.string(),
120
+ usual: z.array(z.object({ label: z.string(), words: z.string() })),
121
+ }).optional(),
122
+ });
123
+ export const stepCardsSchema = z.object({
124
+ version,
125
+ task: z.object({ id: z.string(), root: z.string(), title: z.string(), state: z.string(), project: z.string().nullable() }),
126
+ chain: z.enum(["plan-first", "just-code"]),
127
+ headline: z.string().nullable(),
128
+ liveRun: z.number().int().nullable(),
129
+ cards: z.array(stepCardSchema).nullable(),
130
+ review: z.object({ run: z.number().int(), receipt: z.string().regex(/^[0-9a-f]{64}$/), source: z.string(),
131
+ accept: z.object({ owed: z.enum(["person-check", "exception"]).nullable(), blockers: z.array(z.string()), needs: z.string().nullable() }),
132
+ }).nullable(),
133
+ room: z.string(),
134
+ });
135
+ const diffProblemSchema = z.string().nullable();
136
+ export const resultDiffSchema = z.object({
137
+ version,
138
+ task: z.string(),
139
+ run: z.number().int().nullable(),
140
+ totals: z.object({ files: z.number().int(), additions: z.number().int(), deletions: z.number().int(), binary: z.number().int(), filesTruncated: z.boolean() }).nullable(),
141
+ files: z.array(z.object({ file: z.number().int(), path: z.string(), oldPath: z.string().nullable(), additions: z.number().int(), deletions: z.number().int(), binary: z.boolean(),
142
+ hunks: z.number().int() })),
143
+ patchTruncated: z.boolean(),
144
+ problem: diffProblemSchema,
145
+ });
146
+ const diffLineSchema = z.object({ kind: z.enum(["context", "addition", "deletion", "meta"]), text: z.string(), oldLine: z.number().int().nullable(), newLine: z.number().int().nullable() });
147
+ export const resultDiffFileSchema = z.object({
148
+ version,
149
+ task: z.string(),
150
+ run: z.number().int(),
151
+ file: z.object({ file: z.number().int(), path: z.string(), oldPath: z.string().nullable(), meta: z.array(z.string()),
152
+ hunks: z.array(z.object({ header: z.string(), lines: z.array(diffLineSchema) })) }),
153
+ linesTruncated: z.boolean(),
154
+ });
155
+ export const DIFF_CONTEXT_MAX = 100;
156
+ export const resultDiffContextSchema = z.object({
157
+ version,
158
+ task: z.string(),
159
+ run: z.number().int(),
160
+ file: z.number().int(),
161
+ from: z.number().int(),
162
+ lines: z.array(z.object({ newLine: z.number().int(), text: z.string() })),
163
+ lineCount: z.number().int().nullable(),
164
+ problem: z.string().nullable(),
165
+ });
166
+ export const agentsReadSchema = z.object({
167
+ version,
168
+ checkedAt: iso.nullable(),
169
+ agents: z.array(z.object({
170
+ id: z.string(),
171
+ name: z.string(),
172
+ state: z.enum(["signed-in", "signed-out", "unknown", "not-installed"]),
173
+ how: z.string().nullable(),
174
+ signIn: z.string().nullable(),
175
+ ready: z.boolean(),
176
+ next: z.string().nullable(),
177
+ setup: z.object({
178
+ install: z.string().nullable(),
179
+ canInstall: z.boolean(),
180
+ signIn: z.string().nullable(),
181
+ canSignIn: z.boolean(),
182
+ key: z.string().nullable(),
183
+ check: z.string().nullable(),
184
+ note: z.string().nullable(),
185
+ registry: z.string().nullable(),
186
+ registryUnsure: z.boolean(),
187
+ }),
188
+ })),
189
+ firstTask: z.object({ id: z.string(), name: z.string() }).nullable(),
190
+ lines: z.array(z.string()),
191
+ });
192
+ export const modelsReadSchema = z.object({
193
+ version,
194
+ canChange: z.boolean(),
195
+ digest: z.string(),
196
+ problem: z.string().nullable(),
197
+ roles: z.array(z.object({
198
+ key: z.enum(["plan", "build", "review"]),
199
+ label: z.string(),
200
+ current: z.string(),
201
+ words: z.string(),
202
+ choices: z.array(z.object({ provider: z.string(), label: z.string(), models: z.array(z.object({ value: z.string(), label: z.string() })) })),
203
+ })),
204
+ defaultAgent: z.string().nullable(),
205
+ presets: z.array(z.object({ agent: z.string(), name: z.string(), words: z.string(),
206
+ fields: z.record(z.string(), z.string()) })),
207
+ });
208
+ export const termStateSchema = z.object({
209
+ available: z.boolean(),
210
+ problem: z.string().nullable(),
211
+ programs: z.array(z.enum(["claude", "codex", "shell"])),
212
+ projects: z.array(z.object({ path: z.string(), name: z.string() })),
213
+ sessions: z.array(z.object({
214
+ id: z.string().regex(/^[0-9a-f]{32}$/), repo: z.string(), project: z.string(), program: z.enum(["claude", "codex", "shell"]), branch: z.string(),
215
+ startedAt: iso, endedAt: iso.nullable(), exit: z.object({ code: z.number().int().nullable(), signal: z.number().int().nullable() }).nullable(),
216
+ cleanup: z.enum(["clean", "uncertain"]).nullable(), task: z.string().nullable(), run: z.number().int().nullable(),
217
+ })),
218
+ });
219
+ export const termStartedSchema = z.discriminatedUnion("ok", [
220
+ z.object({ ok: z.literal(true), id: z.string().regex(/^[0-9a-f]{32}$/) }),
221
+ z.object({ ok: z.literal(false), error: z.string() }),
222
+ ]);
223
+ export const linkRedemptionSchema = z.object({
224
+ version,
225
+ account: z.string(),
226
+ cookie: z.object({ name: z.string(), value: z.string().regex(/^[0-9a-f]{64}$/) }),
227
+ csrf: z.string().regex(/^[0-9a-f]{64}$/),
228
+ key: z.string().regex(/^[0-9a-f]{64}$/),
229
+ epoch: z.string(),
230
+ });
231
+ export const linkRedemptionRequestSchema = z.strictObject({ code: z.string().regex(/^[A-Za-z0-9_-]{43}$/) });
232
+ export const ENGINE_REQUESTS = {
233
+ linkRedemption: { route: "POST /login/once", schema: linkRedemptionRequestSchema },
234
+ };
235
+ export const engineRefusalSchema = z.object({ error: z.string() });
236
+ export const helloSchema = z.object({ version, toolroll: z.string(), contract: z.string().regex(/^[0-9a-f]{64}$/), responses: z.array(z.string()),
237
+ mode: z.enum(["solo", "team"]), defaultChain: z.enum(["just-code", "plan-first"]) });
238
+ export const ENGINE_RESPONSES = {
239
+ liveSessionWindow: { route: "GET /agents/live/<kind>/<id>", schema: liveSessionWindowSchema },
240
+ liveThreads: { route: "GET /agents/live/threads", schema: liveThreadsSchema },
241
+ workRows: { route: "GET /work/rows", schema: workRowsSchema },
242
+ stepCards: { route: "GET /t/<task>/steps", schema: stepCardsSchema },
243
+ resultDiff: { route: "GET /t/<task>/diff", schema: resultDiffSchema },
244
+ resultDiffFile: { route: "GET /t/<task>/diff?run=&file=", schema: resultDiffFileSchema },
245
+ resultDiffContext: { route: "GET /t/<task>/diff?run=&file=&from=&count=", schema: resultDiffContextSchema },
246
+ linkRedemption: { route: "POST /login/once", schema: linkRedemptionSchema },
247
+ refusal: { route: "every engine route's refusal", schema: engineRefusalSchema },
248
+ hello: { route: "GET /engine/hello", schema: helloSchema },
249
+ agents: { route: "GET /engine/agents", schema: agentsReadSchema },
250
+ models: { route: "GET /engine/models", schema: modelsReadSchema },
251
+ termState: { route: "GET /term/state", schema: termStateSchema },
252
+ termStarted: { route: "POST /term/start, /term/agent/sign-in, /term/agent/install", schema: termStartedSchema },
253
+ };
254
+ const toStderr = (route, issues) => process.stderr.write(`engine api: ${route} disagrees with its contract: ${issues.slice(0, 5).map(one => `${one.path} ${one.kind}`).join("; ")}\n`);
255
+ export function checkEngineResponse(name, payload, report = toStderr) {
256
+ const { route, schema } = ENGINE_RESPONSES[name];
257
+ const parsed = parseContract(schema, payload);
258
+ if (!parsed.ok)
259
+ report(route, parsed.issues);
260
+ return payload;
261
+ }
262
+ export function engineJsonSchemas() {
263
+ const json = (schema) => { const { $schema: _dialect, ...rest } = z.toJSONSchema(schema, { target: "draft-2020-12", unrepresentable: "throw" }); return rest; };
264
+ return {
265
+ responses: Object.fromEntries(Object.entries(ENGINE_RESPONSES).map(([name, one]) => [name, json(one.schema)])),
266
+ requests: Object.fromEntries(Object.entries(ENGINE_REQUESTS).map(([name, one]) => [name, json(one.schema)])),
267
+ };
268
+ }
269
+ export function engineContractDigest() {
270
+ return createHash("sha256").update(JSON.stringify({ version: ENGINE_API_VERSION, ...engineJsonSchemas() })).digest("hex");
271
+ }
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { hashSecret, mintCredential } from "./api-tokens.js";
3
3
  import { canonicalRepos } from "./runner.js";
4
4
  import { fileTaskProposal } from "./proposal.js";
5
- import { describeScope } from "./scope.js";
5
+ import { describeScope, summaryContextOf } from "./approval-summary.js";
6
6
  import { reportSummaryFor } from "./lead-tools.js";
7
7
  import { claimedNowSql, markedRunningSql } from "./task-moves.js";
8
8
  import { taskWorkSummaryOf } from "./work-summary.js";
@@ -358,7 +358,7 @@ export function taskDetailFor(store, who, taskId, evidenceRoot, now = new Date()
358
358
  scope: {
359
359
  sealed: store.scopeSealed(taskId),
360
360
  goal: scope?.goal ?? null,
361
- words: scope === null ? [] : describeScope(scope),
361
+ words: scope === null ? [] : describeScope(scope, undefined, null, summaryContextOf(store, taskId, scope, now)),
362
362
  },
363
363
  waits,
364
364
  attempts,
@@ -1,7 +1,8 @@
1
1
  import { chmodSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { guardDiscord } from "./outbound-privacy.js";
3
4
  import { randomBytes } from "node:crypto";
4
- import { ChatDeliveryError, chatHash, } from "./chat-delivery-state.js";
5
+ import { ChatDeliveryError, chatHash, withheldPart, } from "./chat-delivery-state.js";
5
6
  import { chatObject as object } from "./chat-delivery.js";
6
7
  export { object };
7
8
  export const discordId = (v) => typeof v === "string" && /^[1-9][0-9]{16,19}$/.test(v);
@@ -10,7 +11,7 @@ export class DiscordError extends ChatDeliveryError {
10
11
  export const DISCORD_REFUSED = "Discord refused access. Check the app and direct-message permissions.";
11
12
  export const DISCORD_GONE = "The Discord message or conversation is unavailable. Open the saved chat.";
12
13
  export function discordApi(token, fetcher = fetch) {
13
- return async (method, path, body, file) => {
14
+ return guardDiscord(async (method, path, body, file) => {
14
15
  if (!/^\/(?:users\/@me|users\/[0-9]+|oauth2\/applications\/@me|channels\/[0-9]+(?:\/typing|\/messages\/[0-9]+\/reactions\/%F0%9F%91%80\/@me|\/messages(?:\/[0-9]+)?(?:\?limit=100)?)?|interactions\/[0-9]+\/[A-Za-z0-9._-]+\/callback)$/.test(path))
15
16
  throw new DiscordError("Invalid Discord request");
16
17
  if (method === "DELETE" && !/^\/channels\/[0-9]+\/messages\/[0-9]+\/reactions\/%F0%9F%91%80\/@me$/.test(path))
@@ -67,7 +68,7 @@ export function discordApi(token, fetcher = fetch) {
67
68
  throw new DiscordError(message, response.status >= 500 ? 15_000 : 60_000, response.status >= 500);
68
69
  }
69
70
  return Array.isArray(raw) ? { items: raw } : data;
70
- };
71
+ }, withheldPart);
71
72
  }
72
73
  export const discordCredentialFile = (dir) => join(dir, "discord-connection.json");
73
74
  export function loadDiscordCredentials(dir) {
@@ -6,7 +6,8 @@ import { cardWithin } from "./chat-card.js";
6
6
  import { chatFlowButtons } from "./chat-flow.js";
7
7
  import { refuseResultShots, resultShotsPruned, shotWaitsUntil } from "./result-shots.js";
8
8
  import { admitChatEvent } from "./chat-admission.js";
9
- import { ChatState, ChatDeliveryError, chatHash, chatRetryAt, partContent, } from "./chat-delivery-state.js";
9
+ import { guardDiscord, taskSubject } from "./outbound-privacy.js";
10
+ import { ChatState, ChatDeliveryError, chatHash, chatRetryAt, partContent, withheldPart, } from "./chat-delivery-state.js";
10
11
  import { readChatPart } from "./contracts/chat-content.js";
11
12
  import { readDiscordButtonToken, readDiscordComponentInteraction } from "./contracts/discord-callback.js";
12
13
  import { processChatEvent, planChatNotifications, channelAccess, chatObject as object, planRoomMessages, heldForWatch, } from "./chat-delivery.js";
@@ -183,6 +184,7 @@ export async function deliverDiscordPart(options) {
183
184
  if (event.kind === "notice" && options.canNotify?.() === false)
184
185
  return false;
185
186
  const content = partContent(row.payload);
187
+ options = { ...options, api: guardDiscord(options.api, withheldPart, taskSubject(store, content.task ?? content.image?.taskId)) };
186
188
  const destination = content.channel ?? binding.channel;
187
189
  if (content.task &&
188
190
  !repos.includes(store.lookupRef(content.task)?.repo ?? ""))
@@ -1,17 +1,21 @@
1
1
  export function easyStartArgs(argv) {
2
- let web = false, verbose = false, projectRoot = null, port = null;
2
+ let web = false, verbose = false, screenReader = false, projectRoot = null, port = null, tuiBinary = null;
3
3
  for (let index = 0; index < argv.length; index += 1) {
4
4
  const one = argv[index];
5
5
  if (one === "--web" && !web)
6
6
  web = true;
7
7
  else if (one === "--verbose" && !verbose)
8
8
  verbose = true;
9
- else if ((one === "--project-root" && projectRoot === null) || (one === "--port" && port === null)) {
9
+ else if (one === "--screen-reader" && !screenReader)
10
+ screenReader = true;
11
+ else if ((one === "--project-root" && projectRoot === null) || (one === "--port" && port === null) || (one === "--tui-binary" && tuiBinary === null)) {
10
12
  const value = argv[index + 1];
11
13
  if (value === undefined || value === "" || value.startsWith("-"))
12
14
  return null;
13
15
  if (one === "--port")
14
16
  port = value;
17
+ else if (one === "--tui-binary")
18
+ tuiBinary = value;
15
19
  else
16
20
  projectRoot = value;
17
21
  index += 1;
@@ -19,7 +23,7 @@ export function easyStartArgs(argv) {
19
23
  else
20
24
  return null;
21
25
  }
22
- return { web, projectRoot, port, ...(verbose ? { verbose } : {}) };
26
+ return { web, projectRoot, port, ...(verbose ? { verbose } : {}), ...(screenReader ? { screenReader } : {}), ...(tuiBinary === null ? {} : { tuiBinary }) };
23
27
  }
24
28
  export function easyStartApplies(argv, facts) {
25
29
  return facts.stdin && facts.stdout && !facts.agent && easyStartArgs(argv) !== null;
@@ -289,6 +289,31 @@ export function defaultEasyStartSeams(options) {
289
289
  openBrowser: async (url) => { (await import("./operate.js")).openBrowser(url); },
290
290
  openSignedIn: () => openLocalSignIn(file, options.build),
291
291
  openTui: async (session) => {
292
+ const { chooseTuiBinary, runTuiBinary } = await import("./tui-launch.js");
293
+ const { engineContractDigest } = await import("./contracts/engine-api.js");
294
+ const choice = chooseTuiBinary({ env: process.env, screenReader: options.screenReader === true, platform: process.platform, arch: process.arch, contract: engineContractDigest(), devBinary: options.tuiBinary ?? null });
295
+ if (choice.notice !== undefined)
296
+ options.write(`${choice.notice}.`);
297
+ let why = choice.ok ? null : choice.why;
298
+ if (choice.ok) {
299
+ const reader = openStoreReadOnly(file);
300
+ const link = reader === null ? { ok: false, message: "Toolroll's database can't be read" }
301
+ : await requestLocalLink(file, reader, options.build).finally(() => reader.close());
302
+ if (!link.ok)
303
+ why = `the terminal workbench couldn't sign in (${link.message})`;
304
+ else {
305
+ const { checkoutTop } = await import("./teardown-git.js");
306
+ const end = await runTuiBinary({ binary: choice.binary, identity: choice.identity, link: link.url, session, project: checkoutTop(cwd), cwd });
307
+ if (end === "changed")
308
+ why = "the terminal workbench changed after it was checked";
309
+ else if (end !== "classic")
310
+ return end;
311
+ else
312
+ why = null;
313
+ }
314
+ }
315
+ if (why !== null)
316
+ options.write(`Opening the classic screen: ${why}.`);
292
317
  const { createTuiSource } = await import("./tui-source.js");
293
318
  const { runAsLocalOwner } = await import("./local-owner.js");
294
319
  const source = createTuiSource({ databaseFile: file, ...(options.operate === undefined ? {} : { operate: options.operate }) });
package/dist/egress.js CHANGED
@@ -37,6 +37,28 @@ export function hostAllowed(host, hosts) {
37
37
  return false;
38
38
  return hosts.some(entry => entry === name || (entry.startsWith("*.") && name.endsWith(entry.slice(1))));
39
39
  }
40
+ export function untilClosed(signal, work) {
41
+ if (signal.aborted)
42
+ return Promise.resolve(null);
43
+ return new Promise((resolve, reject) => {
44
+ const aborted = () => resolve(null);
45
+ signal.addEventListener("abort", aborted, { once: true });
46
+ let pending;
47
+ try {
48
+ pending = work();
49
+ }
50
+ catch (error) {
51
+ signal.removeEventListener("abort", aborted);
52
+ reject(error);
53
+ return;
54
+ }
55
+ pending.then(value => { signal.removeEventListener("abort", aborted); resolve(value); }, error => { signal.removeEventListener("abort", aborted); reject(error); });
56
+ });
57
+ }
58
+ function anyHostByName(host) {
59
+ const name = normalizeHost(host);
60
+ return name !== null && !name.startsWith("*.");
61
+ }
40
62
  export const PROVIDER_HOSTS = {
41
63
  claude: ["api.anthropic.com", "console.anthropic.com", "platform.claude.com"],
42
64
  codex: ["api.openai.com", "chatgpt.com", "auth.openai.com"],
@@ -156,16 +178,24 @@ export function projectNetworkFromValue(value) {
156
178
  return null;
157
179
  return { mode: v["mode"], hosts: [...new Set(hosts)].sort(), loopback: v["loopback"] };
158
180
  }
159
- export function networkWords(network) {
181
+ export function unaccountedHosts(network, provider) {
182
+ const full = Object.values(REGISTRY_HOSTS).filter(hosts => hosts.every(one => network.hosts.includes(one)));
183
+ const own = PROVIDER_HOSTS[provider] ?? [];
184
+ const known = new Set([...(own.length > 0 && own.every(one => network.hosts.includes(one)) ? own : []), ...full.flat()]);
185
+ return network.hosts.filter(one => !known.has(one));
186
+ }
187
+ export function networkWords(network, provider) {
160
188
  if (network === null)
161
189
  return "Network: approved before network rules (provider and package registries only)";
162
190
  if (network.mode === "open")
163
191
  return `Network: open — any host${network.loopback === "proxy-only" ? "" : ", and every local service on this Mac"}`;
164
- const registries = Object.entries(REGISTRY_HOSTS)
165
- .filter(([, hosts]) => hosts.every(one => network.hosts.includes(one))).map(([name]) => REGISTRY_NAMES[name]);
166
- const known = new Set([...Object.values(REGISTRY_HOSTS).flat(), ...Object.values(PROVIDER_HOSTS).flat()]);
192
+ const full = Object.entries(REGISTRY_HOSTS).filter(([, hosts]) => hosts.every(one => network.hosts.includes(one)));
193
+ const own = PROVIDER_HOSTS[provider] ?? [];
194
+ const named = own.length > 0 && own.every(one => network.hosts.includes(one));
195
+ const known = new Set([...(named ? own : []), ...full.flatMap(([, hosts]) => hosts)]);
167
196
  const added = network.hosts.filter(one => !known.has(one));
168
- return `Network: the agent's provider${registries.length === 0 ? "" : `, ${registries.join(", ")}`}${added.length === 0 ? "" : `, and ${added.join(", ")}`}`
197
+ const parts = [...(named ? ["the agent's provider"] : []), ...full.map(([name]) => REGISTRY_NAMES[name])];
198
+ return `Network: ${parts.length === 0 && added.length === 0 ? "no hosts" : [parts.join(", "), added.length === 0 ? "" : `${parts.length === 0 ? "" : "and "}${added.join(", ")}`].filter(Boolean).join(", ")}`
169
199
  + (network.loopback === "any" ? "; and every local service on this Mac" : "");
170
200
  }
171
201
  const REGISTRY_NAMES = { npm: "npm", python: "PyPI", rust: "crates.io", go: "the Go proxy", ruby: "RubyGems", jvm: "Maven and Gradle" };
@@ -217,6 +247,9 @@ export async function startEgressProxy(options) {
217
247
  const addressAllowed = options.addressAllowed ?? isPublicAddress;
218
248
  const upstreamPort = options.upstreamPort ?? ((port) => port);
219
249
  const lookup = options.lookup ?? (async (host) => (await dnsLookup(host, { all: true, verbatim: true })).map(one => one.address));
250
+ const connectUpstream = options.connect ?? ((addresses, port, signal) => connectFirst(addresses, port, undefined, signal));
251
+ const closing = new AbortController();
252
+ const isClosed = () => closing.signal.aborted;
220
253
  const secret = randomBytes(24).toString("base64url");
221
254
  const expected = Buffer.from(secret);
222
255
  const sockets = new Set();
@@ -259,11 +292,14 @@ export async function startEgressProxy(options) {
259
292
  const admit = async (host, port, wantPort) => {
260
293
  if (port !== wantPort)
261
294
  return { ok: false, why: `port ${port} is not allowed` };
262
- if (!hostAllowed(host, options.hosts))
295
+ if (options.open === true ? !anyHostByName(host) : !hostAllowed(host, options.hosts))
263
296
  return { ok: false, why: "not an approved host" };
264
297
  let addresses;
265
298
  try {
266
- addresses = await lookup(normalizeHost(host));
299
+ const found = await untilClosed(closing.signal, () => lookup(normalizeHost(host)));
300
+ if (found === null || isClosed())
301
+ return { ok: false, why: "the proxy closed" };
302
+ addresses = found;
267
303
  }
268
304
  catch {
269
305
  return { ok: false, why: "the host does not resolve" };
@@ -296,12 +332,21 @@ export async function startEgressProxy(options) {
296
332
  return;
297
333
  }
298
334
  const reached = await admit(url.hostname, Number(url.port || 80), 80);
335
+ if (isClosed()) {
336
+ incoming.socket.destroy();
337
+ return;
338
+ }
299
339
  if (!reached.ok) {
300
340
  count(url.hostname, false, reached.why);
301
341
  outgoing.writeHead(403, { "content-type": "text/plain" }).end(`Toolroll: ${url.hostname} is not one of this build's approved hosts.`);
302
342
  return;
303
343
  }
304
- const upstream = await connectFirst(reached.addresses, upstreamPort(80));
344
+ const upstream = await connectUpstream(reached.addresses, upstreamPort(80), closing.signal);
345
+ if (isClosed()) {
346
+ upstream?.destroy();
347
+ incoming.socket.destroy();
348
+ return;
349
+ }
305
350
  if (upstream === null) {
306
351
  outgoing.writeHead(502).end();
307
352
  return;
@@ -332,12 +377,21 @@ export async function startEgressProxy(options) {
332
377
  }
333
378
  const match = /^([^:[\]\s]+):(\d{1,5})$/.exec(incoming.url ?? "");
334
379
  const reached = match === null ? { ok: false, why: "not a host name and port" } : await admit(match[1], Number(match[2]), 443);
380
+ if (isClosed()) {
381
+ client.destroy();
382
+ return;
383
+ }
335
384
  if (!reached.ok) {
336
385
  count(match?.[1] ?? String(incoming.url ?? ""), false, reached.why);
337
386
  client.end("HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n");
338
387
  return;
339
388
  }
340
- const upstream = await connectFirst(reached.addresses, upstreamPort(443));
389
+ const upstream = await connectUpstream(reached.addresses, upstreamPort(443), closing.signal);
390
+ if (isClosed()) {
391
+ upstream?.destroy();
392
+ client.destroy();
393
+ return;
394
+ }
341
395
  if (upstream === null) {
342
396
  if (!client.destroyed)
343
397
  client.end("HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n");
@@ -354,7 +408,14 @@ export async function startEgressProxy(options) {
354
408
  client.pipe(upstream);
355
409
  })();
356
410
  });
357
- server.on("connection", socket => { sockets.add(socket); socket.on("close", () => sockets.delete(socket)); });
411
+ server.on("connection", socket => {
412
+ if (isClosed()) {
413
+ socket.destroy();
414
+ return;
415
+ }
416
+ sockets.add(socket);
417
+ socket.on("close", () => sockets.delete(socket));
418
+ });
358
419
  await new Promise((done, fail) => {
359
420
  server.once("error", fail);
360
421
  server.listen(0, "127.0.0.1", () => { server.off("error", fail); done(); });
@@ -367,6 +428,7 @@ export async function startEgressProxy(options) {
367
428
  port,
368
429
  counts: () => ({ connections, refused, hosts: [...byHost].map(([host, one]) => ({ host, ...one })).sort((a, b) => b.connections + b.refused - (a.connections + a.refused) || a.host.localeCompare(b.host)), otherHosts }),
369
430
  close: () => new Promise(done => {
431
+ closing.abort();
370
432
  for (const socket of sockets)
371
433
  socket.destroy();
372
434
  server.close(() => done());