toolroll 0.9.109 → 0.9.111

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +5 -1
  3. package/THIRD_PARTY_NOTICES.md +30 -0
  4. package/dist/agent-detect.js +244 -0
  5. package/dist/agent-fence.js +12 -1
  6. package/dist/agent-said-schema.js +4 -0
  7. package/dist/agent-said.js +23 -0
  8. package/dist/agentconfig.js +2 -2
  9. package/dist/approval-summary.js +375 -0
  10. package/dist/attest.js +2 -2
  11. package/dist/browser/THIRD_PARTY_NOTICES.txt +30 -0
  12. package/dist/browser/workspace.css +2 -2
  13. package/dist/browser/workspace.js +27 -27
  14. package/dist/builder.js +42 -3
  15. package/dist/chat-actions.js +24 -17
  16. package/dist/chat-core.js +3 -1
  17. package/dist/chat-decide.js +101 -46
  18. package/dist/chat-delivery-state.js +2 -0
  19. package/dist/chat-delivery.js +3 -2
  20. package/dist/chat-live.js +2 -1
  21. package/dist/chat-task-actions.js +6 -0
  22. package/dist/check-report.js +1 -1
  23. package/dist/claim.js +28 -13
  24. package/dist/cli-help.js +1 -1
  25. package/dist/cli.js +2 -0
  26. package/dist/codex-limits.js +21 -8
  27. package/dist/console-instance.js +11 -1
  28. package/dist/contracts/console-api.js +13 -7
  29. package/dist/contracts/engine-api.js +283 -0
  30. package/dist/contracts/route.js +1 -0
  31. package/dist/coordinator.js +2 -2
  32. package/dist/discord-api.js +4 -3
  33. package/dist/discord-chat.js +3 -1
  34. package/dist/dispatch.js +1 -1
  35. package/dist/dispose.js +15 -9
  36. package/dist/easy-start-args.js +7 -3
  37. package/dist/easy-start.js +40 -1
  38. package/dist/egress.js +72 -10
  39. package/dist/engine-handoff.js +34 -0
  40. package/dist/engine-reads.js +338 -0
  41. package/dist/eval-world.js +3 -2
  42. package/dist/evidence.js +2 -0
  43. package/dist/fast-start.js +68 -18
  44. package/dist/fast-terms.js +2 -2
  45. package/dist/first-run.js +10 -2
  46. package/dist/flexible-agents.js +234 -0
  47. package/dist/flexible-answers-schema.js +61 -0
  48. package/dist/flexible-answers.js +889 -0
  49. package/dist/flexible-custody.js +494 -0
  50. package/dist/flexible-import.js +782 -0
  51. package/dist/flexible-launch-schema.js +72 -0
  52. package/dist/flexible-launch.js +331 -0
  53. package/dist/flexible-launcher.js +88 -0
  54. package/dist/flexible-levels.js +34 -0
  55. package/dist/flexible-merge-guard.js +47 -0
  56. package/dist/flexible-refs.js +47 -0
  57. package/dist/flexible-relay-cancel.js +19 -0
  58. package/dist/flexible-relay-schema.js +55 -0
  59. package/dist/flexible-relay-upstreams.js +36 -0
  60. package/dist/flexible-relay.js +1032 -0
  61. package/dist/flexible-session.js +732 -0
  62. package/dist/flexible-ship-schema.js +81 -0
  63. package/dist/flexible-ship.js +694 -0
  64. package/dist/flexible-start.js +80 -0
  65. package/dist/flexible-thread.js +175 -25
  66. package/dist/flexible-turns-schema.js +69 -0
  67. package/dist/flexible-turns.js +490 -0
  68. package/dist/flexible.js +10 -1
  69. package/dist/flow-actions.js +6 -4
  70. package/dist/flow-steps.js +1 -1
  71. package/dist/flows-cli.js +2 -1
  72. package/dist/git-views.js +6 -3
  73. package/dist/install-mode.js +225 -0
  74. package/dist/integrations.js +6 -1
  75. package/dist/lead-doors.js +7 -1
  76. package/dist/limits-ui.js +7 -0
  77. package/dist/live-reply.js +6 -0
  78. package/dist/live-terminal.js +425 -29
  79. package/dist/local-owner.js +7 -0
  80. package/dist/model-choices.js +12 -6
  81. package/dist/needs-you.js +2 -0
  82. package/dist/notification-delivery.js +11 -0
  83. package/dist/operate.js +128 -37
  84. package/dist/outbound-privacy.js +204 -0
  85. package/dist/passwordless.js +2 -1
  86. package/dist/phase-routing.js +3 -1
  87. package/dist/plane-review.js +1 -1
  88. package/dist/project-delete.js +14 -0
  89. package/dist/proposal.js +2 -2
  90. package/dist/provider-connection.js +19 -5
  91. package/dist/publish.js +5 -0
  92. package/dist/pull-request-flow.js +26 -7
  93. package/dist/push.js +5 -1
  94. package/dist/release-card.js +11 -3
  95. package/dist/release.js +10 -1
  96. package/dist/route-store.js +3 -3
  97. package/dist/sandbox-launch.js +32 -8
  98. package/dist/sandbox-runtime.js +16 -7
  99. package/dist/sandbox-tools.js +176 -0
  100. package/dist/scope.js +12 -36
  101. package/dist/scout-net.js +7 -2
  102. package/dist/serve.js +62 -13
  103. package/dist/server/chrome.js +3 -1
  104. package/dist/server/console.css +33 -6
  105. package/dist/server/engine-api.js +378 -0
  106. package/dist/server/flows.js +2 -2
  107. package/dist/server/http.js +7 -0
  108. package/dist/server/link-redemption.js +52 -0
  109. package/dist/server/mutation-key.js +21 -7
  110. package/dist/server/pages.js +72 -40
  111. package/dist/server/people-tokens.js +17 -41
  112. package/dist/server/render-chat.js +1 -0
  113. package/dist/server/render-new-task.js +3 -3
  114. package/dist/server/render-results.js +4 -4
  115. package/dist/server/render-tasks.js +133 -139
  116. package/dist/server/route-table.js +32 -1
  117. package/dist/server/settings-section-table.js +6 -0
  118. package/dist/server/settings-sections.js +69 -0
  119. package/dist/server/settings.js +120 -10
  120. package/dist/server/task-views.js +8 -2
  121. package/dist/server/tasks.js +56 -12
  122. package/dist/server/terminals.js +181 -28
  123. package/dist/server/welcome.js +35 -10
  124. package/dist/settings-groups-ui.js +2 -2
  125. package/dist/settings-proofs.js +14 -9
  126. package/dist/slack-api.js +4 -3
  127. package/dist/slack-chat.js +5 -3
  128. package/dist/spend.js +46 -12
  129. package/dist/status-probe.js +343 -0
  130. package/dist/store.js +181 -12
  131. package/dist/task-sizing-schema.js +14 -0
  132. package/dist/task-sizing.js +76 -10
  133. package/dist/teams-api.js +4 -3
  134. package/dist/teams-chat.js +4 -2
  135. package/dist/telegram-lead.js +2 -1
  136. package/dist/telegram-live.js +2 -1
  137. package/dist/telegram-team.js +2 -1
  138. package/dist/telegram.js +17 -5
  139. package/dist/toolroll-update.js +3 -1
  140. package/dist/trusted-path.js +162 -0
  141. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  142. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  143. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  144. package/dist/tui/linux-x64/toolroll-tui +0 -0
  145. package/dist/tui-launch.js +282 -0
  146. package/dist/tui-source.js +5 -3
  147. package/dist/tui.js +1 -1
  148. package/dist/webhooks.js +14 -4
  149. package/dist/welcome-facts.js +22 -15
  150. package/dist/work-index.js +2 -2
  151. package/dist/workspace-ui.js +5 -0
  152. package/package.json +1 -1
  153. package/scripts/crash-canary.mjs +1 -1
  154. package/scripts/pilot.mjs +1 -1
  155. package/scripts/provider-canary.mjs +5 -3
