@draht/coding-agent 2026.7.30 → 2026.9.5-1

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 (459) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/README.md +46 -2
  3. package/agents/debugger.md +12 -1
  4. package/agents/git-committer.md +1 -0
  5. package/agents/implementer.md +20 -0
  6. package/agents/investigator.md +75 -0
  7. package/agents/reviewer.md +7 -0
  8. package/agents/spec-reviewer.md +66 -0
  9. package/agents/verifier.md +4 -3
  10. package/bin/draht-tools.cjs +472 -41
  11. package/dist/agents/debugger.md +12 -1
  12. package/dist/agents/git-committer.md +1 -0
  13. package/dist/agents/implementer.md +20 -0
  14. package/dist/agents/investigator.md +75 -0
  15. package/dist/agents/reviewer.md +7 -0
  16. package/dist/agents/spec-reviewer.md +66 -0
  17. package/dist/agents/verifier.md +4 -3
  18. package/dist/cli/args.d.ts +10 -0
  19. package/dist/cli/args.d.ts.map +1 -1
  20. package/dist/cli/args.js +69 -2
  21. package/dist/cli/args.js.map +1 -1
  22. package/dist/cli/attach-mode.d.ts +61 -0
  23. package/dist/cli/attach-mode.d.ts.map +1 -1
  24. package/dist/cli/attach-mode.js +243 -5
  25. package/dist/cli/attach-mode.js.map +1 -1
  26. package/dist/cli/credential-print.d.ts +1 -1
  27. package/dist/cli/credential-print.d.ts.map +1 -1
  28. package/dist/cli/credential-print.js +5 -4
  29. package/dist/cli/credential-print.js.map +1 -1
  30. package/dist/config.d.ts +9 -0
  31. package/dist/config.d.ts.map +1 -1
  32. package/dist/config.js +31 -4
  33. package/dist/config.js.map +1 -1
  34. package/dist/core/agent-session-runtime.d.ts +17 -1
  35. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  36. package/dist/core/agent-session-runtime.js +87 -30
  37. package/dist/core/agent-session-runtime.js.map +1 -1
  38. package/dist/core/agent-session-services.d.ts +1 -1
  39. package/dist/core/agent-session-services.d.ts.map +1 -1
  40. package/dist/core/agent-session-services.js +1 -0
  41. package/dist/core/agent-session-services.js.map +1 -1
  42. package/dist/core/agent-session.d.ts +35 -16
  43. package/dist/core/agent-session.d.ts.map +1 -1
  44. package/dist/core/agent-session.js +149 -64
  45. package/dist/core/agent-session.js.map +1 -1
  46. package/dist/core/auth-storage.d.ts +5 -1
  47. package/dist/core/auth-storage.d.ts.map +1 -1
  48. package/dist/core/auth-storage.js +72 -15
  49. package/dist/core/auth-storage.js.map +1 -1
  50. package/dist/core/builtins/checkpoints.d.ts +20 -0
  51. package/dist/core/builtins/checkpoints.d.ts.map +1 -0
  52. package/dist/core/builtins/checkpoints.js +161 -0
  53. package/dist/core/builtins/checkpoints.js.map +1 -0
  54. package/dist/core/builtins/duet.d.ts +26 -0
  55. package/dist/core/builtins/duet.d.ts.map +1 -0
  56. package/dist/core/builtins/duet.js +660 -0
  57. package/dist/core/builtins/duet.js.map +1 -0
  58. package/dist/core/builtins/index.d.ts.map +1 -1
  59. package/dist/core/builtins/index.js +7 -1
  60. package/dist/core/builtins/index.js.map +1 -1
  61. package/dist/core/builtins/subagent.d.ts +24 -4
  62. package/dist/core/builtins/subagent.d.ts.map +1 -1
  63. package/dist/core/builtins/subagent.js +278 -35
  64. package/dist/core/builtins/subagent.js.map +1 -1
  65. package/dist/core/checkpoints/checkpoint-cli.d.ts +17 -0
  66. package/dist/core/checkpoints/checkpoint-cli.d.ts.map +1 -0
  67. package/dist/core/checkpoints/checkpoint-cli.js +78 -0
  68. package/dist/core/checkpoints/checkpoint-cli.js.map +1 -0
  69. package/dist/core/checkpoints/checkpoint-manager.d.ts +294 -0
  70. package/dist/core/checkpoints/checkpoint-manager.d.ts.map +1 -0
  71. package/dist/core/checkpoints/checkpoint-manager.js +865 -0
  72. package/dist/core/checkpoints/checkpoint-manager.js.map +1 -0
  73. package/dist/core/checkpoints/rewind.d.ts +141 -0
  74. package/dist/core/checkpoints/rewind.d.ts.map +1 -0
  75. package/dist/core/checkpoints/rewind.js +246 -0
  76. package/dist/core/checkpoints/rewind.js.map +1 -0
  77. package/dist/core/compaction/branch-summarization.d.ts +1 -1
  78. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  79. package/dist/core/compaction/branch-summarization.js +9 -4
  80. package/dist/core/compaction/branch-summarization.js.map +1 -1
  81. package/dist/core/compaction/compaction.d.ts +5 -0
  82. package/dist/core/compaction/compaction.d.ts.map +1 -1
  83. package/dist/core/compaction/compaction.js +25 -4
  84. package/dist/core/compaction/compaction.js.map +1 -1
  85. package/dist/core/extensions/index.d.ts +1 -1
  86. package/dist/core/extensions/index.d.ts.map +1 -1
  87. package/dist/core/extensions/index.js.map +1 -1
  88. package/dist/core/extensions/loader.d.ts.map +1 -1
  89. package/dist/core/extensions/loader.js +83 -20
  90. package/dist/core/extensions/loader.js.map +1 -1
  91. package/dist/core/extensions/runner.d.ts +13 -2
  92. package/dist/core/extensions/runner.d.ts.map +1 -1
  93. package/dist/core/extensions/runner.js +37 -2
  94. package/dist/core/extensions/runner.js.map +1 -1
  95. package/dist/core/extensions/types.d.ts +189 -6
  96. package/dist/core/extensions/types.d.ts.map +1 -1
  97. package/dist/core/extensions/types.js.map +1 -1
  98. package/dist/core/http-dispatcher.d.ts.map +1 -1
  99. package/dist/core/http-dispatcher.js +7 -0
  100. package/dist/core/http-dispatcher.js.map +1 -1
  101. package/dist/core/index.d.ts +1 -1
  102. package/dist/core/index.d.ts.map +1 -1
  103. package/dist/core/index.js.map +1 -1
  104. package/dist/core/keybindings.d.ts +5 -0
  105. package/dist/core/keybindings.d.ts.map +1 -1
  106. package/dist/core/keybindings.js +1 -0
  107. package/dist/core/keybindings.js.map +1 -1
  108. package/dist/core/model-registry.d.ts +3 -2
  109. package/dist/core/model-registry.d.ts.map +1 -1
  110. package/dist/core/model-registry.js +8 -8
  111. package/dist/core/model-registry.js.map +1 -1
  112. package/dist/core/model-resolver.d.ts.map +1 -1
  113. package/dist/core/model-resolver.js +34 -7
  114. package/dist/core/model-resolver.js.map +1 -1
  115. package/dist/core/model-runtime.d.ts +7 -1
  116. package/dist/core/model-runtime.d.ts.map +1 -1
  117. package/dist/core/model-runtime.js +30 -10
  118. package/dist/core/model-runtime.js.map +1 -1
  119. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  120. package/dist/core/multi-agent/permission-gate.js +4 -3
  121. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  122. package/dist/core/multi-agent/worktree.d.ts +2 -0
  123. package/dist/core/multi-agent/worktree.d.ts.map +1 -1
  124. package/dist/core/multi-agent/worktree.js +2 -2
  125. package/dist/core/multi-agent/worktree.js.map +1 -1
  126. package/dist/core/package-manager.d.ts +7 -1
  127. package/dist/core/package-manager.d.ts.map +1 -1
  128. package/dist/core/package-manager.js +21 -44
  129. package/dist/core/package-manager.js.map +1 -1
  130. package/dist/core/permission-relay/index.d.ts +19 -0
  131. package/dist/core/permission-relay/index.d.ts.map +1 -0
  132. package/dist/core/permission-relay/index.js +49 -0
  133. package/dist/core/permission-relay/index.js.map +1 -0
  134. package/dist/core/permission-relay/relay-ui-context.d.ts +39 -0
  135. package/dist/core/permission-relay/relay-ui-context.d.ts.map +1 -0
  136. package/dist/core/permission-relay/relay-ui-context.js +788 -0
  137. package/dist/core/permission-relay/relay-ui-context.js.map +1 -0
  138. package/dist/core/permission-relay/types.d.ts +222 -0
  139. package/dist/core/permission-relay/types.d.ts.map +1 -0
  140. package/dist/core/permission-relay/types.js +15 -0
  141. package/dist/core/permission-relay/types.js.map +1 -0
  142. package/dist/core/pi-manifest.d.ts +14 -0
  143. package/dist/core/pi-manifest.d.ts.map +1 -0
  144. package/dist/core/pi-manifest.js +35 -0
  145. package/dist/core/pi-manifest.js.map +1 -0
  146. package/dist/core/project-trust.js +2 -2
  147. package/dist/core/project-trust.js.map +1 -1
  148. package/dist/core/resource-loader.d.ts +21 -0
  149. package/dist/core/resource-loader.d.ts.map +1 -1
  150. package/dist/core/resource-loader.js +101 -24
  151. package/dist/core/resource-loader.js.map +1 -1
  152. package/dist/core/sandbox/bash-operations.d.ts +149 -0
  153. package/dist/core/sandbox/bash-operations.d.ts.map +1 -0
  154. package/dist/core/sandbox/bash-operations.js +163 -0
  155. package/dist/core/sandbox/bash-operations.js.map +1 -0
  156. package/dist/core/sandbox/env.d.ts +83 -0
  157. package/dist/core/sandbox/env.d.ts.map +1 -0
  158. package/dist/core/sandbox/env.js +123 -0
  159. package/dist/core/sandbox/env.js.map +1 -0
  160. package/dist/core/sandbox/executor.d.ts +104 -0
  161. package/dist/core/sandbox/executor.d.ts.map +1 -0
  162. package/dist/core/sandbox/executor.js +92 -0
  163. package/dist/core/sandbox/executor.js.map +1 -0
  164. package/dist/core/sandbox/index.d.ts +36 -0
  165. package/dist/core/sandbox/index.d.ts.map +1 -0
  166. package/dist/core/sandbox/index.js +36 -0
  167. package/dist/core/sandbox/index.js.map +1 -0
  168. package/dist/core/sandbox/linux.d.ts +121 -0
  169. package/dist/core/sandbox/linux.d.ts.map +1 -0
  170. package/dist/core/sandbox/linux.js +260 -0
  171. package/dist/core/sandbox/linux.js.map +1 -0
  172. package/dist/core/sandbox/policy.d.ts +142 -0
  173. package/dist/core/sandbox/policy.d.ts.map +1 -0
  174. package/dist/core/sandbox/policy.js +297 -0
  175. package/dist/core/sandbox/policy.js.map +1 -0
  176. package/dist/core/sandbox/real-path.d.ts +112 -0
  177. package/dist/core/sandbox/real-path.d.ts.map +1 -0
  178. package/dist/core/sandbox/real-path.js +158 -0
  179. package/dist/core/sandbox/real-path.js.map +1 -0
  180. package/dist/core/sandbox/seatbelt-profile.d.ts +95 -0
  181. package/dist/core/sandbox/seatbelt-profile.d.ts.map +1 -0
  182. package/dist/core/sandbox/seatbelt-profile.js +239 -0
  183. package/dist/core/sandbox/seatbelt-profile.js.map +1 -0
  184. package/dist/core/sandbox/seatbelt.d.ts +95 -0
  185. package/dist/core/sandbox/seatbelt.d.ts.map +1 -0
  186. package/dist/core/sandbox/seatbelt.js +154 -0
  187. package/dist/core/sandbox/seatbelt.js.map +1 -0
  188. package/dist/core/sandbox/self-test.d.ts +109 -0
  189. package/dist/core/sandbox/self-test.d.ts.map +1 -0
  190. package/dist/core/sandbox/self-test.js +369 -0
  191. package/dist/core/sandbox/self-test.js.map +1 -0
  192. package/dist/core/sandbox/spawn.d.ts +33 -0
  193. package/dist/core/sandbox/spawn.d.ts.map +1 -0
  194. package/dist/core/sandbox/spawn.js +87 -0
  195. package/dist/core/sandbox/spawn.js.map +1 -0
  196. package/dist/core/sdk.d.ts.map +1 -1
  197. package/dist/core/sdk.js +3 -1
  198. package/dist/core/sdk.js.map +1 -1
  199. package/dist/core/session-manager.d.ts +60 -1
  200. package/dist/core/session-manager.d.ts.map +1 -1
  201. package/dist/core/session-manager.js +53 -6
  202. package/dist/core/session-manager.js.map +1 -1
  203. package/dist/core/settings-manager.d.ts +21 -0
  204. package/dist/core/settings-manager.d.ts.map +1 -1
  205. package/dist/core/settings-manager.js +36 -16
  206. package/dist/core/settings-manager.js.map +1 -1
  207. package/dist/core/skills.d.ts +3 -1
  208. package/dist/core/skills.d.ts.map +1 -1
  209. package/dist/core/skills.js +19 -6
  210. package/dist/core/skills.js.map +1 -1
  211. package/dist/core/slash-commands.d.ts.map +1 -1
  212. package/dist/core/slash-commands.js +1 -0
  213. package/dist/core/slash-commands.js.map +1 -1
  214. package/dist/core/soak/soak-log.d.ts +298 -0
  215. package/dist/core/soak/soak-log.d.ts.map +1 -0
  216. package/dist/core/soak/soak-log.js +660 -0
  217. package/dist/core/soak/soak-log.js.map +1 -0
  218. package/dist/core/soak/soak-reader.d.ts +60 -0
  219. package/dist/core/soak/soak-reader.d.ts.map +1 -0
  220. package/dist/core/soak/soak-reader.js +106 -0
  221. package/dist/core/soak/soak-reader.js.map +1 -0
  222. package/dist/core/socket-server/discovery.d.ts +78 -1
  223. package/dist/core/socket-server/discovery.d.ts.map +1 -1
  224. package/dist/core/socket-server/discovery.js +356 -37
  225. package/dist/core/socket-server/discovery.js.map +1 -1
  226. package/dist/core/socket-server/index.d.ts +10 -4
  227. package/dist/core/socket-server/index.d.ts.map +1 -1
  228. package/dist/core/socket-server/index.js +6 -3
  229. package/dist/core/socket-server/index.js.map +1 -1
  230. package/dist/core/socket-server/permission-delivery.d.ts +125 -0
  231. package/dist/core/socket-server/permission-delivery.d.ts.map +1 -0
  232. package/dist/core/socket-server/permission-delivery.js +152 -0
  233. package/dist/core/socket-server/permission-delivery.js.map +1 -0
  234. package/dist/core/socket-server/permission-registry.d.ts +301 -0
  235. package/dist/core/socket-server/permission-registry.d.ts.map +1 -0
  236. package/dist/core/socket-server/permission-registry.js +410 -0
  237. package/dist/core/socket-server/permission-registry.js.map +1 -0
  238. package/dist/core/socket-server/permission-relay.d.ts +81 -0
  239. package/dist/core/socket-server/permission-relay.d.ts.map +1 -0
  240. package/dist/core/socket-server/permission-relay.js +528 -0
  241. package/dist/core/socket-server/permission-relay.js.map +1 -0
  242. package/dist/core/socket-server/safe-text.d.ts +83 -0
  243. package/dist/core/socket-server/safe-text.d.ts.map +1 -0
  244. package/dist/core/socket-server/safe-text.js +277 -0
  245. package/dist/core/socket-server/safe-text.js.map +1 -0
  246. package/dist/core/socket-server/session-integration.d.ts +65 -2
  247. package/dist/core/socket-server/session-integration.d.ts.map +1 -1
  248. package/dist/core/socket-server/session-integration.js +434 -32
  249. package/dist/core/socket-server/session-integration.js.map +1 -1
  250. package/dist/core/socket-server/socket-client.d.ts +21 -2
  251. package/dist/core/socket-server/socket-client.d.ts.map +1 -1
  252. package/dist/core/socket-server/socket-client.js +52 -1
  253. package/dist/core/socket-server/socket-client.js.map +1 -1
  254. package/dist/core/socket-server/socket-server.d.ts +152 -1
  255. package/dist/core/socket-server/socket-server.d.ts.map +1 -1
  256. package/dist/core/socket-server/socket-server.js +775 -26
  257. package/dist/core/socket-server/socket-server.js.map +1 -1
  258. package/dist/core/socket-server/types.d.ts +106 -2
  259. package/dist/core/socket-server/types.d.ts.map +1 -1
  260. package/dist/core/socket-server/types.js +13 -1
  261. package/dist/core/socket-server/types.js.map +1 -1
  262. package/dist/core/system-prompt.d.ts.map +1 -1
  263. package/dist/core/system-prompt.js +8 -9
  264. package/dist/core/system-prompt.js.map +1 -1
  265. package/dist/core/tools/bash.d.ts +1 -1
  266. package/dist/core/tools/bash.d.ts.map +1 -1
  267. package/dist/core/tools/bash.js +5 -2
  268. package/dist/core/tools/bash.js.map +1 -1
  269. package/dist/core/tools/edit.d.ts.map +1 -1
  270. package/dist/core/tools/edit.js +17 -2
  271. package/dist/core/tools/edit.js.map +1 -1
  272. package/dist/core/tools/find.d.ts +3 -0
  273. package/dist/core/tools/find.d.ts.map +1 -1
  274. package/dist/core/tools/find.js +11 -18
  275. package/dist/core/tools/find.js.map +1 -1
  276. package/dist/core/trust-manager.d.ts +6 -4
  277. package/dist/core/trust-manager.d.ts.map +1 -1
  278. package/dist/core/trust-manager.js +55 -21
  279. package/dist/core/trust-manager.js.map +1 -1
  280. package/dist/extensions/index.d.ts.map +1 -1
  281. package/dist/extensions/index.js +5 -1
  282. package/dist/extensions/index.js.map +1 -1
  283. package/dist/extensions/llama/provider.d.ts.map +1 -1
  284. package/dist/extensions/llama/provider.js +5 -1
  285. package/dist/extensions/llama/provider.js.map +1 -1
  286. package/dist/extensions/stub-provider/index.d.ts +9 -0
  287. package/dist/extensions/stub-provider/index.d.ts.map +1 -0
  288. package/dist/extensions/stub-provider/index.js +13 -0
  289. package/dist/extensions/stub-provider/index.js.map +1 -0
  290. package/dist/extensions/stub-provider/provider.d.ts +77 -0
  291. package/dist/extensions/stub-provider/provider.d.ts.map +1 -0
  292. package/dist/extensions/stub-provider/provider.js +193 -0
  293. package/dist/extensions/stub-provider/provider.js.map +1 -0
  294. package/dist/hooks/gsd/draht-quality-gate.js +3 -3
  295. package/dist/index.d.ts +1 -1
  296. package/dist/index.d.ts.map +1 -1
  297. package/dist/index.js.map +1 -1
  298. package/dist/main.d.ts.map +1 -1
  299. package/dist/main.js +242 -45
  300. package/dist/main.js.map +1 -1
  301. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  302. package/dist/modes/interactive/components/config-selector.js +3 -2
  303. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  304. package/dist/modes/interactive/components/extension-selector.d.ts +49 -0
  305. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  306. package/dist/modes/interactive/components/extension-selector.js +202 -5
  307. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  308. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  309. package/dist/modes/interactive/components/session-selector.js +10 -2
  310. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  311. package/dist/modes/interactive/components/settings-selector.d.ts +2 -0
  312. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  313. package/dist/modes/interactive/components/settings-selector.js +10 -0
  314. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  315. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  316. package/dist/modes/interactive/components/tool-execution.js +10 -1
  317. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  318. package/dist/modes/interactive/components/tree-selector.d.ts +20 -2
  319. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  320. package/dist/modes/interactive/components/tree-selector.js +21 -5
  321. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  322. package/dist/modes/interactive/interactive-mode.d.ts +97 -3
  323. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  324. package/dist/modes/interactive/interactive-mode.js +394 -24
  325. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  326. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  327. package/dist/modes/rpc/rpc-mode.js +165 -7
  328. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  329. package/dist/modes/rpc/rpc-types.d.ts +68 -1
  330. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  331. package/dist/modes/rpc/rpc-types.js.map +1 -1
  332. package/dist/prompts/commands/atomic-commit.md +1 -12
  333. package/dist/prompts/commands/brainstorm.md +12 -15
  334. package/dist/prompts/commands/create-verification-skill.md +108 -0
  335. package/dist/prompts/commands/discuss-phase.md +3 -14
  336. package/dist/prompts/commands/execute-phase.md +3 -11
  337. package/dist/prompts/commands/fix.md +41 -18
  338. package/dist/prompts/commands/grill.md +66 -0
  339. package/dist/prompts/commands/init-project.md +5 -15
  340. package/dist/prompts/commands/map-codebase.md +1 -13
  341. package/dist/prompts/commands/new-project.md +5 -15
  342. package/dist/prompts/commands/next-milestone.md +1 -13
  343. package/dist/prompts/commands/orchestrate.md +1 -1
  344. package/dist/prompts/commands/pause-work.md +1 -13
  345. package/dist/prompts/commands/plan-phase.md +2 -11
  346. package/dist/prompts/commands/progress.md +0 -13
  347. package/dist/prompts/commands/quick.md +3 -11
  348. package/dist/prompts/commands/resolve-conflicts.md +71 -0
  349. package/dist/prompts/commands/resume-work.md +0 -13
  350. package/dist/prompts/commands/review.md +4 -13
  351. package/dist/prompts/commands/triage.md +159 -0
  352. package/dist/prompts/commands/verify-work.md +4 -14
  353. package/dist/prompts/commands/why.md +135 -0
  354. package/dist/skills/atomic-reasoning/SKILL.md +115 -0
  355. package/dist/skills/blast-radius/SKILL.md +55 -0
  356. package/dist/skills/epistemics/SKILL.md +99 -0
  357. package/dist/skills/hexagon-animation/SKILL.md +49 -0
  358. package/dist/skills/hexagon-animation/generate.mjs +81 -0
  359. package/dist/skills/hexagon-animation/template.html +361 -0
  360. package/dist/skills/typescript-discipline/SKILL.md +50 -0
  361. package/dist/skills/typescript-discipline/references/patterns.md +294 -0
  362. package/dist/skills/unslop/SKILL.md +101 -0
  363. package/dist/utils/canonical-path.d.ts +28 -0
  364. package/dist/utils/canonical-path.d.ts.map +1 -0
  365. package/dist/utils/canonical-path.js +90 -0
  366. package/dist/utils/canonical-path.js.map +1 -0
  367. package/dist/utils/child-process.d.ts +12 -1
  368. package/dist/utils/child-process.d.ts.map +1 -1
  369. package/dist/utils/child-process.js +25 -8
  370. package/dist/utils/child-process.js.map +1 -1
  371. package/dist/utils/clipboard.d.ts +1 -1
  372. package/dist/utils/clipboard.d.ts.map +1 -1
  373. package/dist/utils/clipboard.js +22 -2
  374. package/dist/utils/clipboard.js.map +1 -1
  375. package/dist/utils/exif-orientation.d.ts.map +1 -1
  376. package/dist/utils/exif-orientation.js +2 -3
  377. package/dist/utils/exif-orientation.js.map +1 -1
  378. package/dist/utils/paths.d.ts +2 -7
  379. package/dist/utils/paths.d.ts.map +1 -1
  380. package/dist/utils/paths.js +13 -15
  381. package/dist/utils/paths.js.map +1 -1
  382. package/dist/utils/shell.d.ts.map +1 -1
  383. package/dist/utils/shell.js +6 -4
  384. package/dist/utils/shell.js.map +1 -1
  385. package/dist/utils/tools-manager.d.ts.map +1 -1
  386. package/dist/utils/tools-manager.js +3 -5
  387. package/dist/utils/tools-manager.js.map +1 -1
  388. package/docs/attachable-sessions.md +79 -0
  389. package/docs/compaction.md +21 -21
  390. package/docs/containerization.md +23 -23
  391. package/docs/custom-provider.md +16 -16
  392. package/docs/development.md +9 -9
  393. package/docs/docs.json +6 -2
  394. package/docs/duet.md +42 -0
  395. package/docs/extensions.md +58 -58
  396. package/docs/index.md +10 -10
  397. package/docs/json.md +7 -7
  398. package/docs/keybindings.md +6 -5
  399. package/docs/llama-cpp.md +6 -6
  400. package/docs/models.md +6 -6
  401. package/docs/packages.md +43 -43
  402. package/docs/prompt-templates.md +4 -4
  403. package/docs/providers.md +12 -12
  404. package/docs/quickstart.md +32 -32
  405. package/docs/rpc.md +83 -12
  406. package/docs/sdk.md +15 -15
  407. package/docs/security.md +18 -18
  408. package/docs/session-format.md +35 -13
  409. package/docs/sessions.md +17 -14
  410. package/docs/settings.md +25 -18
  411. package/docs/shell-aliases.md +2 -2
  412. package/docs/skills.md +12 -11
  413. package/docs/terminal-setup.md +12 -12
  414. package/docs/termux.md +6 -6
  415. package/docs/themes.md +11 -11
  416. package/docs/tmux.md +4 -4
  417. package/docs/tui.md +5 -5
  418. package/docs/usage.md +50 -50
  419. package/docs/windows.md +2 -2
  420. package/examples/extensions/overlay-qa-tests.ts +3 -3
  421. package/hooks/gsd/draht-quality-gate.js +3 -3
  422. package/package.json +11 -10
  423. package/prompts/commands/atomic-commit.md +1 -12
  424. package/prompts/commands/brainstorm.md +12 -15
  425. package/prompts/commands/create-verification-skill.md +108 -0
  426. package/prompts/commands/discuss-phase.md +3 -14
  427. package/prompts/commands/execute-phase.md +3 -11
  428. package/prompts/commands/fix.md +41 -18
  429. package/prompts/commands/grill.md +66 -0
  430. package/prompts/commands/init-project.md +5 -15
  431. package/prompts/commands/map-codebase.md +1 -13
  432. package/prompts/commands/new-project.md +5 -15
  433. package/prompts/commands/next-milestone.md +1 -13
  434. package/prompts/commands/orchestrate.md +1 -1
  435. package/prompts/commands/pause-work.md +1 -13
  436. package/prompts/commands/plan-phase.md +2 -11
  437. package/prompts/commands/progress.md +0 -13
  438. package/prompts/commands/quick.md +3 -11
  439. package/prompts/commands/resolve-conflicts.md +71 -0
  440. package/prompts/commands/resume-work.md +0 -13
  441. package/prompts/commands/review.md +4 -13
  442. package/prompts/commands/triage.md +159 -0
  443. package/prompts/commands/verify-work.md +4 -14
  444. package/prompts/commands/why.md +135 -0
  445. package/skills/atomic-reasoning/SKILL.md +115 -0
  446. package/skills/blast-radius/SKILL.md +55 -0
  447. package/skills/epistemics/SKILL.md +99 -0
  448. package/skills/hexagon-animation/SKILL.md +49 -0
  449. package/skills/hexagon-animation/generate.mjs +81 -0
  450. package/skills/hexagon-animation/template.html +361 -0
  451. package/skills/typescript-discipline/SKILL.md +50 -0
  452. package/skills/typescript-discipline/references/patterns.md +294 -0
  453. package/skills/unslop/SKILL.md +101 -0
  454. package/dist/prompts/agents/build.md +0 -86
  455. package/dist/prompts/agents/plan.md +0 -79
  456. package/dist/prompts/agents/verify.md +0 -69
  457. package/prompts/agents/build.md +0 -86
  458. package/prompts/agents/plan.md +0 -79
  459. package/prompts/agents/verify.md +0 -69
