@fitchmultz/pi-subagents 0.0.0-stage → 0.44.5

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 (347) hide show
  1. package/CHANGELOG.md +1654 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1533 -2
  4. package/agents/context-builder.md +97 -0
  5. package/agents/debugger.md +51 -0
  6. package/agents/delegate.md +13 -0
  7. package/agents/fixer.md +37 -0
  8. package/agents/oracle.md +71 -0
  9. package/agents/planner.md +72 -0
  10. package/agents/researcher.md +51 -0
  11. package/agents/reviewer-claude.md +69 -0
  12. package/agents/reviewer-gpt.md +68 -0
  13. package/agents/reviewer-ponytail.md +82 -0
  14. package/agents/reviewer-security.md +81 -0
  15. package/agents/reviewer.md +69 -0
  16. package/agents/scout.md +66 -0
  17. package/agents/ui-designer.md +51 -0
  18. package/agents/watcher.md +26 -0
  19. package/agents/worker.md +46 -0
  20. package/agents/writer.md +36 -0
  21. package/dist/agents/agent-management.js +923 -0
  22. package/dist/agents/agent-scope.js +7 -0
  23. package/dist/agents/agent-selection.js +20 -0
  24. package/dist/agents/agent-serializer.js +100 -0
  25. package/dist/agents/agents.js +752 -0
  26. package/dist/agents/chain-serializer.js +367 -0
  27. package/dist/agents/frontmatter.js +21 -0
  28. package/dist/agents/identity.js +29 -0
  29. package/dist/agents/skills.js +570 -0
  30. package/dist/extension/build-info.js +1 -0
  31. package/dist/extension/compact-tools.js +112 -0
  32. package/dist/extension/config.js +22 -0
  33. package/dist/extension/control-notices.js +29 -0
  34. package/dist/extension/doctor.js +143 -0
  35. package/dist/extension/fanout-child.js +326 -0
  36. package/dist/extension/index.js +577 -0
  37. package/dist/extension/schemas.js +416 -0
  38. package/dist/extension/tool-input.js +20 -0
  39. package/dist/extension/tool-result.js +14 -0
  40. package/dist/history/canonical-result.js +81 -0
  41. package/dist/history/database.js +72 -0
  42. package/dist/history/index.js +199 -0
  43. package/dist/history/ingest.js +468 -0
  44. package/dist/history/queries.js +350 -0
  45. package/dist/history/store.js +216 -0
  46. package/dist/history/types.js +4 -0
  47. package/dist/history/worker.js +466 -0
  48. package/dist/intercom/intercom-bridge.js +112 -0
  49. package/dist/intercom/live-intercom.js +94 -0
  50. package/dist/intercom/result-intercom.js +373 -0
  51. package/dist/pi-intercom/agent-dir.js +10 -0
  52. package/dist/pi-intercom/bridge.js +750 -0
  53. package/dist/pi-intercom/broker/broker.js +426 -0
  54. package/dist/pi-intercom/broker/client.js +492 -0
  55. package/dist/pi-intercom/broker/framing.js +65 -0
  56. package/dist/pi-intercom/broker/paths.js +42 -0
  57. package/dist/pi-intercom/broker/pid.js +66 -0
  58. package/dist/pi-intercom/broker/spawn.js +221 -0
  59. package/dist/pi-intercom/config.js +102 -0
  60. package/dist/pi-intercom/index.js +2942 -0
  61. package/dist/pi-intercom/reply-tracker.js +182 -0
  62. package/dist/pi-intercom/session-targets.js +128 -0
  63. package/dist/pi-intercom/subagent-live-events.js +132 -0
  64. package/dist/pi-intercom/topics.js +157 -0
  65. package/dist/pi-intercom/types.js +163 -0
  66. package/dist/pi-intercom/ui/compose.js +269 -0
  67. package/dist/pi-intercom/ui/inline-message.js +80 -0
  68. package/dist/pi-intercom/ui/session-list.js +124 -0
  69. package/dist/runs/background/async-control.js +95 -0
  70. package/dist/runs/background/async-execution.js +676 -0
  71. package/dist/runs/background/async-job-tracker.js +383 -0
  72. package/dist/runs/background/async-result-file.js +58 -0
  73. package/dist/runs/background/async-resume.js +305 -0
  74. package/dist/runs/background/async-status.js +442 -0
  75. package/dist/runs/background/completion-dedupe.js +69 -0
  76. package/dist/runs/background/completion-delivery.js +245 -0
  77. package/dist/runs/background/notify.js +71 -0
  78. package/dist/runs/background/parallel-groups.js +55 -0
  79. package/dist/runs/background/result-watcher.js +426 -0
  80. package/dist/runs/background/run-id-resolver.js +64 -0
  81. package/dist/runs/background/run-status.js +382 -0
  82. package/dist/runs/background/stale-run-reconciler.js +335 -0
  83. package/dist/runs/background/subagent-runner-launcher.js +55 -0
  84. package/dist/runs/background/subagent-runner.js +1872 -0
  85. package/dist/runs/background/top-level-async.js +5 -0
  86. package/dist/runs/foreground/chain-clarify.js +1152 -0
  87. package/dist/runs/foreground/clarify-invocation.js +72 -0
  88. package/dist/runs/foreground/execution-input.js +423 -0
  89. package/dist/runs/foreground/foreground-control.js +817 -0
  90. package/dist/runs/foreground/question-control.js +88 -0
  91. package/dist/runs/foreground/run-async-path.js +205 -0
  92. package/dist/runs/foreground/subagent-executor.js +442 -0
  93. package/dist/runs/foreground/subagent-params.js +165 -0
  94. package/dist/runs/foreground/wait-run.js +141 -0
  95. package/dist/runs/shared/acceptance-contract.js +253 -0
  96. package/dist/runs/shared/acceptance-evaluation.js +256 -0
  97. package/dist/runs/shared/acceptance-finalization.js +280 -0
  98. package/dist/runs/shared/acceptance-reports.js +147 -0
  99. package/dist/runs/shared/acceptance.js +4 -0
  100. package/dist/runs/shared/chain-outputs.js +110 -0
  101. package/dist/runs/shared/child-attempt.js +693 -0
  102. package/dist/runs/shared/child-execution-cwd.js +96 -0
  103. package/dist/runs/shared/child-observations.js +114 -0
  104. package/dist/runs/shared/claude-code.js +199 -0
  105. package/dist/runs/shared/completion-guard.js +31 -0
  106. package/dist/runs/shared/dynamic-fanout.js +274 -0
  107. package/dist/runs/shared/history-index.js +72 -0
  108. package/dist/runs/shared/mcp-direct-tool-allowlist.js +334 -0
  109. package/dist/runs/shared/model-fallback.js +185 -0
  110. package/dist/runs/shared/mutating-tool-guard.js +170 -0
  111. package/dist/runs/shared/native-finalization.js +101 -0
  112. package/dist/runs/shared/native-usage.js +153 -0
  113. package/dist/runs/shared/nested-events.js +700 -0
  114. package/dist/runs/shared/nested-path.js +48 -0
  115. package/dist/runs/shared/nested-render.js +108 -0
  116. package/dist/runs/shared/parallel-utils.js +61 -0
  117. package/dist/runs/shared/parent-receipts.js +68 -0
  118. package/dist/runs/shared/parent-usage.js +121 -0
  119. package/dist/runs/shared/pi-args.js +310 -0
  120. package/dist/runs/shared/pi-spawn.js +52 -0
  121. package/dist/runs/shared/run-history-queries.js +45 -0
  122. package/dist/runs/shared/run-history.js +110 -0
  123. package/dist/runs/shared/run-id-ambiguity.js +4 -0
  124. package/dist/runs/shared/run-records.js +679 -0
  125. package/dist/runs/shared/session-cwd-preload.js +33 -0
  126. package/dist/runs/shared/single-output.js +222 -0
  127. package/dist/runs/shared/streaming-text.js +15 -0
  128. package/dist/runs/shared/structured-output.js +55 -0
  129. package/dist/runs/shared/subagent-control.js +179 -0
  130. package/dist/runs/shared/subagent-prompt-runtime.js +197 -0
  131. package/dist/runs/shared/subagent-tool-loop-guard.js +66 -0
  132. package/dist/runs/shared/supervisor-questions.js +350 -0
  133. package/dist/runs/shared/workflow-graph.js +214 -0
  134. package/dist/runs/shared/workflow-policy.js +84 -0
  135. package/dist/runs/shared/worktree.js +525 -0
  136. package/dist/shared/agent-context-policy.js +126 -0
  137. package/dist/shared/artifacts.js +96 -0
  138. package/dist/shared/atomic-json.js +13 -0
  139. package/dist/shared/cooperative.js +20 -0
  140. package/dist/shared/execution-cwd.js +14 -0
  141. package/dist/shared/file-coalescer.js +21 -0
  142. package/dist/shared/fork-context.js +49 -0
  143. package/dist/shared/formatters.js +85 -0
  144. package/dist/shared/journal-reader.js +407 -0
  145. package/dist/shared/lazy-tools.js +32 -0
  146. package/dist/shared/model-info.js +68 -0
  147. package/dist/shared/native-session.js +15 -0
  148. package/dist/shared/native-tui.js +18 -0
  149. package/dist/shared/native-typebox.js +20 -0
  150. package/dist/shared/post-exit-stdio-guard.js +197 -0
  151. package/dist/shared/prompt-sections.js +8 -0
  152. package/dist/shared/session-entries.js +52 -0
  153. package/dist/shared/session-identity.js +14 -0
  154. package/dist/shared/settings.js +254 -0
  155. package/dist/shared/status-format.js +111 -0
  156. package/dist/shared/temp-root.js +114 -0
  157. package/dist/shared/types.js +207 -0
  158. package/dist/shared/ui-mode.js +3 -0
  159. package/dist/shared/utils.js +334 -0
  160. package/dist/slash/prompt-template-bridge.js +298 -0
  161. package/dist/slash/slash-bridge.js +116 -0
  162. package/dist/slash/slash-commands.js +607 -0
  163. package/dist/slash/slash-live-state.js +246 -0
  164. package/dist/tui/action-hints.js +75 -0
  165. package/dist/tui/agent-history.js +197 -0
  166. package/dist/tui/agent-view.js +1656 -0
  167. package/dist/tui/render.js +1515 -0
  168. package/docs/intercom-bridge.md +212 -0
  169. package/docs/intercom.md +581 -0
  170. package/docs/performance.md +121 -0
  171. package/package.json +102 -4
  172. package/prompts/gather-context-and-clarify.md +14 -0
  173. package/prompts/parallel-cleanup.md +62 -0
  174. package/prompts/parallel-context-build.md +56 -0
  175. package/prompts/parallel-handoff-plan.md +62 -0
  176. package/prompts/parallel-research.md +51 -0
  177. package/prompts/parallel-review.md +59 -0
  178. package/prompts/review-loop.md +42 -0
  179. package/scripts/build.mjs +134 -0
  180. package/scripts/check-compat.mjs +48 -0
  181. package/scripts/compat-host.mjs +19 -0
  182. package/scripts/intercom-bridge-credentials.mjs +143 -0
  183. package/scripts/intercom-remote.mjs +103 -0
  184. package/scripts/linux-smoke.sh +51 -0
  185. package/scripts/local-install-smoke.mjs +66 -0
  186. package/scripts/native-package-smoke.mjs +82 -0
  187. package/scripts/package-smoke.mjs +209 -0
  188. package/scripts/prepare.mjs +67 -0
  189. package/scripts/real-pi-smoke.mjs +415 -0
  190. package/scripts/run-tests.mjs +149 -0
  191. package/skills/pi-intercom/SKILL.md +113 -0
  192. package/skills/pi-intercom/evals/evals.json +29 -0
  193. package/skills/pi-intercom/evals/trigger-evals.json +47 -0
  194. package/skills/pi-intercom/references/peer-sessions.md +69 -0
  195. package/skills/pi-subagents/SKILL.md +76 -0
  196. package/skills/pi-subagents/evals/evals.json +29 -0
  197. package/skills/pi-subagents/evals/trigger-evals.json +42 -0
  198. package/skills/pi-subagents/references/full-orchestration-guide.md +863 -0
  199. package/src/agents/agent-management.ts +813 -0
  200. package/src/agents/agent-scope.ts +7 -0
  201. package/src/agents/agent-selection.ts +23 -0
  202. package/src/agents/agent-serializer.ts +99 -0
  203. package/src/agents/agents.ts +916 -0
  204. package/src/agents/chain-serializer.ts +329 -0
  205. package/src/agents/frontmatter.ts +21 -0
  206. package/src/agents/identity.ts +30 -0
  207. package/src/agents/skills.ts +637 -0
  208. package/src/extension/build-info.ts +2 -0
  209. package/src/extension/compact-tools.ts +114 -0
  210. package/src/extension/config.ts +23 -0
  211. package/src/extension/control-notices.ts +47 -0
  212. package/src/extension/doctor.ts +171 -0
  213. package/src/extension/fanout-child.ts +312 -0
  214. package/src/extension/index.ts +649 -0
  215. package/src/extension/schemas.ts +444 -0
  216. package/src/extension/tool-input.ts +19 -0
  217. package/src/extension/tool-result.ts +16 -0
  218. package/src/history/canonical-result.ts +62 -0
  219. package/src/history/database.ts +59 -0
  220. package/src/history/index.ts +156 -0
  221. package/src/history/ingest.ts +349 -0
  222. package/src/history/queries.ts +241 -0
  223. package/src/history/store.ts +203 -0
  224. package/src/history/types.ts +166 -0
  225. package/src/history/worker.ts +321 -0
  226. package/src/intercom/intercom-bridge.ts +123 -0
  227. package/src/intercom/live-intercom.ts +104 -0
  228. package/src/intercom/result-intercom.ts +429 -0
  229. package/src/pi-intercom/agent-dir.ts +9 -0
  230. package/src/pi-intercom/bridge.ts +668 -0
  231. package/src/pi-intercom/broker/broker.ts +463 -0
  232. package/src/pi-intercom/broker/client.ts +558 -0
  233. package/src/pi-intercom/broker/framing.ts +77 -0
  234. package/src/pi-intercom/broker/paths.ts +47 -0
  235. package/src/pi-intercom/broker/pid.ts +59 -0
  236. package/src/pi-intercom/broker/spawn.ts +248 -0
  237. package/src/pi-intercom/config.ts +142 -0
  238. package/src/pi-intercom/index.ts +2929 -0
  239. package/src/pi-intercom/reply-tracker.ts +211 -0
  240. package/src/pi-intercom/session-targets.ts +172 -0
  241. package/src/pi-intercom/subagent-live-events.ts +133 -0
  242. package/src/pi-intercom/topics.ts +125 -0
  243. package/src/pi-intercom/types.ts +271 -0
  244. package/src/pi-intercom/ui/compose.ts +289 -0
  245. package/src/pi-intercom/ui/inline-message.ts +92 -0
  246. package/src/pi-intercom/ui/session-list.ts +139 -0
  247. package/src/runs/background/async-control.ts +89 -0
  248. package/src/runs/background/async-execution.ts +850 -0
  249. package/src/runs/background/async-job-tracker.ts +385 -0
  250. package/src/runs/background/async-result-file.ts +62 -0
  251. package/src/runs/background/async-resume.ts +333 -0
  252. package/src/runs/background/async-status.ts +481 -0
  253. package/src/runs/background/completion-dedupe.ts +79 -0
  254. package/src/runs/background/completion-delivery.ts +195 -0
  255. package/src/runs/background/notify.ts +123 -0
  256. package/src/runs/background/parallel-groups.ts +53 -0
  257. package/src/runs/background/result-watcher.ts +423 -0
  258. package/src/runs/background/run-id-resolver.ts +69 -0
  259. package/src/runs/background/run-status.ts +384 -0
  260. package/src/runs/background/stale-run-reconciler.ts +369 -0
  261. package/src/runs/background/subagent-runner-launcher.ts +56 -0
  262. package/src/runs/background/subagent-runner.ts +2053 -0
  263. package/src/runs/background/top-level-async.ts +13 -0
  264. package/src/runs/foreground/chain-clarify.ts +1340 -0
  265. package/src/runs/foreground/clarify-invocation.ts +77 -0
  266. package/src/runs/foreground/execution-input.ts +467 -0
  267. package/src/runs/foreground/foreground-control.ts +821 -0
  268. package/src/runs/foreground/question-control.ts +82 -0
  269. package/src/runs/foreground/run-async-path.ts +243 -0
  270. package/src/runs/foreground/subagent-executor.ts +501 -0
  271. package/src/runs/foreground/subagent-params.ts +320 -0
  272. package/src/runs/foreground/wait-run.ts +124 -0
  273. package/src/runs/shared/acceptance-contract.ts +257 -0
  274. package/src/runs/shared/acceptance-evaluation.ts +275 -0
  275. package/src/runs/shared/acceptance-finalization.ts +353 -0
  276. package/src/runs/shared/acceptance-reports.ts +152 -0
  277. package/src/runs/shared/acceptance.ts +33 -0
  278. package/src/runs/shared/chain-outputs.ts +114 -0
  279. package/src/runs/shared/child-attempt.ts +623 -0
  280. package/src/runs/shared/child-execution-cwd.ts +91 -0
  281. package/src/runs/shared/child-observations.ts +99 -0
  282. package/src/runs/shared/claude-code.ts +243 -0
  283. package/src/runs/shared/completion-guard.ts +35 -0
  284. package/src/runs/shared/dynamic-fanout.ts +295 -0
  285. package/src/runs/shared/history-index.ts +69 -0
  286. package/src/runs/shared/mcp-direct-tool-allowlist.ts +376 -0
  287. package/src/runs/shared/model-fallback.ts +219 -0
  288. package/src/runs/shared/mutating-tool-guard.ts +194 -0
  289. package/src/runs/shared/native-finalization.ts +128 -0
  290. package/src/runs/shared/native-usage.ts +113 -0
  291. package/src/runs/shared/nested-events.ts +752 -0
  292. package/src/runs/shared/nested-path.ts +52 -0
  293. package/src/runs/shared/nested-render.ts +119 -0
  294. package/src/runs/shared/parallel-utils.ts +153 -0
  295. package/src/runs/shared/parent-receipts.ts +59 -0
  296. package/src/runs/shared/parent-usage.ts +121 -0
  297. package/src/runs/shared/pi-args.ts +350 -0
  298. package/src/runs/shared/pi-spawn.ts +52 -0
  299. package/src/runs/shared/run-history-queries.ts +44 -0
  300. package/src/runs/shared/run-history.ts +100 -0
  301. package/src/runs/shared/run-id-ambiguity.ts +4 -0
  302. package/src/runs/shared/run-records.ts +607 -0
  303. package/src/runs/shared/session-cwd-preload.ts +27 -0
  304. package/src/runs/shared/single-output.ts +267 -0
  305. package/src/runs/shared/streaming-text.ts +18 -0
  306. package/src/runs/shared/structured-output.ts +68 -0
  307. package/src/runs/shared/subagent-control.ts +219 -0
  308. package/src/runs/shared/subagent-prompt-runtime.ts +201 -0
  309. package/src/runs/shared/subagent-tool-loop-guard.ts +89 -0
  310. package/src/runs/shared/supervisor-questions.ts +415 -0
  311. package/src/runs/shared/workflow-graph.ts +220 -0
  312. package/src/runs/shared/workflow-policy.ts +125 -0
  313. package/src/runs/shared/worktree.ts +635 -0
  314. package/src/shared/agent-context-policy.ts +184 -0
  315. package/src/shared/artifacts.ts +95 -0
  316. package/src/shared/atomic-json.ts +16 -0
  317. package/src/shared/cooperative.ts +21 -0
  318. package/src/shared/execution-cwd.ts +14 -0
  319. package/src/shared/file-coalescer.ts +29 -0
  320. package/src/shared/fork-context.ts +68 -0
  321. package/src/shared/formatters.ts +84 -0
  322. package/src/shared/journal-reader.ts +333 -0
  323. package/src/shared/lazy-tools.ts +36 -0
  324. package/src/shared/model-info.ts +81 -0
  325. package/src/shared/native-session.ts +8 -0
  326. package/src/shared/native-tui.ts +10 -0
  327. package/src/shared/native-typebox.ts +14 -0
  328. package/src/shared/post-exit-stdio-guard.ts +204 -0
  329. package/src/shared/prompt-sections.ts +10 -0
  330. package/src/shared/session-entries.ts +49 -0
  331. package/src/shared/session-identity.ts +18 -0
  332. package/src/shared/settings.ts +384 -0
  333. package/src/shared/status-format.ts +123 -0
  334. package/src/shared/temp-root.ts +107 -0
  335. package/src/shared/types.ts +1260 -0
  336. package/src/shared/ui-mode.ts +5 -0
  337. package/src/shared/utils.ts +342 -0
  338. package/src/slash/prompt-template-bridge.ts +408 -0
  339. package/src/slash/slash-bridge.ts +178 -0
  340. package/src/slash/slash-commands.ts +617 -0
  341. package/src/slash/slash-live-state.ts +292 -0
  342. package/src/tui/action-hints.ts +69 -0
  343. package/src/tui/agent-history.ts +210 -0
  344. package/src/tui/agent-view.ts +1323 -0
  345. package/src/tui/render.ts +1550 -0
  346. package/tsconfig.build.json +12 -0
  347. package/tsconfig.json +19 -0