@@ -1,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 ?? ""))
package/dist/dispatch.js CHANGED
@@ -35,7 +35,7 @@ export function taskReadinessBlocker(store, taskRef, now) {
35
35
  const hold = db
36
36
  .prepare(`SELECT owner_kind, until, reason FROM hold
37
37
  WHERE task_ref = ? AND (until IS NULL OR until > ?)
38
- ORDER BY held_at, id LIMIT 1`)
38
+ ORDER BY owner_kind = 'backoff', held_at, id LIMIT 1`)
39
39
  .get(taskRef, stamp);
40
40
  if (hold !== undefined) {
41
41
  return {
package/dist/dispose.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { STORAGE_HOLD_PREFIX } from "./needs-you.js";
2
+ import { recordAgentSaid } from "./store.js";
2
3
  import { blockAfterSignedOut } from "./fallback.js";
3
4
  import { authorizeCheckOnly } from "./check-only.js";
4
5
  import { proposeNewRoute } from "./route-change.js";
@@ -29,6 +30,7 @@ const TICK_FAILURE_REASONS = new Set([
29
30
  "git",
30
31
  "commit-failure",
31
32
  "provider-init",
33
+ "agent-error",
32
34
  "setup",
33
35
  "revision-brief",
34
36
  "stopped",
@@ -223,18 +225,22 @@ function disposeBuildOutcomeLocked(context, result) {
223
225
  recordExecClass(store, runId, result.reason);
224
226
  const failureClass = result.reason === "agent-reported"
225
227
  ? "agent-reported"
226
- : result.reason === "no-handoff"
227
- ? "no-handoff"
228
- : result.reason === "no-op" || result.reason === "moved-head" || result.reason === "moved-branch"
229
- ? "no-op"
230
- : result.reason === "timeout" || result.reason === "git" || result.reason === "provider-init" || result.reason === "setup" || result.reason === "stopped" || result.reason === "provider-unattested" || result.reason === "provider-protocol"
231
- ? "retryable-infra"
232
- : result.reason === "commit-failure"
233
- ? "commit-failure"
234
- : "unknown";
228
+ : result.reason === "agent-error"
229
+ ? "agent-error"
230
+ : result.reason === "no-handoff"
231
+ ? "no-handoff"
232
+ : result.reason === "no-op" || result.reason === "moved-head" || result.reason === "moved-branch"
233
+ ? "no-op"
234
+ : result.reason === "timeout" || result.reason === "git" || result.reason === "provider-init" || result.reason === "setup" || result.reason === "stopped" || result.reason === "provider-unattested" || result.reason === "provider-protocol"
235
+ ? "retryable-infra"
236
+ : result.reason === "commit-failure"
237
+ ? "commit-failure"
238
+ : "unknown";
235
239
  if (result.reason !== "agent-reported" && result.message.trim() !== "") {
236
240
  store.recordOutcomeFacts(runId, { handoff: result.message });
237
241
  }
242
+ if (result.agentSaid !== undefined && result.agentSaid.length > 0)
243
+ recordAgentSaid(store, runId, result.agentSaid);
238
244
  if (leaseId === undefined) {
239
245
  store.finishRun(runId, { outcome: "failed", reason: result.reason, now: clock() });
240
246
  return { kind: "failed", failureClass, disposition: null, strikes: null, sealed: false, closedState: null };
@@ -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;
@@ -2,7 +2,7 @@ import { spawn } from "node:child_process";
2
2
  import { existsSync, realpathSync } from "node:fs";
3
3
  import { dirname, resolve } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
- import { requestLocalLink } from "./console-instance.js";
5
+ import { instanceSocketTooLong, requestLocalLink } from "./console-instance.js";
6
6
  import { backgroundInstalled, backgroundOn, startInstalledService } from "./laptop-background.js";
7
7
  import { proveConsoleReadOnly } from "./quick-start.js";
8
8
  import { backgroundAsked, installationCreatedBy, localModeCandidate, localModeOf, openStore, openStoreReadOnly, recordBackgroundAsked } from "./store.js";
@@ -32,6 +32,15 @@ export async function runEasyStart(mode, args, seams) {
32
32
  write(`Toolroll can't open: ${first.message}.`);
33
33
  return EXIT.refused;
34
34
  }