@@ -7,10 +7,139 @@
7
7
  * - Input from any client is echoed to all others
8
8
  * - Clients can join/leave without disrupting the session
9
9
  */
10
- import { existsSync } from "node:fs";
11
- import { mkdir, rm, writeFile } from "node:fs/promises";
10
+ import { rmSync } from "node:fs";
11
+ import { chmod, lstat, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
12
12
  import { createServer } from "node:net";
13
13
  import path from "node:path";
14
+ import { assertValidSessionId } from "../session-manager.js";
15
+ import { getSoakLog, SOAK_EVENTS } from "../soak/soak-log.js";
16
+ import { currentUid, discoverSocketSessions, pidOwnership } from "./discovery.js";
17
+ import { CLIENT_MODES, PERMISSION_RELAY_CAPABILITY, } from "./types.js";
18
+ /**
19
+ * How long {@link SocketServer.stop} waits for peers to close their end before it
20
+ * forces the remaining sockets down.
21
+ */
22
+ const STOP_CLOSE_TIMEOUT_MS = 1000;
23
+ /**
24
+ * How long a lock file with no readable PID has to sit untouched before it counts as
25
+ * debris rather than as a claim another starter is in the middle of writing.
26
+ */
27
+ const UNWRITTEN_LOCK_STALE_MS = 10_000;
28
+ /**
29
+ * How many live attachable sockets one host may hold (R35-ALWAYS.4).
30
+ *
31
+ * There was no cap at all: 500 sockets bound in one process with zero refusals,
32
+ * and `ulimit -n` on the development machine is 1048576, so the fd ceiling never
33
+ * arrives to stop a crash-restart loop. 64 is far above real use — a heavy user
34
+ * runs perhaps 10-20 concurrent sessions — and still low enough that a runaway is
35
+ * caught while the machine is healthy. It is a per-host number, counted from the
36
+ * sockets directory after the start-time sweep, not a per-process one: the point
37
+ * is to bound what accumulates on disk, and a restart loop is a new process each
38
+ * time.
39
+ *
40
+ * Overridable per server via {@link SocketServerOptions.maxLiveSockets}.
41
+ */
42
+ export const DEFAULT_MAX_LIVE_SOCKETS = 64;
43
+ /**
44
+ * Longest client-supplied string this file will copy into the soak log.
45
+ *
46
+ * A `clientId` and a client `mode` arrive over the socket and are self-asserted.
47
+ * They are recorded because a soak verdict has to be able to name which peer
48
+ * churned — and bounded because the log is append-only for weeks and a peer must
49
+ * not be able to make one line of it megabytes long.
50
+ */
51
+ const SOAK_LABEL_MAX = 128;
52
+ /**
53
+ * One soak record, and nothing else: no stdout, no stderr, no throw. See the
54
+ * three rules at the head of the same helper in `session-integration.ts`; the
55
+ * helper is kept per-file rather than shared because the only places to share it
56
+ * from are `soak-log.ts` (a finished file this task may not edit) or a fourth
57
+ * module that would exist solely to hold six lines.
58
+ *
59
+ * `sessionId` is passed through as an ordinary field: the writer stamps its own
60
+ * over it whenever it has one — which it does for every session process, set at
61
+ * bind — and honours this one otherwise, so a `SocketServer` used outside a
62
+ * session still records under the id it was refused for.
63
+ */
64
+ function soakRecord(event, fields, level = "info") {
65
+ try {
66
+ getSoakLog().record(event, fields, level);
67
+ }
68
+ catch {
69
+ // Deliberately empty, and deliberately not logged anywhere.
70
+ }
71
+ }
72
+ /** A client-supplied value, made safe to put in a record: a bounded string, always. */
73
+ function soakLabel(value) {
74
+ const text = typeof value === "string" ? value : JSON.stringify(value);
75
+ return (text ?? String(value)).slice(0, SOAK_LABEL_MAX);
76
+ }
77
+ /**
78
+ * Thrown when another live process already owns the socket for this session id.
79
+ *
80
+ * Taking the socket over would silently steal attachments from a running session,
81
+ * so the second process refuses to bind instead.
82
+ */
83
+ export class SocketSessionBusyError extends Error {
84
+ constructor(sessionId, ownerPid, socketPath) {
85
+ // Two genuinely different situations - do not describe them the same way. A
86
+ // readable PID means a live process really does own this session. An
87
+ // unreadable lock usually means another process is claiming it right now, but
88
+ // it is equally a lock left truncated by a process killed mid-claim, in which
89
+ // case nothing is running and the claim clears itself shortly.
90
+ super(ownerPid === null
91
+ ? `Session "${sessionId}" has an attachable lock that names no readable PID. ` +
92
+ `Another process is probably claiming it right now; it can also be debris from a ` +
93
+ `process killed mid-claim, in which case it clears itself within ` +
94
+ `${Math.round(UNWRITTEN_LOCK_STALE_MS / 1000)}s. Retry shortly. Socket: ${socketPath}`
95
+ : `Session "${sessionId}" is already attachable from a running process (PID ${ownerPid}). ` +
96
+ `Attach to it instead, or stop that process. Socket: ${socketPath}`);
97
+ this.name = "SocketSessionBusyError";
98
+ this.sessionId = sessionId;
99
+ this.ownerPid = ownerPid;
100
+ this.socketPath = socketPath;
101
+ }
102
+ }
103
+ /**
104
+ * Thrown when this host already holds as many live attachable sockets as it may.
105
+ *
106
+ * Names both the cap and the count that hit it, so an operator can tell a cap
107
+ * from a bug without reading the source. Exported deliberately and by name: the
108
+ * default-on start path branches on `error instanceof SocketCapReachedError` to
109
+ * pick the one refusal message that must never be confused with a broken sockets
110
+ * directory. A cap-hit is not a reason to refuse to START a session — that
111
+ * decision belongs to the caller, and this class exists so the caller can make it.
112
+ */
113
+ export class SocketCapReachedError extends Error {
114
+ constructor(sessionId, cap, liveCount, socketDir) {
115
+ super(`This machine already holds ${liveCount} live attachable sessions and the cap is ${cap}. ` +
116
+ `Session "${sessionId}" was not registered. Stop a session you are no longer using, or raise ` +
117
+ `the cap. Sockets: ${socketDir}`);
118
+ this.name = "SocketCapReachedError";
119
+ this.sessionId = sessionId;
120
+ this.cap = cap;
121
+ this.liveCount = liveCount;
122
+ this.socketDir = socketDir;
123
+ }
124
+ }
125
+ /**
126
+ * Thrown when the sockets directory is not a directory this user owns privately.
127
+ *
128
+ * The 0700 mode was the ONLY same-owner protection that existed, and nothing
129
+ * asserted it: there is not one `getuid()` call in the whole of coding-agent,
130
+ * geist-core or the gateway. A world-writable directory holding a 0666 socket and
131
+ * a lock naming root's pid 1 was listed as a live attachable session and would
132
+ * have been dialled. Refusing is the point — silently `chmod`ing a directory this
133
+ * process does not own would either fail with EPERM or, worse, succeed on a
134
+ * directory somebody else planted.
135
+ */
136
+ export class SocketDirectoryUnsafeError extends Error {
137
+ constructor(socketDir, reason) {
138
+ super(`Refusing to publish an attachable session in ${socketDir}: ${reason}`);
139
+ this.name = "SocketDirectoryUnsafeError";
140
+ this.socketDir = socketDir;
141
+ }
142
+ }
14
143
  /**
15
144
  * SocketServer manages a Unix domain socket for a single draht session.
16
145
  *
@@ -22,64 +151,244 @@ export class SocketServer {
22
151
  #socketPath;
23
152
  #lockPath;
24
153
  #cwd;
154
+ #socketDir;
25
155
  #maxClients;
156
+ #maxLiveSockets;
26
157
  #broadcastInputEcho;
27
158
  #server = null;
28
159
  #clients = new Map();
160
+ /**
161
+ * Every accepted connection, including ones that never sent an `attach` frame.
162
+ * `#clients` only holds attached peers, and shutdown has to reach the others too.
163
+ */
164
+ #sockets = new Set();
29
165
  #createdAt = new Date();
166
+ #stopped = false;
167
+ /**
168
+ * Whether THIS instance won the exclusive lock create. Only an owner may remove
169
+ * the socket/lock files; an instance whose start() was refused must never delete
170
+ * the live owner's files.
171
+ */
172
+ #ownsLock = false;
173
+ #rejectListen = null;
30
174
  /** Callback for input received from any client */
31
175
  #onInput = null;
176
+ /**
177
+ * Callback for a permission answer from a client. Nothing here decides
178
+ * anything: this class is plumbing, and the pending-ask registry that owns
179
+ * validation, first-answer-wins and expiry lives on the session side.
180
+ *
181
+ * With no callback registered, an answer is refused with a targeted
182
+ * `PERMISSION_UNKNOWN_REQUEST` error rather than swallowed — a phone must be
183
+ * able to tell "answered" from "this draht is too old to have asked".
184
+ */
185
+ #onPermissionResponse = null;
186
+ /**
187
+ * Fired immediately after a newly attached client has been sent
188
+ * `session_metadata`, so whatever holds unanswered asks can replay them to a
189
+ * client that arrived after they were raised.
190
+ */
191
+ #onAttachReplay = null;
192
+ /**
193
+ * Fired when an attached client's connection ends. Everything that keeps
194
+ * per-connection state outside this class resets it here.
195
+ */
196
+ #onClientDisconnect = null;
32
197
  constructor(options) {
198
+ // The id becomes a path component of the .sock and .lock files, and it arrives here
199
+ // straight from a session file on disk, so it is untrusted input. Reject anything
200
+ // that is not a plain session id rather than trying to sanitize it.
201
+ assertValidSessionId(options.sessionId);
33
202
  this.#sessionId = options.sessionId;
34
203
  this.#cwd = options.cwd;
35
204
  this.#maxClients = options.maxClients ?? 10;
205
+ this.#maxLiveSockets = options.maxLiveSockets ?? DEFAULT_MAX_LIVE_SOCKETS;
36
206
  this.#broadcastInputEcho = options.broadcastInputEcho ?? true;
207
+ this.#socketDir = options.socketDir;
37
208
  this.#socketPath = path.join(options.socketDir, `${options.sessionId}.sock`);
38
209
  this.#lockPath = path.join(options.socketDir, `${options.sessionId}.lock`);
39
210
  }
40
211
  /**
41
212
  * Start the socket server.
42
- * Creates socket directory, binds Unix socket, and starts listening.
213
+ * Creates socket directory, claims the session lock, binds the Unix socket, and listens.
214
+ *
215
+ * @throws {SocketSessionBusyError} When another live process already owns this session's socket.
216
+ * @throws {SocketDirectoryUnsafeError} When the sockets directory is not a private directory of ours.
217
+ * @throws {SocketCapReachedError} When this host already holds the maximum number of live sockets.
43
218
  */
44
219
  async start() {
45
- // Ensure socket directory exists
220
+ // Ensure socket directory exists and is owner-only. `mkdir` applies its mode only
221
+ // when it creates the directory, and masks it with the umask, so re-assert it on
222
+ // the path that created it.
46
223
  const socketDir = path.dirname(this.#socketPath);
47
- await mkdir(socketDir, { recursive: true, mode: 0o700 });
48
- // Clean up stale socket if it exists
49
- if (existsSync(this.#socketPath)) {
50
- await rm(this.#socketPath, { force: true });
224
+ const created = await mkdir(socketDir, { recursive: true, mode: 0o700 });
225
+ if (created !== undefined)
226
+ await chmod(socketDir, 0o700);
227
+ // Then assert it, every time, before anything is written into it.
228
+ await this.#assertSocketDirIsOurs(socketDir);
229
+ // REAP ON START (R35-ALWAYS.4). Before this, start() touched only this session's
230
+ // two paths and reaping happened ONLY inside discovery — so on a machine where no
231
+ // phone and no daemon ever asks for the fleet, the directory grew without bound.
232
+ // Measured: 25 start/SIGKILL cycles of the emitted binary left exactly 50 files,
233
+ // strictly linear, zero reaped. A full sweep here is what makes "N crash cycles
234
+ // leave nothing behind" true without a second process having to come along.
235
+ //
236
+ // Not sampled and not bounded: measured cost is 12-32 ms to scan 1000 live pairs
237
+ // and 106 ms to reap 1000 dead ones, once per session start, against the cap
238
+ // below. Sampling would trade a bounded, once-per-start cost for an unbounded
239
+ // on-disk one.
240
+ const live = await discoverSocketSessions(socketDir);
241
+ // THE CAP, counted after the sweep so debris can never be what refuses a session.
242
+ // Our own id does not count against it: re-binding a session id we already hold
243
+ // replaces one socket, it does not add one.
244
+ const others = live.filter((session) => session.sessionId !== this.#sessionId).length;
245
+ if (others >= this.#maxLiveSockets) {
246
+ // A refusal is the most interesting thing that can happen at a bind, and it is
247
+ // the one outcome that leaves NO socket behind for anything else to notice.
248
+ soakRecord(SOAK_EVENTS.CLIENT_REJECTED, {
249
+ reason: "socket_cap_reached",
250
+ sessionId: this.#sessionId,
251
+ cap: this.#maxLiveSockets,
252
+ liveSockets: others,
253
+ }, "warn");
254
+ throw new SocketCapReachedError(this.#sessionId, this.#maxLiveSockets, others, socketDir);
255
+ }
256
+ // Take ownership of the session id before touching the socket path.
257
+ try {
258
+ await this.#claimLock();
259
+ }
260
+ catch (error) {
261
+ // The busy twin (`draht -c` in a second terminal) is the commonest default-on
262
+ // refusal there is and it is not environmental, so a soak that could not count
263
+ // them would mistake the phase's most likely papercut for silence.
264
+ if (error instanceof SocketSessionBusyError) {
265
+ soakRecord(SOAK_EVENTS.CLIENT_REJECTED, { reason: "session_busy", sessionId: this.#sessionId, ownerPid: error.ownerPid }, "warn");
266
+ }
267
+ throw error;
268
+ }
269
+ try {
270
+ this.#server = createServer((socket) => this.#handleConnection(socket));
271
+ const server = this.#server;
272
+ // One long-lived error listener: it rejects the pending listen() and swallows
273
+ // post-startup server errors, which must not become uncaught exceptions.
274
+ server.on("error", (error) => {
275
+ const reject = this.#rejectListen;
276
+ this.#rejectListen = null;
277
+ reject?.(error);
278
+ });
279
+ await new Promise((resolve, reject) => {
280
+ this.#rejectListen = reject;
281
+ server.listen(this.#socketPath, () => {
282
+ this.#rejectListen = null;
283
+ resolve();
284
+ });
285
+ });
286
+ // bind(2) applies the process umask, so tighten the socket explicitly. Between
287
+ // bind and this chmod the socket is still unreachable for other users: it can
288
+ // only be named through the 0700 directory above, and Unix-domain permissions
289
+ // are enforced at connect(2) time. Mutating the process-global umask instead
290
+ // would leak into every unrelated file this process creates concurrently.
291
+ await chmod(this.#socketPath, 0o600);
292
+ }
293
+ catch (error) {
294
+ // Never leave a lock behind that advertises a socket which was never bound.
295
+ this.#server = null;
296
+ this.#rejectListen = null;
297
+ await rm(this.#lockPath, { force: true }).catch(() => { });
298
+ await rm(this.#socketPath, { force: true }).catch(() => { });
299
+ throw error;
51
300
  }
52
- // Write PID lock file for cleanup on crash
53
- await writeFile(this.#lockPath, `${process.pid}\n${this.#cwd}\n${this.#createdAt.toISOString()}`);
54
- // Create Unix domain socket server
55
- this.#server = createServer((socket) => this.#handleConnection(socket));
56
- // Bind to socket path
57
- await new Promise((resolve, reject) => {
58
- this.#server.listen(this.#socketPath, () => resolve());
59
- this.#server.on("error", reject);
60
- });
61
- // Set socket permissions (owner-only)
62
- await import("node:fs/promises").then((fs) => fs.chmod(this.#socketPath, 0o600));
63
301
  }
64
302
  /**
65
303
  * Stop the socket server and clean up.
66
304
  */
67
305
  async stop() {
68
- // Disconnect all clients
69
- for (const client of this.#clients.values()) {
70
- client.socket.end();
306
+ if (this.#stopped)
307
+ return;
308
+ this.#stopped = true;
309
+ // Half-close every accepted connection, not just the attached clients: a peer that
310
+ // connected and never sent an `attach` frame is not in #clients, and leaving it open
311
+ // would keep server.close() from ever calling back.
312
+ for (const socket of this.#sockets) {
313
+ try {
314
+ socket.end();
315
+ }
316
+ catch { }
71
317
  }
72
318
  this.#clients.clear();
73
319
  // Close server
74
320
  if (this.#server) {
321
+ const server = this.#server;
322
+ this.#server = null;
75
323
  await new Promise((resolve) => {
76
- this.#server.close(() => resolve());
324
+ // A peer that never closes its own half - a non-Node bridge, say - must not be
325
+ // able to wedge shutdown forever. Force the stragglers down after a grace
326
+ // period and carry on; the .sock/.lock cleanup below then runs either way.
327
+ const timer = setTimeout(() => {
328
+ for (const socket of this.#sockets) {
329
+ try {
330
+ socket.destroy();
331
+ }
332
+ catch { }
333
+ }
334
+ this.#sockets.clear();
335
+ resolve();
336
+ }, STOP_CLOSE_TIMEOUT_MS);
337
+ server.close(() => {
338
+ clearTimeout(timer);
339
+ resolve();
340
+ });
77
341
  });
342
+ }
343
+ this.#sockets.clear();
344
+ // Clean up socket and lock files — but only if this instance owns them. A
345
+ // server whose start() was refused with SocketSessionBusyError never claimed
346
+ // the lock; deleting these paths would destroy the LIVE owner's files and let
347
+ // a third process steal the session id.
348
+ if (this.#ownsLock) {
349
+ this.#ownsLock = false;
350
+ await rm(this.#socketPath, { force: true });
351
+ await rm(this.#lockPath, { force: true });
352
+ }
353
+ }
354
+ /**
355
+ * Stop the socket server from a synchronous exit path.
356
+ *
357
+ * `process.on("exit")` and signal handlers cannot await, so this does the same
358
+ * teardown as {@link stop} without yielding to the event loop.
359
+ */
360
+ stopSync() {
361
+ if (this.#stopped)
362
+ return;
363
+ this.#stopped = true;
364
+ for (const socket of this.#sockets) {
365
+ try {
366
+ socket.destroy();
367
+ }
368
+ catch { }
369
+ }
370
+ this.#sockets.clear();
371
+ this.#clients.clear();
372
+ if (this.#server) {
373
+ const server = this.#server;
78
374
  this.#server = null;
375
+ try {
376
+ server.close();
377
+ }
378
+ catch { }
379
+ }
380
+ // Only remove files this instance actually claimed — see stop().
381
+ if (this.#ownsLock) {
382
+ this.#ownsLock = false;
383
+ try {
384
+ rmSync(this.#socketPath, { force: true });
385
+ }
386
+ catch { }
387
+ try {
388
+ rmSync(this.#lockPath, { force: true });
389
+ }
390
+ catch { }
79
391
  }
80
- // Clean up socket and lock files
81
- await rm(this.#socketPath, { force: true });
82
- await rm(this.#lockPath, { force: true });
83
392
  }
84
393
  /**
85
394
  * Broadcast output to all connected clients.
@@ -95,28 +404,299 @@ export class SocketServer {
95
404
  };
96
405
  this.#broadcast(message);
97
406
  }
407
+ /**
408
+ * Broadcast an error to all connected clients.
409
+ */
410
+ broadcastError(message, code) {
411
+ const error = { type: "error", message, code };
412
+ this.#broadcast(error);
413
+ }
414
+ /**
415
+ * Send an error to one specific client, if it is still connected.
416
+ */
417
+ sendErrorToClient(clientId, message, code) {
418
+ const client = this.#clients.get(clientId);
419
+ if (!client)
420
+ return;
421
+ this.#sendError(client.socket, message, code);
422
+ }
423
+ /**
424
+ * Send a permission ask to one client, if it is still connected and may have it.
425
+ *
426
+ * Silently does nothing for a client that is gone, read-only, or never
427
+ * declared {@link PERMISSION_RELAY_CAPABILITY}: not being asked is the
428
+ * correct outcome for all three, and none of them is an error the asker can
429
+ * act on.
430
+ */
431
+ sendPermissionRequest(clientId, message) {
432
+ const client = this.#clients.get(clientId);
433
+ if (!client || !this.#mayReceivePermissionFrames(client))
434
+ return;
435
+ this.#send(client.socket, message);
436
+ }
437
+ /**
438
+ * Broadcast a permission ask to every client that may answer it.
439
+ *
440
+ * @returns the ids that were actually sent the ask — the asker needs to know
441
+ * whether anybody at all can answer, and an empty result is the
442
+ * honest answer "nobody remote is listening".
443
+ */
444
+ broadcastPermissionRequest(message) {
445
+ const reached = [];
446
+ for (const client of this.#clients.values()) {
447
+ if (!this.#mayReceivePermissionFrames(client))
448
+ continue;
449
+ this.#send(client.socket, message);
450
+ reached.push(client.id);
451
+ }
452
+ return reached;
453
+ }
454
+ /**
455
+ * Broadcast the outcome of a permission ask.
456
+ *
457
+ * Gated exactly like the ask itself: a client that could not have been asked
458
+ * is not told how somebody else's ask ended, and a client that never declared
459
+ * the capability is never sent a frame it cannot decode.
460
+ */
461
+ broadcastPermissionResolved(message) {
462
+ for (const client of this.#clients.values()) {
463
+ if (!this.#mayReceivePermissionFrames(client))
464
+ continue;
465
+ this.#send(client.socket, message);
466
+ }
467
+ }
468
+ /**
469
+ * How many attached clients could answer a permission ask RIGHT NOW.
470
+ *
471
+ * Gated by exactly the predicate emission is gated by, so the count and the
472
+ * fan-out can never disagree. This is what `ExtensionRunner.hasUI()` becomes
473
+ * for a headless attachable session, and it must therefore stay honest in
474
+ * both directions: reporting a client that cannot be asked turns today's loud
475
+ * "no UI available to request approval" block into an instant `false` that
476
+ * the permission gate reports as "User denied approval" — a user action in
477
+ * the transcript that no user took.
478
+ */
479
+ get permissionCapableClientCount() {
480
+ let count = 0;
481
+ for (const client of this.#clients.values()) {
482
+ if (this.#mayReceivePermissionFrames(client))
483
+ count++;
484
+ }
485
+ return count;
486
+ }
487
+ /**
488
+ * Whether this client is eligible for permission frames at all: read-write
489
+ * (a read-only peer may watch but never decide) and capability-declaring.
490
+ */
491
+ #mayReceivePermissionFrames(client) {
492
+ return client.mode !== "read-only" && client.capabilities.includes(PERMISSION_RELAY_CAPABILITY);
493
+ }
98
494
  /**
99
495
  * Set callback for input received from clients.
100
496
  */
101
497
  onInput(callback) {
102
498
  this.#onInput = callback;
103
499
  }
500
+ /**
501
+ * Set callback for a permission answer received from a client.
502
+ */
503
+ onPermissionResponse(callback) {
504
+ this.#onPermissionResponse = callback;
505
+ }
506
+ /**
507
+ * Set callback fired right after a client has been sent `session_metadata`,
508
+ * for the clients that could actually be sent a permission frame.
509
+ *
510
+ * See the attach case for the gate and for what does — and does not —
511
+ * authenticate the peer being replayed to.
512
+ */
513
+ onAttachReplay(callback) {
514
+ this.#onAttachReplay = callback;
515
+ }
516
+ /**
517
+ * Set callback fired when an attached client's connection ends, however it
518
+ * ended — a graceful `detach`, a closed socket, or a socket error.
519
+ *
520
+ * Per-connection bookkeeping outside this class needs the same signal the
521
+ * `client_left` broadcast carries, and it needs it for the same reason: a
522
+ * client that reconnects under the same id is a NEW connection with nothing
523
+ * on its screen. Whatever tracked what that client had already been shown has
524
+ * to forget it here, or the reconnecting peer is never shown it again.
525
+ */
526
+ onClientDisconnect(callback) {
527
+ this.#onClientDisconnect = callback;
528
+ }
104
529
  /**
105
530
  * Get socket path for this session.
106
531
  */
107
532
  get socketPath() {
108
533
  return this.#socketPath;
109
534
  }
535
+ /**
536
+ * Get the session id this socket is bound to.
537
+ */
538
+ get sessionId() {
539
+ return this.#sessionId;
540
+ }
110
541
  /**
111
542
  * Get number of connected clients.
112
543
  */
113
544
  get clientCount() {
114
545
  return this.#clients.size;
115
546
  }
547
+ /**
548
+ * Assert the sockets directory is a real directory, owned by this user, with no
549
+ * group or other permission bits (R35-ALWAYS.3).
550
+ *
551
+ * `lstat`, not `stat`: a symlink pointing at a directory somebody else controls
552
+ * would otherwise pass every check that follows.
553
+ *
554
+ * The one thing this does silently is re-tighten a loose mode on a directory that
555
+ * IS ours — that is not a trust decision, it is the same `chmod` this method has
556
+ * always done, and refusing there would strand every user whose directory predates
557
+ * the mode being enforced. A directory owned by somebody else is refused outright:
558
+ * `chmod`ing it would either fail with EPERM or succeed on a directory planted for
559
+ * us to publish into.
560
+ *
561
+ * Off POSIX there are no uids and file modes do not mean this; the assertion is
562
+ * skipped rather than faked.
563
+ */
564
+ async #assertSocketDirIsOurs(socketDir) {
565
+ const uid = currentUid();
566
+ if (uid === null)
567
+ return;
568
+ let info = await lstat(socketDir).catch((error) => {
569
+ throw new SocketDirectoryUnsafeError(socketDir, `it cannot be inspected (${error?.code ?? "unknown"})`);
570
+ });
571
+ if (!info.isDirectory()) {
572
+ throw new SocketDirectoryUnsafeError(socketDir, "it is not a directory (a symlink is not one either)");
573
+ }
574
+ if (info.uid !== uid) {
575
+ throw new SocketDirectoryUnsafeError(socketDir, `it belongs to uid ${info.uid}, not to uid ${uid}`);
576
+ }
577
+ if ((info.mode & 0o077) !== 0) {
578
+ await chmod(socketDir, 0o700).catch(() => { });
579
+ info = await lstat(socketDir).catch(() => info);
580
+ if ((info.mode & 0o077) !== 0) {
581
+ throw new SocketDirectoryUnsafeError(socketDir, `it is readable or writable by other users (mode ${(info.mode & 0o777).toString(8)})`);
582
+ }
583
+ }
584
+ }
585
+ /**
586
+ * Claim the session lock, or refuse when a live process already holds it.
587
+ *
588
+ * The lock file is created exclusively so two processes racing for the same session id
589
+ * cannot both believe they won. An existing lock is only reaped when its PID is dead
590
+ * (or is our own leftover, e.g. re-binding after a session switch). A lock that exists
591
+ * but names no readable PID counts as held, not as dead: the exclusive create and the
592
+ * PID write are two steps, and reaping in between would steal a live owner's session.
593
+ */
594
+ async #claimLock() {
595
+ // Four lines. The first three are the published contract (pid, cwd, ISO creation
596
+ // time) and both readers still accept exactly three, so locks written by older
597
+ // builds — and the ones already on disk — keep parsing. The 4th is the OWNING
598
+ // PROCESS's start time in epoch milliseconds, which is what lets a reader retire a
599
+ // lock whose pid was recycled by a reboot instead of letting it poison the session
600
+ // id forever. See `lockIsPreBootDebris` in discovery.ts for why that comparison,
601
+ // and not a blanket age bound on readable-pid locks.
602
+ const processStartedAtMs = Math.round(Date.now() - process.uptime() * 1000);
603
+ const contents = `${process.pid}\n${this.#cwd}\n${this.#createdAt.toISOString()}\n${processStartedAtMs}`;
604
+ for (let attempt = 0; attempt < 2; attempt++) {
605
+ try {
606
+ await writeFile(this.#lockPath, contents, { flag: "wx", mode: 0o600 });
607
+ // A leftover socket from a dead owner cannot be connected to; remove it so
608
+ // listen() can bind the path.
609
+ await rm(this.#socketPath, { force: true });
610
+ this.#ownsLock = true;
611
+ return;
612
+ }
613
+ catch (error) {
614
+ if (error?.code !== "EEXIST")
615
+ throw error;
616
+ }
617
+ // A lock file that is not ours is not a claim on our session id. It can only
618
+ // exist here because somebody with more privilege wrote it into a directory
619
+ // start() has already asserted is ours and 0700, so it is debris — and treating
620
+ // it as a live owner is exactly how a session id gets refused forever.
621
+ const foreignLock = await this.#lockIsForeign();
622
+ const ownerPid = foreignLock ? null : await this.#readLockPid();
623
+ if (!foreignLock) {
624
+ if (ownerPid === null) {
625
+ // The lock exists but names no readable PID. The likely cause is a starter that
626
+ // won the exclusive create microseconds ago and has not written its PID yet;
627
+ // reaping it here would hand the same session id to two live processes. Only a
628
+ // lock that has sat unwritten far longer than any write takes counts as debris.
629
+ if (!(await this.#lockIsAbandoned())) {
630
+ throw new SocketSessionBusyError(this.#sessionId, null, this.#socketPath);
631
+ }
632
+ }
633
+ else if (ownerPid !== process.pid && pidOwnership(ownerPid) === "ours") {
634
+ // "ours" and not "alive": a pid we cannot signal is alive but belongs to
635
+ // another user, so it cannot be a draht of ours holding this id — the file is
636
+ // ours and only this uid could have written it. Reading EPERM as a live owner
637
+ // is what made a lock naming root's pid 1 refuse a session id forever,
638
+ // regardless of age. EPERM still means the PROCESS is alive (discovery never
639
+ // reaps another user's session); it just stops meaning the LOCK is live.
640
+ throw new SocketSessionBusyError(this.#sessionId, ownerPid, this.#socketPath);
641
+ }
642
+ }
643
+ // Dead owner, our own leftover, or abandoned debris: reap and retry the create.
644
+ await rm(this.#lockPath, { force: true });
645
+ await rm(this.#socketPath, { force: true });
646
+ }
647
+ throw new Error(`Could not claim the attachable-session lock at ${this.#lockPath}`);
648
+ }
649
+ /**
650
+ * Whether an existing lock with no readable PID is old enough to count as debris
651
+ * rather than as a claim another process is in the middle of writing.
652
+ */
653
+ async #lockIsAbandoned() {
654
+ try {
655
+ const info = await stat(this.#lockPath);
656
+ return Date.now() - info.mtimeMs > UNWRITTEN_LOCK_STALE_MS;
657
+ }
658
+ catch {
659
+ // It vanished while we looked at it: the session id is free again.
660
+ return true;
661
+ }
662
+ }
663
+ /**
664
+ * Whether an existing lock file belongs to another uid, or is not a plain file.
665
+ *
666
+ * Either way it is not a claim this process may honour: see {@link #claimLock}.
667
+ * Off POSIX, where there are no uids, nothing is foreign.
668
+ */
669
+ async #lockIsForeign() {
670
+ const uid = currentUid();
671
+ try {
672
+ const info = await lstat(this.#lockPath);
673
+ if (!info.isFile())
674
+ return true;
675
+ return uid !== null && info.uid !== uid;
676
+ }
677
+ catch {
678
+ // It vanished while we looked at it; the retry re-creates it.
679
+ return false;
680
+ }
681
+ }
682
+ /**
683
+ * Read the PID recorded in an existing lock file, or null when it is unreadable.
684
+ */
685
+ async #readLockPid() {
686
+ try {
687
+ const contents = await readFile(this.#lockPath, "utf-8");
688
+ const pid = Number.parseInt(contents.trim().split("\n")[0], 10);
689
+ return Number.isInteger(pid) ? pid : null;
690
+ }
691
+ catch {
692
+ return null;
693
+ }
694
+ }
116
695
  /**
117
696
  * Handle new client connection.
118
697
  */
119
698
  #handleConnection(socket) {
699
+ this.#sockets.add(socket);
120
700
  let clientId = null;
121
701
  let _mode = "read-write";
122
702
  let buffer = "";
@@ -142,6 +722,7 @@ export class SocketServer {
142
722
  });
143
723
  // Handle client disconnect
144
724
  socket.on("close", () => {
725
+ this.#sockets.delete(socket);
145
726
  if (clientId) {
146
727
  this.#handleClientDisconnect(clientId);
147
728
  }
@@ -161,12 +742,42 @@ export class SocketServer {
161
742
  // Check max clients
162
743
  if (this.#clients.size >= this.#maxClients) {
163
744
  this.#sendError(socket, "Maximum clients reached");
745
+ soakRecord(SOAK_EVENTS.CLIENT_REJECTED, {
746
+ reason: "max_clients",
747
+ sessionId: this.#sessionId,
748
+ clientId: soakLabel(message.clientId),
749
+ maxClients: this.#maxClients,
750
+ clientCount: this.#clients.size,
751
+ }, "warn");
752
+ socket.end();
753
+ return;
754
+ }
755
+ // The mode decides whether this peer's keystrokes reach the session, so
756
+ // it is validated against the closed set rather than tested for one
757
+ // value. A negative `=== "read-only"` check would let `mode: "banana"`
758
+ // attach with full write access on the strength of not being the one
759
+ // string that is refused.
760
+ if (!CLIENT_MODES.includes(message.mode)) {
761
+ this.#sendError(socket, `Unknown client mode ${JSON.stringify(message.mode)}`, "UNKNOWN_CLIENT_MODE");
762
+ soakRecord(SOAK_EVENTS.CLIENT_REJECTED, {
763
+ reason: "unknown_client_mode",
764
+ sessionId: this.#sessionId,
765
+ clientId: soakLabel(message.clientId),
766
+ code: "UNKNOWN_CLIENT_MODE",
767
+ mode: soakLabel(message.mode),
768
+ }, "warn");
164
769
  socket.end();
165
770
  return;
166
771
  }
167
772
  // Check for duplicate client ID
168
773
  if (this.#clients.has(message.clientId)) {
169
774
  this.#sendError(socket, "Client ID already connected");
775
+ soakRecord(SOAK_EVENTS.CLIENT_REJECTED, {
776
+ reason: "duplicate_client_id",
777
+ sessionId: this.#sessionId,
778
+ clientId: soakLabel(message.clientId),
779
+ clientCount: this.#clients.size,
780
+ }, "warn");
170
781
  socket.end();
171
782
  return;
172
783
  }
@@ -176,9 +787,27 @@ export class SocketServer {
176
787
  mode: message.mode,
177
788
  socket,
178
789
  connectedAt: new Date(),
790
+ // Only strings, and only what was actually declared. An absent
791
+ // `capabilities` is an older client, which is exactly the case the
792
+ // gating exists for.
793
+ capabilities: Array.isArray(message.capabilities)
794
+ ? message.capabilities.filter((entry) => typeof entry === "string")
795
+ : [],
179
796
  };
180
797
  this.#clients.set(message.clientId, client);
181
798
  onAttach(message.clientId, message.mode);
799
+ // THE `client_attach` SEAM (R35-ALWAYS.11). Here, and not at the
800
+ // `onAttachReplay` hook one layer up, because this line is reached by EVERY
801
+ // client while that hook is gated on the permission capability — see the note
802
+ // at that callback in `session-integration.ts`. Recorded before the metadata
803
+ // goes out, so an attach that dies mid-write is still counted.
804
+ soakRecord(SOAK_EVENTS.CLIENT_ATTACH, {
805
+ clientId: soakLabel(message.clientId),
806
+ sessionId: this.#sessionId,
807
+ mode: soakLabel(message.mode),
808
+ capabilities: client.capabilities.map(soakLabel),
809
+ clientCount: this.#clients.size,
810
+ });
182
811
  // Send session metadata
183
812
  const metadata = {
184
813
  type: "session_metadata",
@@ -187,6 +816,31 @@ export class SocketServer {
187
816
  createdAt: this.#createdAt.toISOString(),
188
817
  };
189
818
  this.#send(socket, metadata);
819
+ // ── replay (R34-PERM.6) ───────────────────────────────────────────────
820
+ //
821
+ // Whatever holds unanswered asks gets its chance now: the client is
822
+ // registered and has its metadata, so a replayed ask lands on a surface
823
+ // that already knows which session it is looking at. This fires on EVERY
824
+ // attach, including a reattach under a clientId this server has seen
825
+ // before — a reconnecting peer is a new connection with nothing on its
826
+ // screen, and it may be a whole new process.
827
+ //
828
+ // Gated by exactly the predicate emission is gated by, so a client that
829
+ // could not have been sent an ask is not offered a backlog of them
830
+ // either: a read-only peer may watch but never decide, and a client that
831
+ // never declared PERMISSION_RELAY_CAPABILITY cannot render the dialog.
832
+ //
833
+ // WHAT AUTHENTICATES THE CLIENT BEING REPLAYED TO, stated rather than
834
+ // invented: on this socket, nothing beyond the filesystem. The socket dir
835
+ // is 0700 and the socket itself 0600 (see start()), so reaching this line
836
+ // already means the peer runs as this user; `clientId` is SELF-ASSERTED
837
+ // and is an addressing label, not a credential. The device credential
838
+ // lives one hop up, at the gateway's `/attach`. A replay therefore hands
839
+ // a local peer nothing it could not have had by attaching a moment
840
+ // earlier and receiving the same ask in the ordinary broadcast.
841
+ if (this.#mayReceivePermissionFrames(client)) {
842
+ this.#onAttachReplay?.(message.clientId);
843
+ }
190
844
  // Notify other clients
191
845
  const joined = {
192
846
  type: "client_joined",
@@ -223,16 +877,111 @@ export class SocketServer {
223
877
  socket.end();
224
878
  break;
225
879
  }
880
+ case "permission_response": {
881
+ const client = this.#clients.get(message.clientId);
882
+ if (!client || client.socket !== socket) {
883
+ // Either nobody attached under this id, or somebody else did. Both are
884
+ // "you are not that client", said the same way so neither answer is an
885
+ // oracle for which.
886
+ this.#sendError(socket, "Unknown client", "PERMISSION_NOT_ATTACHED");
887
+ this.#recordPermissionRefusal("permission_not_attached", "PERMISSION_NOT_ATTACHED", message);
888
+ return;
889
+ }
890
+ if (client.mode === "read-only") {
891
+ this.#sendError(socket, "Read-only clients cannot answer permissions", "PERMISSION_READ_ONLY");
892
+ this.#recordPermissionRefusal("permission_read_only", "PERMISSION_READ_ONLY", message);
893
+ return;
894
+ }
895
+ if (!client.capabilities.includes(PERMISSION_RELAY_CAPABILITY)) {
896
+ // It was never sent an ask, so it cannot be answering one it saw.
897
+ this.#sendError(socket, `Client did not declare the ${PERMISSION_RELAY_CAPABILITY} capability on attach`, "PERMISSION_NOT_CAPABLE");
898
+ this.#recordPermissionRefusal("permission_not_capable", "PERMISSION_NOT_CAPABLE", message);
899
+ return;
900
+ }
901
+ if (!this.#onPermissionResponse) {
902
+ // Nothing in this process is holding permission asks. Saying so is the
903
+ // point: silence here is indistinguishable from "accepted", and a phone
904
+ // would sit forever on a dialog nobody is going to resolve.
905
+ this.#sendError(socket, `No permission ask ${JSON.stringify(message.requestId)} is pending`, "PERMISSION_UNKNOWN_REQUEST");
906
+ this.#recordPermissionRefusal("permission_unknown_request", "PERMISSION_UNKNOWN_REQUEST", message);
907
+ return;
908
+ }
909
+ this.#onPermissionResponse(message, message.clientId);
910
+ break;
911
+ }
912
+ default: {
913
+ // A client message type this build does not know. Answering is what makes
914
+ // version skew visible in the client→server direction: without this case
915
+ // an unknown frame vanished with no reply at all, so a newer renderer
916
+ // could not tell a draht that had handled its frame from one that had
917
+ // never heard of it.
918
+ const unknown = message.type;
919
+ this.#sendError(socket, `Unknown message type ${JSON.stringify(unknown)}`, "UNKNOWN_MESSAGE_TYPE");
920
+ // Version skew, counted. A week of these from one peer is a renderer that
921
+ // needs upgrading, not a session that is misbehaving.
922
+ soakRecord(SOAK_EVENTS.CLIENT_REJECTED, {
923
+ reason: "unknown_message_type",
924
+ sessionId: this.#sessionId,
925
+ code: "UNKNOWN_MESSAGE_TYPE",
926
+ messageType: soakLabel(unknown),
927
+ }, "warn");
928
+ break;
929
+ }
226
930
  }
227
931
  }
932
+ /**
933
+ * A permission ANSWER that was refused before anything could decide anything.
934
+ *
935
+ * These are the records that carry a `requestId`, which is what lets a verdict
936
+ * join this stream against the durable `permission_resolution` rows the session
937
+ * writes: an ask that has a refused answer here and no resolution there is a
938
+ * decision that never reached the agent. Nothing about the decision itself is
939
+ * duplicated into this log — the session store owns that.
940
+ */
941
+ #recordPermissionRefusal(reason, code, message) {
942
+ soakRecord(SOAK_EVENTS.CLIENT_REJECTED, {
943
+ reason,
944
+ code,
945
+ sessionId: this.#sessionId,
946
+ clientId: soakLabel(message.clientId),
947
+ requestId: soakLabel(message.requestId),
948
+ }, "warn");
949
+ }
228
950
  /**
229
951
  * Handle client disconnect.
952
+ *
953
+ * R34-PERM.6 — DO NOT MAKE THIS TOUCH A PENDING PERMISSION ASK. It removes a
954
+ * CONNECTION and resets what that connection had been shown; it must never
955
+ * drop, resolve, expire or cancel a registry entry. A client that was shown
956
+ * an ask and then died would otherwise take the ask with it: the agent stays
957
+ * parked in `beforeToolCall` forever with no surface left that can answer,
958
+ * which is the wedge documented at `modes/rpc/rpc-mode.ts`. The ask stays
959
+ * PENDING and is replayed to whoever attaches next, including this same
960
+ * client coming back under the same id.
961
+ *
962
+ * Tidying this up so that "leaving cleans up after itself" is exactly the
963
+ * regression this comment exists to stop.
230
964
  */
231
965
  #handleClientDisconnect(clientId) {
232
966
  const client = this.#clients.get(clientId);
233
967
  if (!client)
234
968
  return;
235
969
  this.#clients.delete(clientId);
970
+ // THE `client_detach` SEAM, symmetric with `client_attach` above: one record per
971
+ // connection that was ever registered, whatever ended it — a `detach` frame, a
972
+ // closed socket, or a peer that died. `#clients.get` guards re-entry, so a socket
973
+ // that both errors and closes is recorded once.
974
+ soakRecord(SOAK_EVENTS.CLIENT_DETACH, {
975
+ clientId: soakLabel(clientId),
976
+ sessionId: this.#sessionId,
977
+ mode: soakLabel(client.mode),
978
+ connectedMs: Date.now() - client.connectedAt.getTime(),
979
+ clientCount: this.#clients.size,
980
+ });
981
+ // Per-connection state ONLY — see the note above. Before the other clients
982
+ // are told, because a listener that keeps per-connection state has to have
983
+ // dropped it by the time anything observable about this session changes.
984
+ this.#onClientDisconnect?.(clientId);
236
985
  // Notify other clients
237
986
  const left = {
238
987
  type: "client_left",