@@ -0,0 +1,668 @@
1
+ import { constants, closeSync, fstatSync, openSync, readFileSync, statSync } from "node:fs";
2
+ import { createServer, type Server } from "node:https";
3
+ import type { IncomingMessage, ServerResponse } from "node:http";
4
+ import type { Socket } from "node:net";
5
+ import { isAbsolute, resolve } from "node:path";
6
+ import { createSecureContext, type TLSSocket } from "node:tls";
7
+ import { randomUUID } from "node:crypto";
8
+ import { IntercomClient } from "./broker/client.ts";
9
+ import { getBrokerSocketPath } from "./broker/paths.ts";
10
+ import { formatSessionTarget, resolveSessionProjectId, resolveSessionTarget } from "./session-targets.ts";
11
+ import type { Message, SendResult, SessionInfo } from "./types.ts";
12
+
13
+ const BODY_LIMIT = 64 * 1024;
14
+ const SEND_TIMEOUT = 8000;
15
+ const LIST_TIMEOUT = 5000;
16
+ const ASK_TIMEOUT = 120000;
17
+ const IDLE_TIMEOUT = 5 * 60 * 1000;
18
+ const MAX_CLIENTS = 64;
19
+ const MAX_CONNECTIONS = 128;
20
+ const MAX_REQUESTS = 8;
21
+ const INBOX_COUNT = 256;
22
+ const INBOX_BYTES = 4 * 1024 * 1024;
23
+ const LABEL_CONTROLS = /[\u0000-\u001f\u007f-\u009f]/;
24
+ const TEXT_CONTROLS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/;
25
+
26
+ class Fault extends Error {
27
+ readonly status: number;
28
+ readonly code: string;
29
+ readonly details: Record<string, unknown>;
30
+ constructor(status: number, code: string, message: string, details: Record<string, unknown> = {}) {
31
+ super(message);
32
+ this.status = status;
33
+ this.code = code;
34
+ this.details = details;
35
+ }
36
+ }
37
+
38
+ interface Identity { fingerprint256: string; name: string; cwd: string }
39
+ interface Config {
40
+ port: number;
41
+ ca: string;
42
+ cert: string;
43
+ key: string;
44
+ clients: Map<string, Identity>;
45
+ tls: { ca: Buffer; cert: Buffer; key: Buffer };
46
+ }
47
+ interface Envelope { from: SessionInfo; message: Message }
48
+ interface InboxEntry extends Envelope { bytes: number; replying: boolean }
49
+ interface Connection { fingerprint: string; expires: number; timer: NodeJS.Timeout }
50
+ interface WaitingAsk { id: string; peer?: string; settled: boolean; resolve: (reply: Envelope) => void; reject: (error: Fault) => void }
51
+
52
+ function object(value: unknown, fields: string[]): Record<string, unknown> {
53
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Fault(400, "invalid_input", "Expected a JSON object.");
54
+ const result = value as Record<string, unknown>;
55
+ if (Object.keys(result).some((key) => !fields.includes(key))) throw new Fault(400, "invalid_input", "Unknown field.");
56
+ return result;
57
+ }
58
+
59
+ function label(value: unknown, field: string, max = 512): string {
60
+ if (typeof value !== "string" || !value.trim() || value.length > max || LABEL_CONTROLS.test(value)) {
61
+ throw new Fault(400, "invalid_input", `Invalid ${field}.`);
62
+ }
63
+ return value;
64
+ }
65
+
66
+ function text(value: unknown): string {
67
+ if (typeof value !== "string" || !value.trim() || TEXT_CONTROLS.test(value)) throw new Fault(400, "invalid_input", "Invalid message.");
68
+ return value;
69
+ }
70
+
71
+ function fingerprint(value: unknown): string {
72
+ if (typeof value !== "string" || !/^(?:[a-fA-F0-9]{64}|(?:[a-fA-F0-9]{2}:){31}[a-fA-F0-9]{2})$/.test(value)) {
73
+ throw new Fault(400, "invalid_input", "Invalid SHA256 certificate fingerprint.");
74
+ }
75
+ return value.replaceAll(":", "").toUpperCase();
76
+ }
77
+
78
+ function readFile(path: string, privateFile: boolean, limit: number): Buffer {
79
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
80
+ try {
81
+ const stat = fstatSync(fd);
82
+ if (!stat.isFile() || stat.size > limit) throw new Error("Configuration/TLS file must be a bounded regular file.");
83
+ if (privateFile && (stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600)) {
84
+ throw new Error("Config and TLS key must be owned by the current user with mode 0600.");
85
+ }
86
+ const data = readFileSync(fd);
87
+ if (data.length > limit) throw new Error("Configuration/TLS file exceeds its size limit.");
88
+ return data;
89
+ } finally {
90
+ closeSync(fd);
91
+ }
92
+ }
93
+
94
+ function loadConfig(path: string): Config {
95
+ const input = object(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(readFile(path, true, BODY_LIMIT))), ["port", "ca", "cert", "key", "clients"]);
96
+ const port = input.port === undefined ? 9443 : input.port;
97
+ if (!Number.isInteger(port) || typeof port !== "number" || port < 0 || port > 65535) throw new Error("Invalid HTTPS port.");
98
+ const ca = label(input.ca, "ca path", 4096);
99
+ const cert = label(input.cert, "cert path", 4096);
100
+ const key = label(input.key, "key path", 4096);
101
+ if (![ca, cert, key].every(isAbsolute)) throw new Error("TLS paths must be absolute.");
102
+ if (!Array.isArray(input.clients) || input.clients.length > MAX_CLIENTS) throw new Error(`clients must be an array of at most ${MAX_CLIENTS} identities.`);
103
+ const clients = new Map<string, Identity>();
104
+ const names = new Set<string>();
105
+ for (const raw of input.clients) {
106
+ const entry = object(raw, ["fingerprint256", "name", "cwd"]);
107
+ const fingerprint256 = fingerprint(entry.fingerprint256);
108
+ const name = label(entry.name, "name", 128).trim();
109
+ const cwd = label(entry.cwd, "cwd", 4096);
110
+ if (!isAbsolute(cwd) || !statSync(cwd).isDirectory()) throw new Error("Client cwd must be an existing absolute directory.");
111
+ if (clients.has(fingerprint256) || names.has(name.toLowerCase())) throw new Error("Client fingerprints and names must be unique.");
112
+ clients.set(fingerprint256, { fingerprint256, name, cwd });
113
+ names.add(name.toLowerCase());
114
+ }
115
+ const tls = { ca: readFile(ca, false, 1024 * 1024), cert: readFile(cert, false, 1024 * 1024), key: readFile(key, true, 1024 * 1024) };
116
+ createSecureContext({ ...tls, minVersion: "TLSv1.2" });
117
+ return { port, ca, cert, key, clients, tls };
118
+ }
119
+
120
+ let logBackpressure = false;
121
+ let lostLogEvents = 0;
122
+ function log(event: string, fields: Record<string, unknown> = {}): void {
123
+ if (logBackpressure) { lostLogEvents = Math.min(Number.MAX_SAFE_INTEGER, lostLogEvents + 1); return; }
124
+ logBackpressure = !process.stdout.write(`${JSON.stringify({ timestamp: new Date().toISOString(), event, ...fields })}\n`);
125
+ if (logBackpressure) process.stdout.once("drain", () => {
126
+ logBackpressure = false;
127
+ if (lostLogEvents) {
128
+ const lostEvents = lostLogEvents;
129
+ lostLogEvents = 0;
130
+ log("log_overflow", { result: "metadata_lost", lostEvents });
131
+ }
132
+ });
133
+ }
134
+
135
+ function cancelled(signal: AbortSignal): void {
136
+ if (signal.aborted) throw signal.reason;
137
+ }
138
+
139
+ function wait<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
140
+ if (signal.aborted) {
141
+ void promise.catch(() => {});
142
+ throw signal.reason;
143
+ }
144
+ return new Promise((resolve, reject) => {
145
+ const abort = () => { cleanup(); reject(signal.reason); };
146
+ const cleanup = () => signal.removeEventListener("abort", abort);
147
+ signal.addEventListener("abort", abort, { once: true });
148
+ promise.then((value) => { cleanup(); resolve(value); }, (error: unknown) => { cleanup(); reject(error); });
149
+ });
150
+ }
151
+
152
+ async function body(req: IncomingMessage, signal: AbortSignal): Promise<unknown> {
153
+ const type = req.headers["content-type"];
154
+ if (typeof type !== "string" || !/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(type)) throw new Fault(415, "content_type", "Use application/json.");
155
+ const length = req.headers["content-length"];
156
+ if (length !== undefined && (!/^\d+$/.test(length) || Number(length) > BODY_LIMIT)) throw new Fault(413, "body_too_large", "JSON body exceeds 64 KiB.");
157
+ const data = await new Promise<Buffer>((resolve, reject) => {
158
+ const chunks: Buffer[] = [];
159
+ let size = 0;
160
+ const cleanup = () => {
161
+ clearTimeout(timer);
162
+ req.off("data", onData);
163
+ req.off("end", onEnd);
164
+ req.off("error", onError);
165
+ signal.removeEventListener("abort", onAbort);
166
+ };
167
+ const fail = (error: unknown) => { cleanup(); req.pause(); reject(error); };
168
+ const onAbort = () => fail(signal.reason);
169
+ const onError = () => fail(new Fault(400, "invalid_body", "Could not read JSON body."));
170
+ const onData = (chunk: Buffer) => {
171
+ size += chunk.length;
172
+ if (size > BODY_LIMIT) { fail(new Fault(413, "body_too_large", "JSON body exceeds 64 KiB.")); return; }
173
+ chunks.push(chunk);
174
+ };
175
+ const onEnd = () => { cleanup(); resolve(Buffer.concat(chunks)); };
176
+ const timer = setTimeout(() => fail(new Fault(408, "body_timeout", "JSON body deadline exceeded.")), 10000);
177
+ signal.addEventListener("abort", onAbort, { once: true });
178
+ req.on("data", onData);
179
+ req.once("end", onEnd);
180
+ req.once("error", onError);
181
+ if (signal.aborted) onAbort();
182
+ });
183
+ try { return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(data)) as unknown; }
184
+ catch { throw new Fault(400, "invalid_json", "Invalid UTF-8 JSON body."); }
185
+ }
186
+
187
+ class Session {
188
+ readonly bridge: Bridge;
189
+ readonly identity: Identity;
190
+ readonly expires: number;
191
+ readonly client = new IntercomClient({ sendTimeoutMs: SEND_TIMEOUT, listTimeoutMs: LIST_TIMEOUT });
192
+ readonly requests = new Set<AbortController>();
193
+ readonly inbox = new Map<string, InboxEntry>();
194
+ inboxBytes = 0;
195
+ pending?: WaitingAsk;
196
+ closed = false;
197
+ private connecting?: Promise<void>;
198
+ private disconnecting?: Promise<void>;
199
+ private lease?: NodeJS.Timeout;
200
+ private closeReason?: Fault;
201
+
202
+ constructor(bridge: Bridge, identity: Identity, expires: number) {
203
+ this.bridge = bridge;
204
+ this.identity = identity;
205
+ this.expires = expires;
206
+ this.client.on("error", () => this.close(new Fault(503, "broker_unavailable", "Broker connection failed.")));
207
+ this.client.on("disconnected", () => this.close(new Fault(503, "broker_disconnected", "Broker disconnected.")));
208
+ this.client.on("_registered", () => {
209
+ // IntercomClient cannot abort socket acquisition; retire a cancelled generation before any application write.
210
+ if (this.closed) void this.disconnect();
211
+ });
212
+ this.client.on("message", (from: SessionInfo, message: Message) => this.receive(from, message));
213
+ this.client.on("session_left", (id: string) => {
214
+ if (this.pending?.peer === id && !this.pending.settled) this.pending.reject(new Fault(409, "peer_offline", "Ask recipient disconnected.", { id: this.pending.id }));
215
+ for (const [messageId, entry] of this.inbox) {
216
+ if (entry.from.id === id && entry.message.expectsReply) { this.remove(messageId); this.bridge.lost(this.identity.fingerprint256); }
217
+ }
218
+ this.presence();
219
+ });
220
+ this.touch();
221
+ }
222
+
223
+ guard(signal?: AbortSignal): void {
224
+ if (signal) cancelled(signal);
225
+ if (this.closed) throw this.closeReason;
226
+ if (!this.bridge.allowed(this.identity)) throw new Fault(403, "revoked", "Identity is no longer authorized.");
227
+ if (this.expires <= Date.now()) {
228
+ const error = new Fault(403, "certificate_expired", "Client certificate expired.");
229
+ this.close(error);
230
+ throw error;
231
+ }
232
+ }
233
+
234
+ touch(): void {
235
+ clearTimeout(this.lease);
236
+ this.lease = setTimeout(() => this.close(this.expires <= Date.now()
237
+ ? new Fault(403, "certificate_expired", "Client certificate expired.")
238
+ : new Fault(410, "lease_expired", "Bridge session idle lease expired.")), Math.max(1, Math.min(IDLE_TIMEOUT, this.expires - Date.now())));
239
+ }
240
+
241
+ async connect(signal: AbortSignal): Promise<void> {
242
+ this.guard(signal);
243
+ if (!this.connecting) {
244
+ this.connecting = (async () => {
245
+ const projectId = await resolveSessionProjectId(this.identity.cwd);
246
+ this.guard();
247
+ await this.client.connect({ name: this.identity.name, cwd: this.identity.cwd, model: "remote-bridge", projectId, status: "idle", acceptsAsks: true, pendingAsks: 0 }, `remote-${this.identity.fingerprint256.toLowerCase()}`);
248
+ if (this.closed) { await this.disconnect(); return; }
249
+ if (this.client.sessionId !== `remote-${this.identity.fingerprint256.toLowerCase()}`) {
250
+ this.close(new Fault(409, "identity_in_use", "This remote identity is already registered by another connection."));
251
+ throw new Fault(409, "identity_in_use", "This remote identity is already registered by another connection.");
252
+ }
253
+ log("registered", this.fields());
254
+ })().catch((error: unknown) => {
255
+ if (!this.closed) this.close(error instanceof Fault ? error : new Fault(503, "broker_unavailable", "Local broker is unavailable; bridge does not start it."));
256
+ throw error;
257
+ }).finally(() => { if (this.closed) void this.disconnect(); });
258
+ }
259
+ await wait(this.connecting, signal);
260
+ this.guard(signal);
261
+ }
262
+
263
+ fields(): Record<string, unknown> { return { name: this.identity.name, fingerprint: this.identity.fingerprint256 }; }
264
+
265
+ private disconnect(): Promise<void> {
266
+ if (!this.disconnecting) {
267
+ this.disconnecting = this.client.disconnect().finally(() => { this.disconnecting = undefined; });
268
+ }
269
+ return this.disconnecting;
270
+ }
271
+
272
+ close(error: Fault): void {
273
+ if (this.closed) return;
274
+ this.closed = true;
275
+ this.closeReason = error;
276
+ clearTimeout(this.lease);
277
+ this.pending?.reject(error);
278
+ for (const controller of this.requests) controller.abort(error);
279
+ this.bridge.lost(this.identity.fingerprint256, this.inbox.size);
280
+ this.inbox.clear();
281
+ this.inboxBytes = 0;
282
+ // Keep the retiring generation in the map until socket acquisition/registration has settled.
283
+ // Otherwise rapid aborts could create an unbounded number of unfinished broker connects.
284
+ const disconnect = this.disconnect();
285
+ void (async () => {
286
+ await disconnect;
287
+ try { await this.connecting; } catch { /* The original request receives the connect failure. */ }
288
+ await this.disconnect();
289
+ if (this.bridge.sessions.get(this.identity.fingerprint256) === this) this.bridge.sessions.delete(this.identity.fingerprint256);
290
+ })();
291
+ log("session_closed", { ...this.fields(), result: error.code });
292
+ }
293
+
294
+ private receive(from: SessionInfo, message: Message): void {
295
+ if (this.closed) return;
296
+ try { this.guard(); } catch (error) {
297
+ this.close(error instanceof Fault ? error : new Fault(403, "revoked", "Identity is no longer authorized."));
298
+ return;
299
+ }
300
+ log("received", { ...this.fields(), peer: from.id, messageId: message.id, result: "received" });
301
+ const pending = this.pending;
302
+ if (pending && !pending.settled && pending.id === message.replyTo && pending.peer === from.id) {
303
+ pending.resolve({ from, message });
304
+ return;
305
+ }
306
+ if (this.inbox.has(message.id)) { this.bridge.lost(this.identity.fingerprint256); return; }
307
+ const bytes = Buffer.byteLength(JSON.stringify({ from, message }));
308
+ if (this.inbox.size >= INBOX_COUNT || this.inboxBytes + bytes > INBOX_BYTES) {
309
+ this.bridge.lost(this.identity.fingerprint256);
310
+ log("inbox_overflow", { ...this.fields(), peer: from.id, messageId: message.id, result: "lost" });
311
+ return;
312
+ }
313
+ // ponytail: inbox is bounded and volatile; use a private durable journal if restart/lease-loss recovery becomes required.
314
+ this.inbox.set(message.id, { from, message, bytes, replying: false });
315
+ this.inboxBytes += bytes;
316
+ this.presence();
317
+ }
318
+
319
+ remove(id: string): void {
320
+ const entry = this.inbox.get(id);
321
+ if (entry) { this.inboxBytes -= entry.bytes; this.inbox.delete(id); }
322
+ }
323
+
324
+ presence(): void {
325
+ if (this.closed) return;
326
+ const pendingAsks = [...this.inbox.values()].filter((entry) => entry.message.expectsReply).length;
327
+ this.client.updatePresence({ pendingAsks, acceptsAsks: this.inbox.size < INBOX_COUNT && this.inboxBytes < INBOX_BYTES });
328
+ }
329
+
330
+ async peers(signal: AbortSignal): Promise<SessionInfo[]> {
331
+ this.guard(signal);
332
+ let peers: SessionInfo[];
333
+ try { peers = await wait(this.client.listSessions(), signal); }
334
+ catch (error) {
335
+ if (signal.aborted) throw signal.reason;
336
+ if (error instanceof Error && error.message === "List sessions timeout") throw new Fault(504, "list_timeout", "Broker session list deadline exceeded.");
337
+ throw new Fault(503, "broker_unavailable", "Broker session list failed.");
338
+ }
339
+ this.guard(signal);
340
+ return peers;
341
+ }
342
+
343
+ async target(to: string, signal: AbortSignal): Promise<SessionInfo> {
344
+ const resolution = resolveSessionTarget(await this.peers(signal), to);
345
+ if (resolution.status === "none") throw new Fault(404, "peer_offline", "Peer is not connected.");
346
+ if (resolution.status !== "found" || !resolution.target) throw new Fault(409, "ambiguous_target", "Use an unambiguous peer name or session ID (prefixes need at least 8 characters).");
347
+ if (resolution.target.id === this.client.sessionId) throw new Fault(400, "self_target", "Choose another peer.");
348
+ return resolution.target;
349
+ }
350
+
351
+ async send(peer: string, message: string, signal: AbortSignal, requestId: string, options: { messageId?: string; replyTo?: string; expectsReply?: boolean } = {}): Promise<SendResult> {
352
+ this.guard(signal);
353
+ const id = options.messageId ?? randomUUID();
354
+ log("send", { ...this.fields(), requestId, peer, messageId: id, result: "attempt" });
355
+ let result: SendResult;
356
+ try { result = await wait(this.client.send(peer, { text: message, delivery: "steer", ...options, messageId: id }), signal); }
357
+ catch (error) {
358
+ if (signal.aborted) throw signal.reason;
359
+ const fault = new Fault(504, "send_unconfirmed", "Broker acknowledgement was not received; delivery is unknown. Do not automatically retry.", { id, deliveryUnknown: true });
360
+ this.close(fault);
361
+ throw fault;
362
+ }
363
+ this.guard(signal);
364
+ log("send_result", { ...this.fields(), requestId, peer, messageId: id, result: result.accepted ? "accepted" : "rejected" });
365
+ if (!result.accepted) throw new Fault(409, "delivery_failed", result.reason ?? "Broker rejected delivery.", { id, accepted: false, delivered: false });
366
+ return result;
367
+ }
368
+
369
+ async ask(to: string, message: string, timeoutMs: number, signal: AbortSignal, requestId: string): Promise<Record<string, unknown>> {
370
+ if (this.pending) throw new Fault(409, "ask_in_progress", "Only one concurrent ask is allowed per identity.");
371
+ const id = randomUUID();
372
+ let waiting!: WaitingAsk;
373
+ let timer: NodeJS.Timeout | undefined;
374
+ let receipt: SendResult | undefined;
375
+ const reply = new Promise<Envelope>((resolve, reject) => {
376
+ waiting = { id, settled: false,
377
+ resolve: (answer) => { waiting.settled = true; clearTimeout(timer); resolve(answer); },
378
+ reject: (error) => { waiting.settled = true; clearTimeout(timer); reject(error); },
379
+ };
380
+ });
381
+ // A disconnect may reject the reply while target lookup or send acknowledgement is still pending.
382
+ void reply.catch(() => {});
383
+ this.pending = waiting;
384
+ const abort = () => waiting.reject(signal.reason as Fault);
385
+ signal.addEventListener("abort", abort, { once: true });
386
+ try {
387
+ await this.connect(signal);
388
+ const peer = await this.target(to, signal);
389
+ this.guard(signal);
390
+ waiting.peer = peer.id;
391
+ timer = setTimeout(() => {
392
+ const fault = new Fault(504, "ask_timeout", "Peer did not reply before the ask deadline.", { id, ...(receipt ? { accepted: receipt.accepted, delivered: receipt.delivered } : { deliveryUnknown: true }) });
393
+ if (receipt) waiting.reject(fault);
394
+ else this.close(fault);
395
+ }, timeoutMs);
396
+ receipt = await this.send(peer.id, message, signal, requestId, { messageId: id, expectsReply: true });
397
+ const answer = await wait(reply, signal);
398
+ this.guard(signal);
399
+ return { ...receipt, replied: true, reply: answer };
400
+ } finally {
401
+ clearTimeout(timer);
402
+ signal.removeEventListener("abort", abort);
403
+ if (this.pending === waiting) this.pending = undefined;
404
+ }
405
+ }
406
+ }
407
+
408
+ class Bridge {
409
+ private config: Config;
410
+ private readonly configPath: string;
411
+ readonly sessions = new Map<string, Session>();
412
+ private readonly losses = new Map<string, number>();
413
+ private readonly sockets = new Set<Socket>();
414
+ private readonly connections = new Map<TLSSocket, Connection>();
415
+ private readonly server: Server;
416
+ private stopping = false;
417
+
418
+ constructor(config: Config, configPath: string) {
419
+ this.config = config;
420
+ this.configPath = configPath;
421
+ this.server = createServer({ ...config.tls, minVersion: "TLSv1.2", requestCert: true, rejectUnauthorized: true, handshakeTimeout: 10000 }, (req, res) => { void this.handle(req, res); });
422
+ this.server.maxConnections = MAX_CONNECTIONS;
423
+ this.server.requestTimeout = 10000;
424
+ this.server.headersTimeout = 10000;
425
+ this.server.keepAliveTimeout = 5000;
426
+ this.server.maxRequestsPerSocket = 100;
427
+ this.server.maxHeadersCount = 32;
428
+ this.server.on("connection", (socket: Socket) => {
429
+ if (this.stopping || this.sockets.size >= MAX_CONNECTIONS) { socket.destroy(); return; }
430
+ this.sockets.add(socket);
431
+ socket.once("close", () => this.sockets.delete(socket));
432
+ });
433
+ this.server.on("secureConnection", (socket: TLSSocket) => this.authenticate(socket));
434
+ this.server.on("tlsClientError", () => log("connection_rejected", { result: "tls_authentication_failed" }));
435
+ this.server.on("clientError", (_error, socket) => socket.destroy());
436
+ this.server.on("error", () => { log("server_error", { result: "listener_failed" }); process.exitCode = 1; this.shutdown(); });
437
+ }
438
+
439
+ allowed(identity: Identity): boolean {
440
+ const current = this.config.clients.get(identity.fingerprint256);
441
+ return !this.stopping && current?.name === identity.name && current.cwd === identity.cwd;
442
+ }
443
+
444
+ lost(fp: string, count = 1): void {
445
+ if (count && this.config.clients.has(fp)) this.losses.set(fp, Math.min(Number.MAX_SAFE_INTEGER, (this.losses.get(fp) ?? 0) + count));
446
+ }
447
+
448
+ private authenticate(socket: TLSSocket): void {
449
+ const cert = socket.getPeerCertificate();
450
+ let fp: string;
451
+ try { fp = fingerprint(cert.fingerprint256); } catch { socket.destroy(); return; }
452
+ const identity = this.config.clients.get(fp);
453
+ const expires = Date.parse(cert.valid_to);
454
+ const starts = Date.parse(cert.valid_from);
455
+ if (!socket.authorized || !identity || this.stopping || !Number.isFinite(expires) || !Number.isFinite(starts) || starts > Date.now() || expires <= Date.now()) {
456
+ log("connection_rejected", { fingerprint: fp, result: "unauthorized" });
457
+ socket.destroy();
458
+ return;
459
+ }
460
+ // Timers longer than INT32_MAX fire immediately in Node; recheck long-lived certificates in bounded slices.
461
+ const expiry = () => {
462
+ if (expires <= Date.now()) { this.drop(fp, new Fault(403, "certificate_expired", "Client certificate expired.")); return; }
463
+ connection.timer = setTimeout(expiry, Math.min(expires - Date.now(), 0x7fffffff));
464
+ };
465
+ const connection: Connection = { fingerprint: fp, expires, timer: setTimeout(expiry, Math.min(expires - Date.now(), 0x7fffffff)) };
466
+ this.connections.set(socket, connection);
467
+ socket.once("close", () => { clearTimeout(connection.timer); this.connections.delete(socket); });
468
+ log("connected", { name: identity.name, fingerprint: fp, result: "authenticated" });
469
+ }
470
+
471
+ private drop(fp: string, error: Fault): void {
472
+ this.sessions.get(fp)?.close(error);
473
+ for (const [socket, connection] of this.connections) if (connection.fingerprint === fp) socket.destroy();
474
+ }
475
+
476
+ start(): void {
477
+ this.server.listen(this.config.port, "127.0.0.1", () => {
478
+ const address = this.server.address();
479
+ log("listening", { result: "ready", host: "127.0.0.1", pid: process.pid, port: typeof address === "object" && address ? address.port : this.config.port, brokerSocket: getBrokerSocketPath() });
480
+ });
481
+ process.on("SIGHUP", () => this.reload());
482
+ process.once("SIGINT", () => this.shutdown());
483
+ process.once("SIGTERM", () => this.shutdown());
484
+ }
485
+
486
+ private reload(): void {
487
+ if (this.stopping) return;
488
+ try {
489
+ const next = loadConfig(this.configPath);
490
+ if (next.port !== this.config.port || next.ca !== this.config.ca || next.cert !== this.config.cert || next.key !== this.config.key
491
+ || !next.tls.ca.equals(this.config.tls.ca) || !next.tls.cert.equals(this.config.tls.cert) || !next.tls.key.equals(this.config.tls.key)) {
492
+ throw new Error("TLS/listener rotation requires restarting the helper.");
493
+ }
494
+ this.config = next;
495
+ for (const [fp, session] of this.sessions) if (!this.allowed(session.identity)) this.drop(fp, new Fault(403, "revoked", "Identity revoked or changed by configuration reload."));
496
+ for (const connection of this.connections.values()) if (!next.clients.has(connection.fingerprint)) this.drop(connection.fingerprint, new Fault(403, "revoked", "Identity revoked."));
497
+ for (const fp of this.losses.keys()) if (!next.clients.has(fp)) this.losses.delete(fp);
498
+ log("allowlist_reloaded", { result: "accepted", clients: next.clients.size });
499
+ } catch {
500
+ this.config.clients.clear();
501
+ for (const session of this.sessions.values()) session.close(new Fault(503, "configuration_invalid", "Configuration reload failed; all identities denied."));
502
+ for (const socket of this.sockets) socket.destroy();
503
+ this.losses.clear();
504
+ log("allowlist_reloaded", { result: "failed_closed" });
505
+ }
506
+ }
507
+
508
+ private shutdown(): void {
509
+ if (this.stopping) return;
510
+ this.stopping = true;
511
+ this.server.close();
512
+ for (const session of this.sessions.values()) session.close(new Fault(503, "shutting_down", "Bridge is shutting down."));
513
+ for (const socket of this.sockets) socket.destroy();
514
+ log("shutdown", { result: "closed" });
515
+ }
516
+
517
+ private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
518
+ const requestId = randomUUID();
519
+ const started = Date.now();
520
+ let session: Session | undefined;
521
+ let controller: AbortController | undefined;
522
+ let deadline: NodeJS.Timeout | undefined;
523
+ let peer: string | undefined;
524
+ const abort = () => session?.close(new Fault(499, "client_aborted", "HTTP client disconnected; delivery may be unknown."));
525
+ const onClose = () => { if (!res.writableFinished) abort(); };
526
+ const reply = (status: number, data: Record<string, unknown>) => {
527
+ if (res.destroyed || res.writableEnded) return;
528
+ const payload = JSON.stringify({ ...data, requestId });
529
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Content-Length": Buffer.byteLength(payload), "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Connection": "close" });
530
+ res.end(payload);
531
+ };
532
+ try {
533
+ const socket = req.socket as TLSSocket;
534
+ const connection = this.connections.get(socket);
535
+ const identity = connection && this.config.clients.get(connection.fingerprint);
536
+ if (!connection || !identity || !socket.authorized || this.stopping) throw new Fault(403, "unauthorized", "Client certificate is not authorized.");
537
+ if (connection.expires <= Date.now()) { this.drop(connection.fingerprint, new Fault(403, "certificate_expired", "Client certificate expired.")); throw new Fault(403, "certificate_expired", "Client certificate expired."); }
538
+ if (req.headers.origin !== undefined || Object.keys(req.headers).some((key) => key.startsWith("sec-fetch-"))) throw new Fault(403, "browser_forbidden", "Browser access is not supported.");
539
+ const route = `${req.method} ${req.url}`;
540
+ if (!["GET /v1/list", "GET /v1/inbox", "POST /v1/register", "POST /v1/send", "POST /v1/ask", "POST /v1/reply", "POST /v1/ack"].includes(route)) throw new Fault(404, "not_found", "Unknown method or path.");
541
+ if (req.method === "GET" && (req.headers["transfer-encoding"] !== undefined || req.headers["content-length"] !== undefined && req.headers["content-length"] !== "0")) throw new Fault(400, "invalid_input", "GET requests must not have a body.");
542
+ session = this.sessions.get(identity.fingerprint256);
543
+ if (!session) { session = new Session(this, identity, connection.expires); this.sessions.set(identity.fingerprint256, session); }
544
+ session.guard();
545
+ if (session.requests.size >= MAX_REQUESTS) throw new Fault(429, "too_many_requests", "Too many concurrent requests for this identity.");
546
+ controller = new AbortController();
547
+ const signal = controller.signal;
548
+ session.requests.add(controller);
549
+ session.touch();
550
+ req.once("aborted", abort);
551
+ res.once("close", onClose);
552
+ const setDeadline = (ms: number) => {
553
+ clearTimeout(deadline);
554
+ deadline = setTimeout(() => session?.close(new Fault(504, "request_timeout", "HTTP operation deadline exceeded; delivery may be unknown.")), Math.max(1, ms - (Date.now() - started)));
555
+ };
556
+ setDeadline(route === "POST /v1/ask" ? ASK_TIMEOUT + 15000 : 15000);
557
+ let input: Record<string, unknown> = {};
558
+ if (req.method === "POST") {
559
+ const fields = route === "POST /v1/register" ? [] : route === "POST /v1/ack" ? ["ids"] : route === "POST /v1/reply" ? ["replyTo", "message"] : route === "POST /v1/ask" ? ["to", "message", "timeoutMs"] : ["to", "message"];
560
+ input = object(await body(req, signal), fields);
561
+ }
562
+ let message: string | undefined;
563
+ let to: string | undefined;
564
+ let replyTo: string | undefined;
565
+ let ids: string[] = [];
566
+ let timeoutMs = ASK_TIMEOUT;
567
+ if (["POST /v1/send", "POST /v1/ask", "POST /v1/reply"].includes(route)) message = text(input.message);
568
+ if (["POST /v1/send", "POST /v1/ask"].includes(route)) to = label(input.to, "to").trim();
569
+ if (route === "POST /v1/reply") replyTo = label(input.replyTo, "replyTo");
570
+ if (route === "POST /v1/ask") {
571
+ const timeout = input.timeoutMs === undefined ? ASK_TIMEOUT : input.timeoutMs;
572
+ if (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout < 100 || timeout > ASK_TIMEOUT) throw new Fault(400, "invalid_input", "timeoutMs must be an integer from 100 to 120000.");
573
+ timeoutMs = timeout;
574
+ setDeadline(timeoutMs + 15000);
575
+ }
576
+ if (route === "POST /v1/ack") {
577
+ if (!Array.isArray(input.ids) || input.ids.length > INBOX_COUNT) throw new Fault(400, "invalid_input", "ids must be an array of at most 256 message IDs.");
578
+ ids = [...new Set(input.ids.map((id) => label(id, "message ID")))];
579
+ }
580
+ session.guard(signal);
581
+ if (route !== "POST /v1/ask") await session.connect(signal);
582
+ let data: Record<string, unknown>;
583
+ switch (route) {
584
+ case "POST /v1/register": data = { sessionId: session.client.sessionId, name: identity.name }; break;
585
+ case "GET /v1/list": {
586
+ const sessions = await session.peers(signal);
587
+ data = { sessionId: session.client.sessionId, sessions: sessions.map(({ topics: _topics, subscriptions: _subscriptions, ...entry }) => ({ ...entry, target: formatSessionTarget(entry, sessions) })) };
588
+ break;
589
+ }
590
+ case "GET /v1/inbox": {
591
+ const lostMessages = this.losses.get(identity.fingerprint256) ?? 0;
592
+ data = { messages: [...session.inbox.values()].map(({ from, message }) => ({ from, message })), overflow: lostMessages > 0, lostMessages };
593
+ break;
594
+ }
595
+ case "POST /v1/ack": {
596
+ const acked: string[] = [];
597
+ const retained: string[] = [];
598
+ for (const id of ids) {
599
+ const entry = session.inbox.get(id);
600
+ if (entry?.message.expectsReply) retained.push(id);
601
+ else if (entry) { session.remove(id); acked.push(id); }
602
+ }
603
+ session.presence();
604
+ data = { acked, retained };
605
+ break;
606
+ }
607
+ case "POST /v1/send": {
608
+ peer = (await session.target(to!, signal)).id;
609
+ data = { ...await session.send(peer, message!, signal, requestId) };
610
+ break;
611
+ }
612
+ case "POST /v1/ask": data = await session.ask(to!, message!, timeoutMs, signal, requestId); break;
613
+ case "POST /v1/reply": {
614
+ const entry = session.inbox.get(replyTo!);
615
+ if (!entry?.message.expectsReply) throw new Fault(404, "unknown_ask", "replyTo must identify an unanswered inbound ask.");
616
+ if (entry.replying) throw new Fault(409, "reply_in_progress", "This ask already has a reply in flight.");
617
+ entry.replying = true;
618
+ peer = entry.from.id;
619
+ try {
620
+ const peers = await session.peers(signal);
621
+ if (!peers.some((candidate) => candidate.id === peer)) throw new Fault(409, "peer_offline", "Original ask sender is disconnected.");
622
+ session.guard(signal);
623
+ if (session.inbox.get(replyTo!) !== entry) throw new Fault(409, "ask_retired", "Inbound ask is no longer replyable.");
624
+ data = { ...await session.send(peer, message!, signal, requestId, { replyTo }) };
625
+ session.remove(replyTo!);
626
+ session.presence();
627
+ } finally { entry.replying = false; }
628
+ break;
629
+ }
630
+ default: throw new Fault(404, "not_found", "Unknown method or path.");
631
+ }
632
+ session.guard(signal);
633
+ log("request", { ...session.fields(), requestId, peer, result: "ok" });
634
+ reply(200, { ok: true, ...data });
635
+ } catch (error) {
636
+ const fault = error instanceof Fault ? error : new Fault(503, "broker_unavailable", "Local broker operation failed.");
637
+ log("request", { ...session?.fields(), requestId, peer, result: fault.code });
638
+ reply(fault.status, { ok: false, error: { code: fault.code, message: fault.message, ...fault.details } });
639
+ } finally {
640
+ clearTimeout(deadline);
641
+ req.off("aborted", abort);
642
+ res.off("close", onClose);
643
+ if (controller) session?.requests.delete(controller);
644
+ }
645
+ }
646
+ }
647
+
648
+ function main(): void {
649
+ const args = process.argv.slice(2);
650
+ if (args.length === 1 && (args[0] === "-h" || args[0] === "--help")) {
651
+ process.stdout.write("Usage: node dist/pi-intercom/bridge.js --config PATH\n\nOptional loopback HTTPS/mTLS bridge for the local pi-intercom broker.\nConfig and TLS key must be owned by you with mode 0600. Never starts the broker.\nSIGHUP reloads the client allowlist (invalid reload denies all clients).\nRestart this helper for TLS/listener rotation. SIGINT/SIGTERM disconnect peers.\n\nExample: node dist/pi-intercom/bridge.js --config ~/.pi/agent/intercom/bridge.json\n");
652
+ return;
653
+ }
654
+ if (args.length !== 2 || args[0] !== "--config" || !args[1]) {
655
+ process.stderr.write("Usage: node dist/pi-intercom/bridge.js --config PATH (or --help)\n");
656
+ process.exitCode = 2;
657
+ return;
658
+ }
659
+ try {
660
+ const path = resolve(args[1]);
661
+ new Bridge(loadConfig(path), path).start();
662
+ } catch {
663
+ process.stderr.write("Bridge startup failed: check config schema, file ownership/mode 0600, absolute TLS/cwd paths, and TLS credentials.\n");
664
+ process.exitCode = 1;
665
+ }
666
+ }
667
+
668
+ main();