@asterxsk/kiln 0.1.0

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 (263) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +170 -0
  3. package/agent/AGENTS.md +67 -0
  4. package/agent/README.md +5 -0
  5. package/agent/extensions/AGENTS.md +68 -0
  6. package/agent/extensions/ask-user/index.ts +418 -0
  7. package/agent/extensions/ask-user/install.ps1 +23 -0
  8. package/agent/extensions/ask-user/install.sh +21 -0
  9. package/agent/extensions/ask-user/package-lock.json +769 -0
  10. package/agent/extensions/ask-user/package.json +19 -0
  11. package/agent/extensions/ask-user/prompt.ts +45 -0
  12. package/agent/extensions/ask-user/tsconfig.json +7 -0
  13. package/agent/extensions/background-terminals/docs/implementation-guide.md +942 -0
  14. package/agent/extensions/background-terminals/index.ts +627 -0
  15. package/agent/extensions/background-terminals/install.ps1 +23 -0
  16. package/agent/extensions/background-terminals/install.sh +21 -0
  17. package/agent/extensions/background-terminals/manager.test.ts +735 -0
  18. package/agent/extensions/background-terminals/output.test.ts +109 -0
  19. package/agent/extensions/background-terminals/package-lock.json +769 -0
  20. package/agent/extensions/background-terminals/package.json +17 -0
  21. package/agent/extensions/background-terminals/prompt.test.ts +125 -0
  22. package/agent/extensions/background-terminals/ps.test.ts +82 -0
  23. package/agent/extensions/background-terminals/result-delivery.test.ts +44 -0
  24. package/agent/extensions/background-terminals/src/domain.ts +87 -0
  25. package/agent/extensions/background-terminals/src/manager.ts +907 -0
  26. package/agent/extensions/background-terminals/src/output.ts +84 -0
  27. package/agent/extensions/background-terminals/src/prompt.ts +142 -0
  28. package/agent/extensions/background-terminals/src/result-delivery.ts +27 -0
  29. package/agent/extensions/background-terminals/src/runtime.ts +36 -0
  30. package/agent/extensions/background-terminals/src/ui/output-view.ts +79 -0
  31. package/agent/extensions/background-terminals/src/ui/ps.ts +621 -0
  32. package/agent/extensions/background-terminals/tsconfig.json +7 -0
  33. package/agent/extensions/destructive/README.md +31 -0
  34. package/agent/extensions/destructive/index.ts +88 -0
  35. package/agent/extensions/destructive/install.ps1 +23 -0
  36. package/agent/extensions/destructive/install.sh +21 -0
  37. package/agent/extensions/file-search/index.spec.ts +443 -0
  38. package/agent/extensions/file-search/index.ts +459 -0
  39. package/agent/extensions/file-search/install.ps1 +23 -0
  40. package/agent/extensions/file-search/install.sh +21 -0
  41. package/agent/extensions/file-search/package-lock.json +2253 -0
  42. package/agent/extensions/file-search/package.json +23 -0
  43. package/agent/extensions/file-search/src/args.ts +122 -0
  44. package/agent/extensions/file-search/src/binaries.ts +422 -0
  45. package/agent/extensions/file-search/src/output.ts +126 -0
  46. package/agent/extensions/file-search/src/process.ts +146 -0
  47. package/agent/extensions/file-search/src/prompt.ts +52 -0
  48. package/agent/extensions/file-search/tsconfig.json +7 -0
  49. package/agent/extensions/goal/README.md +50 -0
  50. package/agent/extensions/goal/index.ts +155 -0
  51. package/agent/extensions/goal/install.ps1 +23 -0
  52. package/agent/extensions/goal/install.sh +21 -0
  53. package/agent/extensions/modelconf/PLAN.md +915 -0
  54. package/agent/extensions/modelconf/README.md +66 -0
  55. package/agent/extensions/modelconf/index.ts +296 -0
  56. package/agent/extensions/modelconf/install.ps1 +23 -0
  57. package/agent/extensions/modelconf/install.sh +21 -0
  58. package/agent/extensions/modelconf/package-lock.json +1809 -0
  59. package/agent/extensions/modelconf/package.json +13 -0
  60. package/agent/extensions/modelconf/src/fuzzy.ts +26 -0
  61. package/agent/extensions/modelconf/src/glob.ts +13 -0
  62. package/agent/extensions/modelconf/src/persistence.test.ts +46 -0
  63. package/agent/extensions/modelconf/src/persistence.ts +164 -0
  64. package/agent/extensions/modelconf/src/ui/ModelConfView.test.ts +75 -0
  65. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -0
  66. package/agent/extensions/modelconf/tsconfig.json +15 -0
  67. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -0
  68. package/agent/extensions/pi-web-access/LICENSE +21 -0
  69. package/agent/extensions/pi-web-access/README.md +470 -0
  70. package/agent/extensions/pi-web-access/SECURITY.md +5 -0
  71. package/agent/extensions/pi-web-access/activity.ts +101 -0
  72. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -0
  73. package/agent/extensions/pi-web-access/banner.png +0 -0
  74. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -0
  75. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -0
  76. package/agent/extensions/pi-web-access/content-find.ts +139 -0
  77. package/agent/extensions/pi-web-access/credential-source.ts +191 -0
  78. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -0
  79. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -0
  80. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -0
  81. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -0
  82. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -0
  83. package/agent/extensions/pi-web-access/exa.ts +526 -0
  84. package/agent/extensions/pi-web-access/extract.ts +1196 -0
  85. package/agent/extensions/pi-web-access/feature-config.ts +29 -0
  86. package/agent/extensions/pi-web-access/fetch-params.ts +111 -0
  87. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -0
  88. package/agent/extensions/pi-web-access/gemini-api.ts +353 -0
  89. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -0
  90. package/agent/extensions/pi-web-access/gemini-search.ts +21 -0
  91. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -0
  92. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -0
  93. package/agent/extensions/pi-web-access/gemini-web.ts +487 -0
  94. package/agent/extensions/pi-web-access/github-api.ts +197 -0
  95. package/agent/extensions/pi-web-access/github-extract.ts +746 -0
  96. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -0
  97. package/agent/extensions/pi-web-access/index.ts +1737 -0
  98. package/agent/extensions/pi-web-access/package-lock.json +5808 -0
  99. package/agent/extensions/pi-web-access/package.json +64 -0
  100. package/agent/extensions/pi-web-access/page-query.ts +96 -0
  101. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -0
  102. package/agent/extensions/pi-web-access/pi-web-fetch-demo.mp4 +0 -0
  103. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -0
  104. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -0
  105. package/agent/extensions/pi-web-access/render-search-error.ts +170 -0
  106. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -0
  107. package/agent/extensions/pi-web-access/search-types.ts +20 -0
  108. package/agent/extensions/pi-web-access/source-check.ts +282 -0
  109. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -0
  110. package/agent/extensions/pi-web-access/storage.ts +521 -0
  111. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -0
  112. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -0
  113. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -0
  114. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -0
  115. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -0
  116. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -0
  117. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -0
  118. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -0
  119. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -0
  120. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -0
  121. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -0
  122. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -0
  123. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -0
  124. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -0
  125. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -0
  126. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -0
  127. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -0
  128. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -0
  129. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -0
  130. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -0
  131. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -0
  132. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -0
  133. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -0
  134. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -0
  135. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -0
  136. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -0
  137. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -0
  138. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -0
  139. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -0
  140. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -0
  141. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -0
  142. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -0
  143. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -0
  144. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -0
  145. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -0
  146. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -0
  147. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -0
  148. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -0
  149. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -0
  150. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -0
  151. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -0
  152. package/agent/extensions/pi-web-access/test/summary-model-scope.test.mjs +106 -0
  153. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -0
  154. package/agent/extensions/pi-web-access/test/web-search-answer-render.test.mjs +66 -0
  155. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -0
  156. package/agent/extensions/pi-web-access/tsconfig.json +11 -0
  157. package/agent/extensions/pi-web-access/utils.ts +451 -0
  158. package/agent/extensions/pi-web-access/video-extract.ts +392 -0
  159. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -0
  160. package/agent/extensions/shared/activity-status.ts +31 -0
  161. package/agent/extensions/shared/child-session.test.ts +270 -0
  162. package/agent/extensions/shared/child-session.ts +148 -0
  163. package/agent/extensions/shared/context-utilization.test.ts +48 -0
  164. package/agent/extensions/shared/context-utilization.ts +47 -0
  165. package/agent/extensions/shared/dashboard-state.ts +99 -0
  166. package/agent/extensions/shared/install.ps1 +23 -0
  167. package/agent/extensions/shared/install.sh +21 -0
  168. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -0
  169. package/agent/extensions/shared/tool-call-timeout.ts +104 -0
  170. package/agent/extensions/skillsconf/README.md +74 -0
  171. package/agent/extensions/skillsconf/index.ts +92 -0
  172. package/agent/extensions/skillsconf/install.ps1 +23 -0
  173. package/agent/extensions/skillsconf/install.sh +21 -0
  174. package/agent/extensions/skillsconf/package-lock.json +1809 -0
  175. package/agent/extensions/skillsconf/package.json +18 -0
  176. package/agent/extensions/skillsconf/src/delete-skill.test.ts +64 -0
  177. package/agent/extensions/skillsconf/src/delete-skill.ts +45 -0
  178. package/agent/extensions/skillsconf/src/filter.test.ts +80 -0
  179. package/agent/extensions/skillsconf/src/filter.ts +74 -0
  180. package/agent/extensions/skillsconf/src/fuzzy.ts +26 -0
  181. package/agent/extensions/skillsconf/src/persistence.test.ts +72 -0
  182. package/agent/extensions/skillsconf/src/persistence.ts +169 -0
  183. package/agent/extensions/skillsconf/src/ui/SkillConfView.test.ts +337 -0
  184. package/agent/extensions/skillsconf/src/ui/SkillConfView.ts +758 -0
  185. package/agent/extensions/skillsconf/src/ui/text-input.ts +91 -0
  186. package/agent/extensions/skillsconf/src/ui/tui-helpers.ts +144 -0
  187. package/agent/extensions/skillsconf/tsconfig.json +15 -0
  188. package/agent/extensions/status line/index.ts +282 -0
  189. package/agent/extensions/status line/install.ps1 +23 -0
  190. package/agent/extensions/status line/install.sh +21 -0
  191. package/agent/extensions/subagents/by-the-way.test.ts +29 -0
  192. package/agent/extensions/subagents/claude.test.ts +119 -0
  193. package/agent/extensions/subagents/codex.test.ts +102 -0
  194. package/agent/extensions/subagents/context-usage.test.ts +107 -0
  195. package/agent/extensions/subagents/docs/design-plan.md +568 -0
  196. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -0
  197. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -0
  198. package/agent/extensions/subagents/index.ts +779 -0
  199. package/agent/extensions/subagents/install.ps1 +23 -0
  200. package/agent/extensions/subagents/install.sh +21 -0
  201. package/agent/extensions/subagents/manager.test.ts +276 -0
  202. package/agent/extensions/subagents/package-lock.json +2244 -0
  203. package/agent/extensions/subagents/package.json +19 -0
  204. package/agent/extensions/subagents/result-delivery.test.ts +27 -0
  205. package/agent/extensions/subagents/src/backend.ts +73 -0
  206. package/agent/extensions/subagents/src/backends/claude.ts +701 -0
  207. package/agent/extensions/subagents/src/backends/codex.ts +1060 -0
  208. package/agent/extensions/subagents/src/backends/pi.ts +575 -0
  209. package/agent/extensions/subagents/src/backends/stub.ts +300 -0
  210. package/agent/extensions/subagents/src/by-the-way.ts +21 -0
  211. package/agent/extensions/subagents/src/domain.ts +253 -0
  212. package/agent/extensions/subagents/src/format.ts +74 -0
  213. package/agent/extensions/subagents/src/manager.ts +736 -0
  214. package/agent/extensions/subagents/src/prompt.ts +92 -0
  215. package/agent/extensions/subagents/src/result-delivery.ts +20 -0
  216. package/agent/extensions/subagents/src/runtime.ts +53 -0
  217. package/agent/extensions/subagents/src/ui/takeover.ts +583 -0
  218. package/agent/extensions/subagents/src/ui/transcript.ts +201 -0
  219. package/agent/extensions/subagents/takeover.test.ts +29 -0
  220. package/agent/extensions/subagents/tsconfig.json +7 -0
  221. package/agent/extensions/taste/index.ts +443 -0
  222. package/agent/extensions/taste/install.ps1 +23 -0
  223. package/agent/extensions/taste/install.sh +21 -0
  224. package/agent/extensions/todo/AGENTS.md +38 -0
  225. package/agent/extensions/todo/LICENSE +21 -0
  226. package/agent/extensions/todo/config.ts +55 -0
  227. package/agent/extensions/todo/index.ts +151 -0
  228. package/agent/extensions/todo/install.ps1 +23 -0
  229. package/agent/extensions/todo/install.sh +21 -0
  230. package/agent/extensions/todo/locales/de.json +17 -0
  231. package/agent/extensions/todo/locales/en.json +15 -0
  232. package/agent/extensions/todo/locales/es.json +17 -0
  233. package/agent/extensions/todo/locales/fr.json +17 -0
  234. package/agent/extensions/todo/locales/pt-BR.json +17 -0
  235. package/agent/extensions/todo/locales/pt.json +17 -0
  236. package/agent/extensions/todo/locales/ru.json +17 -0
  237. package/agent/extensions/todo/locales/uk.json +17 -0
  238. package/agent/extensions/todo/locales/zh.json +17 -0
  239. package/agent/extensions/todo/package-lock.json +3358 -0
  240. package/agent/extensions/todo/package.json +67 -0
  241. package/agent/extensions/todo/state/i18n-bridge.ts +64 -0
  242. package/agent/extensions/todo/state/invariants.ts +20 -0
  243. package/agent/extensions/todo/state/replay.ts +38 -0
  244. package/agent/extensions/todo/state/selectors.ts +107 -0
  245. package/agent/extensions/todo/state/state-reducer.ts +326 -0
  246. package/agent/extensions/todo/state/state.ts +18 -0
  247. package/agent/extensions/todo/state/store.ts +82 -0
  248. package/agent/extensions/todo/state/task-graph.ts +57 -0
  249. package/agent/extensions/todo/todo-overlay.ts +200 -0
  250. package/agent/extensions/todo/todo.ts +155 -0
  251. package/agent/extensions/todo/tool/response-envelope.ts +109 -0
  252. package/agent/extensions/todo/tool/types.ts +206 -0
  253. package/agent/extensions/todo/verify-ref-system.js +0 -0
  254. package/agent/extensions/todo/view/format.ts +177 -0
  255. package/agent/extensions/trim-context/README.md +54 -0
  256. package/agent/extensions/trim-context/index.ts +487 -0
  257. package/agent/extensions/trim-context/install.ps1 +23 -0
  258. package/agent/extensions/trim-context/install.sh +21 -0
  259. package/agent/install.ps1 +527 -0
  260. package/agent/install.sh +511 -0
  261. package/agent/keybindings.json +7 -0
  262. package/bin/kiln.js +359 -0
  263. package/package.json +21 -0