35
+ const refusedTooDeep = () => {
36
+ if (first.ok || (args.web && !seams.serviceInstalled()))
37
+ return false;
38
+ const deep = seams.socketProblem();
39
+ if (deep === null)
40
+ return false;
41
+ write(`Toolroll can't start: ${deep}.`);
42
+ return true;
43
+ };
35
44
  const joinRepo = async () => {
36
45
  if (mode !== "start")
37
46
  return EXIT.ok;
@@ -47,6 +56,8 @@ export async function runEasyStart(mode, args, seams) {
47
56
  };
48
57
  let local = seams.localMode();
49
58
  if ((local === "candidate" || local === "absent") && !first.ok && first.state === "none") {
59
+ if (refusedTooDeep())
60
+ return EXIT.refused;
50
61
  const sandbox = await seams.sandbox();
51
62
  if (sandbox.missing.length > 0) {
52
63
  const { missingSandboxToolsWords } = await import("./sandbox-runtime.js");
@@ -59,6 +70,8 @@ export async function runEasyStart(mode, args, seams) {
59
70
  }
60
71
  if (local === "candidate")
61
72
  local = "off";
73
+ if (local !== "off" && refusedTooDeep())
74
+ return EXIT.refused;
62
75
  if (local === "off") {
63
76
  if (seams.passwordByLaptopStart())
64
77
  write(START_OVER_POINTER);
@@ -244,6 +257,7 @@ export function defaultEasyStartSeams(options) {
244
257
  cwd,
245
258
  write: options.write,
246
259
  prove: () => proveConsoleReadOnly(file, options.build),
260
+ socketProblem: () => instanceSocketTooLong(file),
247
261
  localMode: () => localModeRead(file),
248
262
  initLocal: async () => (await import("./operate.js")).easyStartInitLocalMode(file, {
249
263
  stdin: process.stdin.isTTY === true, stdout: process.stdout.isTTY === true, agent: underAgent(process.env), json: false,
@@ -289,6 +303,31 @@ export function defaultEasyStartSeams(options) {
289
303
  openBrowser: async (url) => { (await import("./operate.js")).openBrowser(url); },
290
304
  openSignedIn: () => openLocalSignIn(file, options.build),
291
305
  openTui: async (session) => {
306
+ const { chooseTuiBinary, runTuiBinary } = await import("./tui-launch.js");
307
+ const { engineContractDigest } = await import("./contracts/engine-api.js");
308
+ const choice = chooseTuiBinary({ env: process.env, screenReader: options.screenReader === true, platform: process.platform, arch: process.arch, contract: engineContractDigest(), devBinary: options.tuiBinary ?? null });
309
+ if (choice.notice !== undefined)
310
+ options.write(`${choice.notice}.`);
311
+ let why = choice.ok ? null : choice.why;
312
+ if (choice.ok) {
313
+ const reader = openStoreReadOnly(file);
314
+ const link = reader === null ? { ok: false, message: "Toolroll's database can't be read" }
315
+ : await requestLocalLink(file, reader, options.build).finally(() => reader.close());
316
+ if (!link.ok)
317
+ why = `the terminal workbench couldn't sign in (${link.message})`;
318
+ else {
319
+ const { checkoutTop } = await import("./teardown-git.js");
320
+ const end = await runTuiBinary({ binary: choice.binary, identity: choice.identity, link: link.url, session, project: checkoutTop(cwd), cwd });
321
+ if (end === "changed")
322
+ why = "the terminal workbench changed after it was checked";
323
+ else if (end !== "classic")
324
+ return end;
325
+ else
326
+ why = null;
327
+ }
328
+ }
329
+ if (why !== null)
330
+ options.write(`Opening the classic screen: ${why}.`);
292
331
  const { createTuiSource } = await import("./tui-source.js");
293
332
  const { runAsLocalOwner } = await import("./local-owner.js");
294
333
  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());
@@ -0,0 +1,34 @@
1
+ import { spawn } from "node:child_process";
2
+ export const LINK_FD = 3;
3
+ const LINK = /^http:\/\/(?:127\.0\.0\.1|\[::1\]):[0-9]{1,5}\/login\/once\/[A-Za-z0-9_-]{43}$/;
4
+ export function spawnWithLink(command, args, link, options = {}) {
5
+ const held = spawnHoldingLink(command, args, link, options);
6
+ held.send();
7
+ return held.child;
8
+ }
9
+ export function spawnHoldingLink(command, args, link, options = {}) {
10
+ if (!LINK.test(link))
11
+ throw new Error("not a local one-time sign-in link");
12
+ const code = link.slice(link.lastIndexOf("/") + 1);
13
+ const env = options.env ?? process.env;
14
+ if (args.some(one => one.includes(code)) || Object.entries(env).some(([name, value]) => name.includes(code) || (value ?? "").includes(code))) {
15
+ throw new Error("the sign-in link goes only over the pipe, never in arguments or the environment");
16
+ }
17
+ const [stdin, stdout, stderr] = options.stdio ?? ["inherit", "inherit", "inherit"];
18
+ const child = spawn(command, [...args], { cwd: options.cwd, env, stdio: options.control === true ? [stdin, stdout, stderr, "pipe", "pipe"] : [stdin, stdout, stderr, "pipe"] });
19
+ const pipe = child.stdio[LINK_FD];
20
+ if (pipe === null || pipe === undefined || !("write" in pipe)) {
21
+ child.kill();
22
+ throw new Error("no pipe for the sign-in link");
23
+ }
24
+ pipe.on("error", () => { });
25
+ let sent = false;
26
+ const send = () => {
27
+ if (sent || child.exitCode !== null || child.signalCode !== null)
28
+ return false;
29
+ sent = true;
30
+ pipe.end(`${link}\n`);
31
+ return true;
32
+ };
33
+ return { child, send };
34
+ }