@@ -0,0 +1,1060 @@
1
+ /**
2
+ * Codex backend — real implementation over `codex app-server`.
3
+ *
4
+ * One scoped app-server process owns one persistent Codex thread. The server
5
+ * speaks LF-delimited JSON-RPC over stdio: initialize, thread/start, and
6
+ * turn/start drive runs; v2 item notifications are translated into normalized
7
+ * SubagentEvents. send() queues a follow-up turn while busy, and interrupt uses
8
+ * turn/interrupt with a local deadline so a missing server acknowledgement can
9
+ * never leave the manager stuck in "running".
10
+ */
11
+
12
+ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
13
+ import * as fs from "node:fs";
14
+ import * as path from "node:path";
15
+ import type { Cause, Scope } from "effect";
16
+ import { Effect, Queue, Stream } from "effect";
17
+ import type { SubagentBackend, SubagentSession } from "../backend.ts";
18
+ import type {
19
+ ReasoningEffort,
20
+ RunOutcome,
21
+ SpawnTask,
22
+ SubagentEvent,
23
+ SubagentMeta,
24
+ TranscriptPart,
25
+ } from "../domain.ts";
26
+ import { SendError, SpawnError } from "../domain.ts";
27
+
28
+ const REQUEST_TIMEOUT_MS = 30_000;
29
+ const MODEL_LIST_TIMEOUT_MS = 5_000;
30
+ const INTERRUPT_FALLBACK_MS = 1_500;
31
+ const FORCE_KILL_AFTER_MS = 2_000;
32
+ const PREVIEW_MAX_LENGTH = 1_024;
33
+ /** A protocol line larger than this without a newline means a broken peer. */
34
+ const STDOUT_BUFFER_MAX_BYTES = 4 * 1024 * 1024;
35
+
36
+ type JsonRecord = Record<string, unknown>;
37
+
38
+ interface PendingRequest {
39
+ readonly resolve: (result: JsonRecord) => void;
40
+ readonly reject: (error: Error) => void;
41
+ readonly timer: ReturnType<typeof setTimeout>;
42
+ }
43
+
44
+ interface ToolState {
45
+ readonly name: string;
46
+ output: string;
47
+ }
48
+
49
+ // --- Binary + protocol helpers -----------------------------------------------
50
+
51
+ let cachedCodexBinary: string | null | undefined;
52
+
53
+ function executable(file: string) {
54
+ try {
55
+ fs.accessSync(file, fs.constants.X_OK);
56
+ return true;
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+
62
+ /** Resolve once on first use; availability checks after that are allocation-only. */
63
+ function resolveCodexBinary() {
64
+ if (cachedCodexBinary !== undefined) return cachedCodexBinary ?? undefined;
65
+ const names =
66
+ process.platform === "win32" ? ["codex.exe", "codex.cmd"] : ["codex"];
67
+ for (const directory of (process.env.PATH ?? "").split(path.delimiter)) {
68
+ if (!directory) continue;
69
+ for (const name of names) {
70
+ const candidate = path.join(directory, name);
71
+ if (executable(candidate)) {
72
+ cachedCodexBinary = candidate;
73
+ return candidate;
74
+ }
75
+ }
76
+ }
77
+ cachedCodexBinary = null;
78
+ return undefined;
79
+ }
80
+
81
+ function record(value: unknown): JsonRecord | undefined {
82
+ return value !== null && typeof value === "object" && !Array.isArray(value)
83
+ ? (value as JsonRecord)
84
+ : undefined;
85
+ }
86
+
87
+ function stringValue(value: unknown) {
88
+ return typeof value === "string" ? value : undefined;
89
+ }
90
+
91
+ function numberValue(value: unknown) {
92
+ return typeof value === "number" && Number.isFinite(value)
93
+ ? value
94
+ : undefined;
95
+ }
96
+
97
+ function booleanValue(value: unknown) {
98
+ return typeof value === "boolean" ? value : undefined;
99
+ }
100
+
101
+ function records(value: unknown) {
102
+ return Array.isArray(value)
103
+ ? value.map(record).filter((item): item is JsonRecord => item !== undefined)
104
+ : [];
105
+ }
106
+
107
+ function strings(value: unknown) {
108
+ return Array.isArray(value)
109
+ ? value.filter((item): item is string => typeof item === "string")
110
+ : [];
111
+ }
112
+
113
+ function safeJson(value: unknown) {
114
+ try {
115
+ const text = JSON.stringify(value);
116
+ return text === undefined ? undefined : text.slice(0, PREVIEW_MAX_LENGTH);
117
+ } catch {
118
+ return undefined;
119
+ }
120
+ }
121
+
122
+ function firstLine(value: unknown) {
123
+ if (typeof value !== "string") return undefined;
124
+ const line = value.split("\n").find((candidate) => candidate.trim());
125
+ return line?.trim().slice(0, PREVIEW_MAX_LENGTH);
126
+ }
127
+
128
+ function boundedError(error: unknown) {
129
+ return (error instanceof Error ? error.message : String(error)).slice(
130
+ 0,
131
+ 4096,
132
+ );
133
+ }
134
+
135
+ function protocolError(value: unknown) {
136
+ const error = record(value);
137
+ const message = stringValue(error?.message);
138
+ return boundedError(
139
+ message ?? safeJson(value) ?? "Codex app-server request failed",
140
+ );
141
+ }
142
+
143
+ /** 0.144.3 accepts these effort slugs; individual models expose a subset. */
144
+ function preferredCodexEffort(effort: ReasoningEffort | undefined) {
145
+ switch (effort) {
146
+ case "off":
147
+ case "minimal":
148
+ return "minimal";
149
+ case "low":
150
+ case "medium":
151
+ case "high":
152
+ return effort;
153
+ case "xhigh":
154
+ case "max":
155
+ return "xhigh";
156
+ case undefined:
157
+ return undefined;
158
+ }
159
+ }
160
+
161
+ /** Clamp against model/list because, for example, some models use none instead of minimal. */
162
+ function supportedCodexEffort(
163
+ effort: ReasoningEffort | undefined,
164
+ modelLabel: string | undefined,
165
+ modelList: JsonRecord | undefined,
166
+ ) {
167
+ const preferred = preferredCodexEffort(effort);
168
+ if (!preferred) return undefined;
169
+ const models = records(modelList?.data);
170
+ const model =
171
+ models.find(
172
+ (candidate) =>
173
+ stringValue(candidate.id) === modelLabel ||
174
+ stringValue(candidate.model) === modelLabel,
175
+ ) ?? models.find((candidate) => candidate.isDefault === true);
176
+ if (!model) return preferred;
177
+ const supported = records(model.supportedReasoningEfforts)
178
+ .map((option) => stringValue(option.reasoningEffort))
179
+ .filter((value): value is string => value !== undefined);
180
+ if (supported.includes(preferred)) return preferred;
181
+
182
+ const scale = ["none", "minimal", "low", "medium", "high", "xhigh"] as const;
183
+ const target = scale.indexOf(preferred);
184
+ const candidates = supported
185
+ .map((value) => ({
186
+ value,
187
+ index: scale.indexOf(value as (typeof scale)[number]),
188
+ }))
189
+ .filter((candidate) => candidate.index >= 0)
190
+ .sort((a, b) => {
191
+ const distance = Math.abs(a.index - target) - Math.abs(b.index - target);
192
+ if (distance !== 0) return distance;
193
+ // "off" biases down to none; all other values bias toward more reasoning.
194
+ return effort === "off" ? a.index - b.index : b.index - a.index;
195
+ });
196
+ return candidates[0]?.value ?? preferred;
197
+ }
198
+
199
+ function textInput(text: string) {
200
+ return { type: "text", text, text_elements: [] };
201
+ }
202
+
203
+ /**
204
+ * Parse a `thread/tokenUsage/updated` payload into context occupancy.
205
+ * `tokenUsage.total` accumulates every request in the thread (cached prompt
206
+ * tokens re-counted per request), so it is a cumulative spend counter — not
207
+ * occupancy — and treating it as occupancy pinned the gauge at 100%.
208
+ * `tokenUsage.last` is the most recent request, whose totalTokens is what
209
+ * codex-rs itself uses as `tokens_in_context_window()`.
210
+ */
211
+ export function parseThreadTokenUsage(params: unknown) {
212
+ const usage = record(record(params)?.tokenUsage);
213
+ const last = record(usage?.last);
214
+ return {
215
+ tokens: numberValue(last?.totalTokens),
216
+ contextWindow: numberValue(usage?.modelContextWindow),
217
+ };
218
+ }
219
+
220
+ // --- Item translation --------------------------------------------------------
221
+
222
+ function fileChangePreview(item: JsonRecord) {
223
+ const paths = records(item.changes)
224
+ .map((change) => stringValue(change.path))
225
+ .filter((value): value is string => value !== undefined);
226
+ return paths.length > 0
227
+ ? paths.join(", ").slice(0, PREVIEW_MAX_LENGTH)
228
+ : undefined;
229
+ }
230
+
231
+ function toolDescription(
232
+ item: JsonRecord,
233
+ ): { id: string; name: string; args?: string } | undefined {
234
+ const id = stringValue(item.id);
235
+ const type = stringValue(item.type);
236
+ if (!id || !type) return undefined;
237
+ switch (type) {
238
+ case "commandExecution":
239
+ return { id, name: "shell", args: firstLine(item.command) };
240
+ case "fileChange":
241
+ return { id, name: "apply_patch", args: fileChangePreview(item) };
242
+ case "webSearch":
243
+ return { id, name: "web_search", args: firstLine(item.query) };
244
+ case "mcpToolCall": {
245
+ const server = stringValue(item.server);
246
+ const tool = stringValue(item.tool) ?? "tool";
247
+ return {
248
+ id,
249
+ name: server ? `${server}/${tool}` : tool,
250
+ args: safeJson(item.arguments),
251
+ };
252
+ }
253
+ case "dynamicToolCall": {
254
+ const namespace = stringValue(item.namespace);
255
+ const tool = stringValue(item.tool) ?? "tool";
256
+ return {
257
+ id,
258
+ name: namespace ? `${namespace}/${tool}` : tool,
259
+ args: safeJson(item.arguments),
260
+ };
261
+ }
262
+ default:
263
+ return undefined;
264
+ }
265
+ }
266
+
267
+ function toolOutput(item: JsonRecord, buffered: string) {
268
+ switch (stringValue(item.type)) {
269
+ case "commandExecution":
270
+ return stringValue(item.aggregatedOutput) ?? buffered;
271
+ case "fileChange":
272
+ return fileChangePreview(item);
273
+ case "webSearch":
274
+ return stringValue(item.query);
275
+ case "mcpToolCall":
276
+ return safeJson(item.result ?? item.error);
277
+ case "dynamicToolCall": {
278
+ const text = records(item.contentItems)
279
+ .map((content) => stringValue(content.text))
280
+ .filter((value): value is string => value !== undefined)
281
+ .join("\n");
282
+ return text || safeJson(item.contentItems);
283
+ }
284
+ default:
285
+ return buffered;
286
+ }
287
+ }
288
+
289
+ function toolFailed(item: JsonRecord) {
290
+ const status = stringValue(item.status);
291
+ const exitCode = numberValue(item.exitCode);
292
+ const success = booleanValue(item.success);
293
+ return (
294
+ (exitCode !== undefined && exitCode !== 0) ||
295
+ success === false ||
296
+ status === "failed" ||
297
+ status === "declined" ||
298
+ status === "cancelled"
299
+ );
300
+ }
301
+
302
+ // --- The session -------------------------------------------------------------
303
+
304
+ const makeCodexSession = (
305
+ task: SpawnTask,
306
+ ): Effect.Effect<SubagentSession, SpawnError, Scope.Scope> =>
307
+ Effect.gen(function* () {
308
+ const binary = resolveCodexBinary();
309
+ if (!binary) {
310
+ return yield* new SpawnError({
311
+ message: "codex executable was not found on PATH.",
312
+ });
313
+ }
314
+
315
+ const events = yield* Queue.make<SubagentEvent, Cause.Done>();
316
+ const emit = (event: SubagentEvent) => {
317
+ Queue.offerUnsafe(events, event);
318
+ };
319
+
320
+ const child = yield* Effect.try({
321
+ try: () =>
322
+ spawn(binary, ["app-server", "--stdio"], {
323
+ cwd: task.cwd,
324
+ env: process.env,
325
+ stdio: ["pipe", "pipe", "pipe"],
326
+ windowsHide: true,
327
+ // Own process group on POSIX so teardown can signal the whole
328
+ // tree: a wedged app-server must not orphan a still-running
329
+ // shell command it spawned.
330
+ detached: process.platform !== "win32",
331
+ }),
332
+ catch: (error) => new SpawnError({ message: boundedError(error) }),
333
+ });
334
+
335
+ const state = {
336
+ closed: false,
337
+ closing: false,
338
+ exited: false,
339
+ activeRun: false,
340
+ dispatching: false,
341
+ interruptRequested: false,
342
+ effort: preferredCodexEffort(task.reasoningEffort),
343
+ runSerial: 0,
344
+ activeTurnId: undefined as string | undefined,
345
+ runError: undefined as string | undefined,
346
+ finalText: "",
347
+ lastAssistantText: "",
348
+ pendingPrompts: [] as string[],
349
+ nextRequestId: 0,
350
+ stderr: "",
351
+ meta: {
352
+ backend: "codex",
353
+ modelLabel: task.model,
354
+ } satisfies SubagentMeta as SubagentMeta,
355
+ interruptTimer: undefined as ReturnType<typeof setTimeout> | undefined,
356
+ };
357
+ const pendingRequests = new Map<number, PendingRequest>();
358
+ const tools = new Map<string, ToolState>();
359
+ /** Turns locally settled by the interrupt fallback may still emit late events. */
360
+ const ignoredTurnIds = new Set<string>();
361
+
362
+ const writeMessage = (message: JsonRecord) => {
363
+ if (state.closed || !child.stdin.writable) return false;
364
+ child.stdin.write(`${JSON.stringify(message)}\n`);
365
+ return true;
366
+ };
367
+
368
+ const request = (
369
+ method: string,
370
+ params: JsonRecord,
371
+ timeoutMs = REQUEST_TIMEOUT_MS,
372
+ ) =>
373
+ new Promise<JsonRecord>((resolve, reject) => {
374
+ if (state.closed) {
375
+ reject(new Error("Codex app-server is closed."));
376
+ return;
377
+ }
378
+ const id = ++state.nextRequestId;
379
+ const timer = setTimeout(() => {
380
+ pendingRequests.delete(id);
381
+ reject(new Error(`Codex app-server request ${method} timed out.`));
382
+ }, timeoutMs);
383
+ pendingRequests.set(id, { resolve, reject, timer });
384
+ if (!writeMessage({ id, method, params })) {
385
+ clearTimeout(timer);
386
+ pendingRequests.delete(id);
387
+ reject(new Error("Codex app-server stdin is closed."));
388
+ }
389
+ });
390
+
391
+ const rejectPending = (message: string) => {
392
+ for (const pending of pendingRequests.values()) {
393
+ clearTimeout(pending.timer);
394
+ pending.reject(new Error(message));
395
+ }
396
+ pendingRequests.clear();
397
+ };
398
+
399
+ const queuedView = () =>
400
+ state.pendingPrompts.map((text) => ({
401
+ text,
402
+ kind: "follow-up" as const,
403
+ }));
404
+
405
+ const startNextQueued = () => {
406
+ if (state.closed || state.activeRun) return;
407
+ const next = state.pendingPrompts.shift();
408
+ if (next === undefined) return;
409
+ emit({ _tag: "QueueChanged", queued: queuedView() });
410
+ startRun(next);
411
+ };
412
+
413
+ const settleRun = (outcome: RunOutcome, serial = state.runSerial) => {
414
+ if (!state.activeRun || serial !== state.runSerial) return;
415
+ if (state.interruptTimer) clearTimeout(state.interruptTimer);
416
+ state.interruptTimer = undefined;
417
+ state.activeRun = false;
418
+ state.dispatching = false;
419
+ // A late turn/completed for this turn must not be misattributed to the
420
+ // next queued run (which starts with no activeTurnId to filter on).
421
+ if (state.activeTurnId) ignoredTurnIds.add(state.activeTurnId);
422
+ state.activeTurnId = undefined;
423
+ state.interruptRequested = false;
424
+ tools.clear();
425
+ emit({ _tag: "RunSettled", outcome });
426
+ queueMicrotask(startNextQueued);
427
+ };
428
+
429
+ const sendInterrupt = (serial: number) => {
430
+ const turnId = state.activeTurnId;
431
+ const threadId = state.meta.nativeSessionId;
432
+ if (
433
+ !turnId ||
434
+ !threadId ||
435
+ !state.activeRun ||
436
+ serial !== state.runSerial
437
+ )
438
+ return;
439
+ void request(
440
+ "turn/interrupt",
441
+ { threadId, turnId },
442
+ INTERRUPT_FALLBACK_MS,
443
+ ).catch((error) => {
444
+ if (state.activeRun && serial === state.runSerial) {
445
+ emit({ _tag: "BackendError", message: boundedError(error) });
446
+ }
447
+ });
448
+ };
449
+
450
+ function startRun(text: string) {
451
+ if (state.closed || state.activeRun) return;
452
+ const threadId = state.meta.nativeSessionId;
453
+ if (!threadId) return;
454
+ const serial = ++state.runSerial;
455
+ state.activeRun = true;
456
+ state.dispatching = true;
457
+ state.interruptRequested = false;
458
+ state.activeTurnId = undefined;
459
+ state.runError = undefined;
460
+ state.finalText = "";
461
+ state.lastAssistantText = "";
462
+ emit({ _tag: "UserMessage", text });
463
+ emit({ _tag: "RunStarted" });
464
+
465
+ const params: JsonRecord = {
466
+ threadId,
467
+ input: [textInput(text)],
468
+ ...(state.effort ? { effort: state.effort } : {}),
469
+ };
470
+ void request("turn/start", params).then(
471
+ (result) => {
472
+ const turn = record(result.turn);
473
+ const turnId = stringValue(turn?.id);
474
+ if (!state.activeRun || serial !== state.runSerial) {
475
+ if (turnId) {
476
+ // The run was already settled locally (interrupt fallback or
477
+ // failure), so whatever native turn this response describes is
478
+ // invisible work — stop it unconditionally.
479
+ ignoredTurnIds.add(turnId);
480
+ void request(
481
+ "turn/interrupt",
482
+ { threadId, turnId },
483
+ INTERRUPT_FALLBACK_MS,
484
+ ).catch(() => undefined);
485
+ }
486
+ return;
487
+ }
488
+ state.dispatching = false;
489
+ state.activeTurnId = turnId ?? state.activeTurnId;
490
+ if (state.interruptRequested) sendInterrupt(serial);
491
+ },
492
+ (error) => {
493
+ if (!state.activeRun || serial !== state.runSerial) return;
494
+ const errorText = boundedError(error);
495
+ settleRun(
496
+ state.interruptRequested
497
+ ? {
498
+ _tag: "Interrupted",
499
+ partialText: state.finalText || undefined,
500
+ }
501
+ : {
502
+ _tag: "Failed",
503
+ errorText,
504
+ partialText: state.finalText || undefined,
505
+ },
506
+ serial,
507
+ );
508
+ // A timed-out turn/start means a turn may be running that we can
509
+ // never see or interrupt (no turn id). That session cannot be
510
+ // trusted with further work — kill it; the exit handler reports
511
+ // the death. Explicit protocol rejections keep the session alive.
512
+ if (errorText.includes("timed out")) {
513
+ void terminateChild(child, () => state.exited);
514
+ }
515
+ },
516
+ );
517
+ }
518
+
519
+ const emitToolStart = (item: JsonRecord) => {
520
+ const tool = toolDescription(item);
521
+ if (!tool || tools.has(tool.id)) return;
522
+ tools.set(tool.id, { name: tool.name, output: "" });
523
+ const toolPart: TranscriptPart = {
524
+ type: "toolCall",
525
+ toolId: tool.id,
526
+ name: tool.name,
527
+ argsPreview: tool.args,
528
+ };
529
+ emit({ _tag: "AssistantMessage", parts: [toolPart] });
530
+ emit({
531
+ _tag: "ToolStart",
532
+ toolId: tool.id,
533
+ name: tool.name,
534
+ argsPreview: tool.args,
535
+ });
536
+ };
537
+
538
+ const emitToolEnd = (item: JsonRecord) => {
539
+ const description = toolDescription(item);
540
+ if (!description) return;
541
+ if (!tools.has(description.id)) emitToolStart(item);
542
+ const live = tools.get(description.id);
543
+ const output = toolOutput(item, live?.output ?? "");
544
+ tools.delete(description.id);
545
+ emit({
546
+ _tag: "ToolEnd",
547
+ toolId: description.id,
548
+ name: live?.name ?? description.name,
549
+ isError: toolFailed(item),
550
+ outputPreview: firstLine(output),
551
+ });
552
+ };
553
+
554
+ const handleItemCompleted = (item: JsonRecord) => {
555
+ const type = stringValue(item.type);
556
+ if (type === "agentMessage") {
557
+ const text = stringValue(item.text) ?? "";
558
+ if (text) {
559
+ emit({ _tag: "AssistantMessage", parts: [{ type: "text", text }] });
560
+ state.lastAssistantText = text;
561
+ if (stringValue(item.phase) === "final_answer")
562
+ state.finalText = text;
563
+ }
564
+ return;
565
+ }
566
+ if (type === "reasoning") {
567
+ const thinking = [
568
+ ...strings(item.summary),
569
+ ...strings(item.content),
570
+ ].join("\n");
571
+ if (thinking) {
572
+ emit({
573
+ _tag: "AssistantMessage",
574
+ parts: [{ type: "thinking", text: thinking }],
575
+ });
576
+ }
577
+ return;
578
+ }
579
+ emitToolEnd(item);
580
+ };
581
+
582
+ const handleNotification = (message: JsonRecord) => {
583
+ if (state.closed) return;
584
+ const method = stringValue(message.method);
585
+ const params = record(message.params) ?? {};
586
+ const notificationTurn = record(params.turn);
587
+ const turnId =
588
+ stringValue(params.turnId) ?? stringValue(notificationTurn?.id);
589
+ if (turnId && ignoredTurnIds.has(turnId)) return;
590
+ const belongsToRun =
591
+ method === "error" ||
592
+ method?.startsWith("turn/") === true ||
593
+ method?.startsWith("item/") === true ||
594
+ method === "thread/tokenUsage/updated";
595
+ if (belongsToRun && !state.activeRun) {
596
+ if (turnId) ignoredTurnIds.add(turnId);
597
+ return;
598
+ }
599
+ if (
600
+ belongsToRun &&
601
+ turnId &&
602
+ state.activeTurnId &&
603
+ turnId !== state.activeTurnId
604
+ ) {
605
+ return;
606
+ }
607
+ switch (method) {
608
+ case "thread/started": {
609
+ const thread = record(params.thread);
610
+ const id = stringValue(thread?.id);
611
+ const sessionFilePath = stringValue(thread?.path);
612
+ if (id) state.meta = { ...state.meta, nativeSessionId: id };
613
+ if (sessionFilePath) state.meta = { ...state.meta, sessionFilePath };
614
+ emit({ _tag: "MetaChanged", meta: state.meta });
615
+ break;
616
+ }
617
+ case "thread/settings/updated": {
618
+ const settings = record(params.threadSettings);
619
+ const modelLabel = stringValue(settings?.model);
620
+ if (modelLabel) {
621
+ state.meta = { ...state.meta, modelLabel };
622
+ emit({ _tag: "MetaChanged", meta: { modelLabel } });
623
+ }
624
+ break;
625
+ }
626
+ case "model/rerouted": {
627
+ const modelLabel = stringValue(params.toModel);
628
+ if (modelLabel) {
629
+ state.meta = { ...state.meta, modelLabel };
630
+ emit({ _tag: "MetaChanged", meta: { modelLabel } });
631
+ }
632
+ break;
633
+ }
634
+ case "turn/started": {
635
+ const turn = record(params.turn);
636
+ const startedId = stringValue(turn?.id);
637
+ // Only adopt a turn we are actually waiting on. A stale start from
638
+ // a run the interrupt fallback settled before its turn/start
639
+ // response arrived would otherwise capture activeTurnId and filter
640
+ // out every event of the real next turn.
641
+ if (!state.dispatching && startedId !== state.activeTurnId) {
642
+ if (startedId) ignoredTurnIds.add(startedId);
643
+ break;
644
+ }
645
+ state.activeTurnId = startedId ?? state.activeTurnId;
646
+ state.dispatching = false;
647
+ emit({ _tag: "RunStarted" });
648
+ if (state.interruptRequested) sendInterrupt(state.runSerial);
649
+ break;
650
+ }
651
+ case "item/agentMessage/delta": {
652
+ const delta = stringValue(params.delta);
653
+ if (delta) emit({ _tag: "AssistantDelta", kind: "text", delta });
654
+ break;
655
+ }
656
+ case "item/reasoning/summaryTextDelta":
657
+ case "item/reasoning/textDelta": {
658
+ const delta = stringValue(params.delta);
659
+ if (delta) emit({ _tag: "AssistantDelta", kind: "thinking", delta });
660
+ break;
661
+ }
662
+ case "item/started": {
663
+ const item = record(params.item);
664
+ if (item) emitToolStart(item);
665
+ break;
666
+ }
667
+ case "item/completed": {
668
+ const item = record(params.item);
669
+ if (item) handleItemCompleted(item);
670
+ break;
671
+ }
672
+ case "item/commandExecution/outputDelta":
673
+ case "item/fileChange/outputDelta": {
674
+ const id = stringValue(params.itemId);
675
+ const delta = stringValue(params.delta);
676
+ const tool = id ? tools.get(id) : undefined;
677
+ if (id && tool && delta) {
678
+ tool.output = `${tool.output}${delta}`.slice(-16_384);
679
+ emit({
680
+ _tag: "ToolUpdate",
681
+ toolId: id,
682
+ outputPreview: firstLine(tool.output),
683
+ });
684
+ }
685
+ break;
686
+ }
687
+ case "item/fileChange/patchUpdated": {
688
+ const id = stringValue(params.itemId);
689
+ if (id) {
690
+ emit({
691
+ _tag: "ToolUpdate",
692
+ toolId: id,
693
+ outputPreview: fileChangePreview({ changes: params.changes }),
694
+ });
695
+ }
696
+ break;
697
+ }
698
+ case "item/mcpToolCall/progress": {
699
+ const id = stringValue(params.itemId);
700
+ if (id) {
701
+ emit({
702
+ _tag: "ToolUpdate",
703
+ toolId: id,
704
+ outputPreview: firstLine(params.message),
705
+ });
706
+ }
707
+ break;
708
+ }
709
+ case "thread/tokenUsage/updated": {
710
+ const { tokens, contextWindow } = parseThreadTokenUsage(params);
711
+ if (contextWindow !== undefined) {
712
+ state.meta = { ...state.meta, contextWindow };
713
+ emit({ _tag: "MetaChanged", meta: { contextWindow } });
714
+ }
715
+ emit({ _tag: "UsageChanged", tokens, contextWindow });
716
+ break;
717
+ }
718
+ case "error": {
719
+ const error = record(params.error);
720
+ const messageText = boundedError(
721
+ stringValue(error?.message) ?? "Codex run failed",
722
+ );
723
+ if (params.willRetry !== true) state.runError = messageText;
724
+ emit({ _tag: "BackendError", message: messageText });
725
+ break;
726
+ }
727
+ case "turn/completed": {
728
+ const turn = record(params.turn);
729
+ const status = stringValue(turn?.status);
730
+ const error = record(turn?.error);
731
+ const partialText =
732
+ state.finalText || state.lastAssistantText || undefined;
733
+ if (state.interruptRequested || status === "interrupted") {
734
+ settleRun({ _tag: "Interrupted", partialText });
735
+ } else if (status === "failed") {
736
+ settleRun({
737
+ _tag: "Failed",
738
+ errorText: boundedError(
739
+ state.runError ??
740
+ stringValue(error?.message) ??
741
+ "Codex run failed",
742
+ ),
743
+ partialText,
744
+ });
745
+ } else {
746
+ settleRun({
747
+ _tag: "Completed",
748
+ finalText: state.finalText || state.lastAssistantText,
749
+ });
750
+ }
751
+ break;
752
+ }
753
+ }
754
+ };
755
+
756
+ const handleServerRequest = (message: JsonRecord) => {
757
+ const id = message.id;
758
+ if (typeof id !== "number" && typeof id !== "string") return;
759
+ const method = stringValue(message.method);
760
+ if (
761
+ method === "item/commandExecution/requestApproval" ||
762
+ method === "item/fileChange/requestApproval"
763
+ ) {
764
+ writeMessage({ id, result: { decision: "decline" } });
765
+ return;
766
+ }
767
+ writeMessage({
768
+ id,
769
+ error: {
770
+ code: -32601,
771
+ message: `Unsupported headless server request: ${method ?? "unknown"}`,
772
+ },
773
+ });
774
+ };
775
+
776
+ const handleLine = (line: string) => {
777
+ if (!line.trim()) return;
778
+ let parsed: unknown;
779
+ try {
780
+ parsed = JSON.parse(line);
781
+ } catch {
782
+ emit({
783
+ _tag: "BackendError",
784
+ message: `Invalid Codex protocol line: ${line.slice(0, 512)}`,
785
+ });
786
+ return;
787
+ }
788
+ const message = record(parsed);
789
+ if (!message) return;
790
+ const id = numberValue(message.id);
791
+ if (id !== undefined && pendingRequests.has(id)) {
792
+ const pending = pendingRequests.get(id);
793
+ if (!pending) return;
794
+ pendingRequests.delete(id);
795
+ clearTimeout(pending.timer);
796
+ if (message.error !== undefined)
797
+ pending.reject(new Error(protocolError(message.error)));
798
+ else pending.resolve(record(message.result) ?? {});
799
+ return;
800
+ }
801
+ if (message.id !== undefined && message.method !== undefined)
802
+ handleServerRequest(message);
803
+ else if (message.method !== undefined) handleNotification(message);
804
+ };
805
+
806
+ const failForProcessExit = (detail: string) => {
807
+ if (state.exited) return;
808
+ state.exited = true;
809
+ rejectPending(detail);
810
+ if (state.closing) return;
811
+ state.closed = true;
812
+ state.pendingPrompts = [];
813
+ emit({ _tag: "QueueChanged", queued: [] });
814
+ if (state.activeRun) {
815
+ settleRun({
816
+ _tag: "Failed",
817
+ errorText: boundedError(detail),
818
+ partialText: state.finalText || state.lastAssistantText || undefined,
819
+ });
820
+ }
821
+ Queue.endUnsafe(events);
822
+ };
823
+
824
+ let stdoutBuffer = "";
825
+ child.stdout.setEncoding("utf8");
826
+ child.stdout.on("data", (chunk: string) => {
827
+ stdoutBuffer += chunk;
828
+ while (true) {
829
+ const newline = stdoutBuffer.indexOf("\n");
830
+ if (newline < 0) break;
831
+ const line = stdoutBuffer.slice(0, newline).replace(/\r$/, "");
832
+ stdoutBuffer = stdoutBuffer.slice(newline + 1);
833
+ handleLine(line);
834
+ }
835
+ if (stdoutBuffer.length > STDOUT_BUFFER_MAX_BYTES) {
836
+ // A frame this large with no newline is protocol corruption, and an
837
+ // unbounded buffer is a memory leak. Session-fatal: the exit handler
838
+ // settles any active run.
839
+ stdoutBuffer = "";
840
+ void terminateChild(child, () => state.exited);
841
+ }
842
+ });
843
+ child.stderr.setEncoding("utf8");
844
+ child.stderr.on("data", (chunk: string) => {
845
+ state.stderr = `${state.stderr}${chunk}`.slice(-4096);
846
+ });
847
+ child.once("error", (error) =>
848
+ failForProcessExit(`Codex app-server failed: ${boundedError(error)}`),
849
+ );
850
+ child.once("exit", (code, signal) => {
851
+ const suffix = firstLine(state.stderr);
852
+ failForProcessExit(
853
+ `Codex app-server exited (${signal ?? `code ${code ?? "unknown"}`})${suffix ? `: ${suffix}` : ""}`,
854
+ );
855
+ });
856
+
857
+ yield* Effect.addFinalizer(() =>
858
+ Effect.promise(async () => {
859
+ if (state.closing) return;
860
+ state.closing = true;
861
+ if (state.interruptTimer) clearTimeout(state.interruptTimer);
862
+ // Settle before marking closed so the run gets the correct
863
+ // "Interrupted" outcome instead of the pump's generic fallback.
864
+ if (state.activeRun) {
865
+ settleRun({
866
+ _tag: "Interrupted",
867
+ partialText:
868
+ state.finalText || state.lastAssistantText || undefined,
869
+ });
870
+ }
871
+ state.closed = true;
872
+ rejectPending("Codex session closed.");
873
+ await terminateChild(child, () => state.exited);
874
+ Queue.endUnsafe(events);
875
+ }),
876
+ );
877
+
878
+ const threadResult = yield* Effect.tryPromise({
879
+ try: async () => {
880
+ await request("initialize", {
881
+ clientInfo: {
882
+ name: "pi-subagents",
883
+ title: "pi subagent",
884
+ version: "2.0.0",
885
+ },
886
+ capabilities: { experimentalApi: true },
887
+ });
888
+ writeMessage({ method: "initialized" });
889
+ // Headless children cannot answer approval prompts. The caller
890
+ // already chose to launch an autonomous subagent, so give the thread
891
+ // full workspace access without interactive approval requests.
892
+ return request("thread/start", {
893
+ cwd: task.cwd,
894
+ approvalPolicy: "never",
895
+ sandbox: "danger-full-access",
896
+ ephemeral: false,
897
+ ...(task.model ? { model: task.model } : {}),
898
+ });
899
+ },
900
+ catch: (error) => new SpawnError({ message: boundedError(error) }),
901
+ });
902
+
903
+ const thread = record(threadResult.thread);
904
+ const nativeSessionId = stringValue(thread?.id);
905
+ if (!nativeSessionId) {
906
+ return yield* new SpawnError({
907
+ message: "Codex thread/start returned no thread id.",
908
+ });
909
+ }
910
+ state.meta = {
911
+ backend: "codex",
912
+ modelLabel: stringValue(threadResult.model) ?? task.model,
913
+ sessionFilePath: stringValue(thread?.path),
914
+ nativeSessionId,
915
+ };
916
+ if (task.reasoningEffort) {
917
+ // Optional capability probe: never let a slow/unsupported model/list
918
+ // hold up the spawn (and its concurrency reservation) for the full
919
+ // request timeout; the unclamped preferred effort is a fine fallback.
920
+ const modelList = yield* Effect.tryPromise(() =>
921
+ request("model/list", { includeHidden: true }, MODEL_LIST_TIMEOUT_MS),
922
+ ).pipe(Effect.orElseSucceed(() => undefined));
923
+ state.effort = supportedCodexEffort(
924
+ task.reasoningEffort,
925
+ state.meta.modelLabel,
926
+ modelList,
927
+ );
928
+ }
929
+ emit({ _tag: "MetaChanged", meta: state.meta });
930
+ startRun(task.prompt);
931
+
932
+ return {
933
+ meta: Effect.sync(() => state.meta),
934
+ events: Stream.fromQueue(events),
935
+ send: (text) =>
936
+ Effect.suspend((): Effect.Effect<void, SendError> => {
937
+ if (state.closed) {
938
+ return new SendError({ message: "Subagent session is closed." });
939
+ }
940
+ if (state.activeRun) {
941
+ state.pendingPrompts.push(text);
942
+ emit({ _tag: "QueueChanged", queued: queuedView() });
943
+ return Effect.void;
944
+ }
945
+ return Effect.sync(() => startRun(text));
946
+ }),
947
+ interrupt: Effect.promise(async () => {
948
+ if (state.closed || !state.activeRun) return;
949
+ const serial = state.runSerial;
950
+ state.pendingPrompts = [];
951
+ emit({ _tag: "QueueChanged", queued: [] });
952
+ state.interruptRequested = true;
953
+ sendInterrupt(serial);
954
+ if (state.interruptTimer) clearTimeout(state.interruptTimer);
955
+ state.interruptTimer = setTimeout(() => {
956
+ if (state.activeRun && serial === state.runSerial) {
957
+ if (state.activeTurnId) ignoredTurnIds.add(state.activeTurnId);
958
+ settleRun({
959
+ _tag: "Interrupted",
960
+ partialText:
961
+ state.finalText || state.lastAssistantText || undefined,
962
+ });
963
+ // The server never acknowledged the interrupt, so the native
964
+ // turn may still be executing tools. A session that ignores
965
+ // interrupts cannot be trusted — kill it rather than let
966
+ // invisible work continue behind a "settled" run.
967
+ void terminateChild(child, () => state.exited);
968
+ }
969
+ }, INTERRUPT_FALLBACK_MS);
970
+ }),
971
+ } satisfies SubagentSession;
972
+ });
973
+
974
+ /** Signal the whole process group on POSIX so tool descendants (shell
975
+ * commands the app-server spawned) die with it; a wedged or force-killed
976
+ * server must not orphan a still-running command in the workspace. */
977
+ function killTree(
978
+ child: ChildProcessWithoutNullStreams,
979
+ signal: NodeJS.Signals,
980
+ ) {
981
+ if (process.platform === "win32" && child.pid) {
982
+ try {
983
+ const killer = spawn(
984
+ "taskkill",
985
+ [
986
+ "/pid",
987
+ String(child.pid),
988
+ "/T",
989
+ ...(signal === "SIGKILL" ? ["/F"] : []),
990
+ ],
991
+ { stdio: "ignore", windowsHide: true },
992
+ );
993
+ const killDirect = () => {
994
+ try {
995
+ child.kill(signal);
996
+ } catch {
997
+ // Process may already be gone.
998
+ }
999
+ };
1000
+ killer.once("error", killDirect);
1001
+ killer.once("exit", (code) => {
1002
+ if (code !== 0) killDirect();
1003
+ });
1004
+ killer.unref();
1005
+ return;
1006
+ } catch {
1007
+ // Fall through to a direct signal when taskkill cannot be launched.
1008
+ }
1009
+ }
1010
+ if (process.platform !== "win32" && child.pid) {
1011
+ try {
1012
+ process.kill(-child.pid, signal);
1013
+ return;
1014
+ } catch {
1015
+ // Group may already be gone; fall through to the direct signal.
1016
+ }
1017
+ }
1018
+ try {
1019
+ child.kill(signal);
1020
+ } catch {
1021
+ // Process may already be gone.
1022
+ }
1023
+ }
1024
+
1025
+ /** SIGTERM is normally enough; the second deadline covers a wedged Rust process. */
1026
+ function terminateChild(
1027
+ child: ChildProcessWithoutNullStreams,
1028
+ exited: () => boolean,
1029
+ ) {
1030
+ if (exited()) return Promise.resolve();
1031
+ return new Promise<void>((resolve) => {
1032
+ let done = false;
1033
+ let forceTimer: ReturnType<typeof setTimeout> | undefined;
1034
+ let lastTimer: ReturnType<typeof setTimeout> | undefined;
1035
+ const finish = () => {
1036
+ if (done) return;
1037
+ done = true;
1038
+ if (forceTimer) clearTimeout(forceTimer);
1039
+ if (lastTimer) clearTimeout(lastTimer);
1040
+ resolve();
1041
+ };
1042
+ child.once("exit", finish);
1043
+ killTree(child, "SIGTERM");
1044
+ forceTimer = setTimeout(() => {
1045
+ if (!exited()) killTree(child, "SIGKILL");
1046
+ }, FORCE_KILL_AFTER_MS);
1047
+ lastTimer = setTimeout(finish, FORCE_KILL_AFTER_MS + 500);
1048
+ });
1049
+ }
1050
+
1051
+ export const codexBackend: SubagentBackend = {
1052
+ name: "codex",
1053
+ capabilities: {
1054
+ steering: false,
1055
+ modelSelection: true,
1056
+ reasoningEffort: true,
1057
+ },
1058
+ available: Effect.sync(() => resolveCodexBinary() !== undefined),
1059
+ spawn: makeCodexSession,
1060
+ };