@jini-ai/agent-runtime 0.7.2 → 0.7.3-next.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 (405) hide show
  1. package/CHANGELOG.md +3 -13
  2. package/README.md +1 -0
  3. package/dist/acp-model-probe.d.ts +2 -3
  4. package/dist/acp-model-probe.js +1 -1
  5. package/dist/agent-protocol/acp/account-failure.d.ts +3 -1
  6. package/dist/agent-protocol/acp/account-failure.js +1 -1
  7. package/dist/agent-protocol/acp/constants.d.ts +3 -1
  8. package/dist/agent-protocol/acp/constants.js +2 -0
  9. package/dist/agent-protocol/acp/index.d.ts +2 -1
  10. package/dist/agent-protocol/acp/index.js +2 -1
  11. package/dist/agent-protocol/acp/json.d.ts +26 -7
  12. package/dist/agent-protocol/acp/json.js +11 -11
  13. package/dist/agent-protocol/acp/models.d.ts +26 -6
  14. package/dist/agent-protocol/acp/models.js +157 -129
  15. package/dist/agent-protocol/acp/rpc.d.ts +37 -9
  16. package/dist/agent-protocol/acp/rpc.js +19 -16
  17. package/dist/agent-protocol/acp/session-params.d.ts +4 -1
  18. package/dist/agent-protocol/acp/session-params.js +1 -1
  19. package/dist/agent-protocol/acp/session-permission.d.ts +13 -0
  20. package/dist/agent-protocol/acp/session-permission.js +110 -0
  21. package/dist/agent-protocol/acp/session-results.d.ts +61 -0
  22. package/dist/agent-protocol/acp/session-results.js +226 -0
  23. package/dist/agent-protocol/acp/session-run.d.ts +92 -0
  24. package/dist/agent-protocol/acp/session-run.js +555 -0
  25. package/dist/agent-protocol/acp/session-state.d.ts +9 -0
  26. package/dist/agent-protocol/acp/session-state.js +29 -0
  27. package/dist/agent-protocol/acp/session-text-updates.d.ts +56 -0
  28. package/dist/agent-protocol/acp/session-text-updates.js +119 -0
  29. package/dist/agent-protocol/acp/session-tool-updates.d.ts +21 -0
  30. package/dist/agent-protocol/acp/session-tool-updates.js +90 -0
  31. package/dist/agent-protocol/acp/session-types.d.ts +166 -0
  32. package/dist/agent-protocol/acp/session-types.js +4 -0
  33. package/dist/agent-protocol/acp/session.d.ts +4 -280
  34. package/dist/agent-protocol/acp/session.js +65 -998
  35. package/dist/agent-protocol/acp/text-suppression.d.ts +5 -1
  36. package/dist/agent-protocol/acp/text-suppression.js +1 -1
  37. package/dist/agent-protocol/acp/updates.d.ts +43 -12
  38. package/dist/agent-protocol/acp/updates.js +34 -34
  39. package/dist/agent-protocol/core/json-line-stream.d.ts +133 -36
  40. package/dist/agent-protocol/core/json-line-stream.js +62 -62
  41. package/dist/agent-protocol/pi-rpc/events.d.ts +14 -4
  42. package/dist/agent-protocol/pi-rpc/events.js +14 -14
  43. package/dist/agent-protocol/pi-rpc/internal.d.ts +9 -3
  44. package/dist/agent-protocol/pi-rpc/internal.js +3 -3
  45. package/dist/agent-protocol/pi-rpc/models.d.ts +3 -17
  46. package/dist/agent-protocol/pi-rpc/models.js +1 -45
  47. package/dist/agent-protocol/pi-rpc/session.d.ts +36 -12
  48. package/dist/agent-protocol/pi-rpc/session.js +134 -122
  49. package/dist/amr-model-cache.d.ts +1 -1
  50. package/dist/anthropic-live-models.d.ts +8 -3
  51. package/dist/anthropic-live-models.js +0 -0
  52. package/dist/auth-common.d.ts +2 -0
  53. package/dist/auth-common.js +2 -0
  54. package/dist/auth.d.ts +7 -34
  55. package/dist/auth.js +25 -139
  56. package/dist/capabilities.d.ts +1 -1
  57. package/dist/claude-code-models.d.ts +13 -5
  58. package/dist/claude-code-models.js +12 -10
  59. package/dist/claude-filesystem-policy.d.ts +1 -1
  60. package/dist/claude-stream-frames.d.ts +125 -0
  61. package/dist/claude-stream-frames.js +327 -0
  62. package/dist/claude-stream-handler.d.ts +19 -0
  63. package/dist/claude-stream-handler.js +480 -0
  64. package/dist/claude-stream.d.ts +3 -72
  65. package/dist/claude-stream.js +2 -801
  66. package/dist/core/model-discovery-shared.d.ts +14 -8
  67. package/dist/core/model-discovery-shared.js +6 -9
  68. package/dist/core/omit-keys.d.ts +4 -1
  69. package/dist/core/omit-keys.js +1 -1
  70. package/dist/defs/aider/executable.d.ts +2 -0
  71. package/dist/defs/aider/executable.js +2 -0
  72. package/dist/defs/aider/model-discovery.d.ts +3 -0
  73. package/dist/defs/aider/model-discovery.js +6 -0
  74. package/dist/defs/aider.d.ts +10 -10
  75. package/dist/defs/amp/index.d.ts +35 -0
  76. package/dist/defs/amp/index.js +75 -0
  77. package/dist/defs/amp.d.ts +1 -34
  78. package/dist/defs/amp.js +1 -74
  79. package/dist/defs/amr/executable-resolution.d.ts +7 -0
  80. package/dist/defs/amr/executable-resolution.js +50 -0
  81. package/dist/defs/amr/executable.d.ts +2 -0
  82. package/dist/defs/amr/executable.js +2 -0
  83. package/dist/defs/amr/index.d.ts +69 -0
  84. package/dist/defs/amr/index.js +279 -0
  85. package/dist/defs/amr/model-discovery.d.ts +3 -0
  86. package/dist/defs/amr/model-discovery.js +4 -0
  87. package/dist/defs/amr.d.ts +1 -68
  88. package/dist/defs/amr.js +1 -291
  89. package/dist/defs/antigravity/auth.d.ts +14 -0
  90. package/dist/defs/antigravity/auth.js +47 -0
  91. package/dist/defs/antigravity/index.d.ts +9 -9
  92. package/dist/defs/antigravity/index.js +3 -3
  93. package/dist/defs/antigravity/model-discovery.d.ts +3 -0
  94. package/dist/defs/antigravity/model-discovery.js +5 -0
  95. package/dist/defs/auggie/executable.d.ts +2 -0
  96. package/dist/defs/auggie/executable.js +2 -0
  97. package/dist/defs/auggie.d.ts +13 -13
  98. package/dist/defs/auggie.js +2 -9
  99. package/dist/defs/claude/auth.d.ts +15 -0
  100. package/dist/defs/claude/auth.js +47 -0
  101. package/dist/defs/claude/executable.d.ts +2 -0
  102. package/dist/defs/claude/executable.js +2 -0
  103. package/dist/defs/claude/model-discovery.d.ts +3 -0
  104. package/dist/defs/claude/model-discovery.js +20 -0
  105. package/dist/defs/claude-compatible-args.d.ts +10 -6
  106. package/dist/defs/claude-compatible-args.js +5 -5
  107. package/dist/defs/claude.d.ts +11 -11
  108. package/dist/defs/claude.js +5 -4
  109. package/dist/defs/cline/executable.d.ts +2 -0
  110. package/dist/defs/cline/executable.js +2 -0
  111. package/dist/defs/cline.d.ts +13 -13
  112. package/dist/defs/cline.js +2 -9
  113. package/dist/defs/codebuddy/executable.d.ts +2 -0
  114. package/dist/defs/codebuddy/executable.js +2 -0
  115. package/dist/defs/codebuddy/index.d.ts +48 -0
  116. package/dist/defs/codebuddy/index.js +121 -0
  117. package/dist/defs/codebuddy/model-discovery.d.ts +3 -0
  118. package/dist/defs/codebuddy/model-discovery.js +5 -0
  119. package/dist/defs/codebuddy.d.ts +1 -47
  120. package/dist/defs/codebuddy.js +1 -120
  121. package/dist/defs/codex/auth.d.ts +4 -0
  122. package/dist/defs/codex/auth.js +2 -0
  123. package/dist/defs/codex/event-stream.d.ts +10 -0
  124. package/dist/defs/codex/event-stream.js +353 -0
  125. package/dist/defs/codex/executable-resolution.d.ts +7 -0
  126. package/dist/defs/codex/executable-resolution.js +37 -0
  127. package/dist/defs/codex/executable.d.ts +2 -0
  128. package/dist/defs/codex/executable.js +2 -0
  129. package/dist/defs/codex/launch.d.ts +3 -0
  130. package/dist/defs/codex/launch.js +155 -0
  131. package/dist/defs/codex/model-discovery.d.ts +3 -0
  132. package/dist/defs/codex/model-discovery.js +11 -0
  133. package/dist/defs/codex/options.d.ts +11 -0
  134. package/dist/defs/codex/options.js +5 -0
  135. package/dist/defs/codex.d.ts +18 -11
  136. package/dist/defs/codex.js +32 -29
  137. package/dist/defs/crush/executable.d.ts +2 -0
  138. package/dist/defs/crush/executable.js +2 -0
  139. package/dist/defs/crush/model-discovery.d.ts +3 -0
  140. package/dist/defs/crush/model-discovery.js +6 -0
  141. package/dist/defs/crush.d.ts +10 -10
  142. package/dist/defs/cursor-agent/auth.d.ts +13 -0
  143. package/dist/defs/cursor-agent/auth.js +22 -0
  144. package/dist/defs/cursor-agent/event-stream.d.ts +8 -0
  145. package/dist/defs/cursor-agent/event-stream.js +104 -0
  146. package/dist/defs/cursor-agent/executable.d.ts +2 -0
  147. package/dist/defs/cursor-agent/executable.js +2 -0
  148. package/dist/defs/cursor-agent/model-discovery.d.ts +3 -0
  149. package/dist/defs/cursor-agent/model-discovery.js +5 -0
  150. package/dist/defs/cursor-agent.d.ts +11 -13
  151. package/dist/defs/cursor-agent.js +1 -1
  152. package/dist/defs/deepseek/auth.d.ts +13 -0
  153. package/dist/defs/deepseek/auth.js +18 -0
  154. package/dist/defs/deepseek/executable.d.ts +2 -0
  155. package/dist/defs/deepseek/executable.js +2 -0
  156. package/dist/defs/deepseek/model-discovery.d.ts +3 -0
  157. package/dist/defs/deepseek/model-discovery.js +5 -0
  158. package/dist/defs/deepseek.d.ts +10 -10
  159. package/dist/defs/devin/executable.d.ts +2 -0
  160. package/dist/defs/devin/executable.js +2 -0
  161. package/dist/defs/devin.d.ts +15 -15
  162. package/dist/defs/devin.js +3 -10
  163. package/dist/defs/droid/executable.d.ts +2 -0
  164. package/dist/defs/droid/executable.js +2 -0
  165. package/dist/defs/droid/model-discovery.d.ts +3 -0
  166. package/dist/defs/droid/model-discovery.js +5 -0
  167. package/dist/defs/droid.d.ts +10 -10
  168. package/dist/defs/gemini/event-stream.d.ts +14 -0
  169. package/dist/defs/gemini/event-stream.js +193 -0
  170. package/dist/defs/goose/executable.d.ts +2 -0
  171. package/dist/defs/goose/executable.js +2 -0
  172. package/dist/defs/goose.d.ts +13 -13
  173. package/dist/defs/goose.js +2 -9
  174. package/dist/defs/grok-build/model-discovery.d.ts +3 -0
  175. package/dist/defs/grok-build/model-discovery.js +5 -0
  176. package/dist/defs/grok-build.d.ts +10 -10
  177. package/dist/defs/hermes/executable.d.ts +2 -0
  178. package/dist/defs/hermes/executable.js +2 -0
  179. package/dist/defs/hermes/index.d.ts +34 -0
  180. package/dist/defs/hermes/index.js +57 -0
  181. package/dist/defs/hermes.d.ts +1 -33
  182. package/dist/defs/hermes.js +1 -56
  183. package/dist/defs/index.d.ts +1 -0
  184. package/dist/defs/index.js +1 -0
  185. package/dist/defs/kilo/executable.d.ts +2 -0
  186. package/dist/defs/kilo/executable.js +2 -0
  187. package/dist/defs/kilo.d.ts +13 -13
  188. package/dist/defs/kilo.js +2 -9
  189. package/dist/defs/kimi/event-stream.d.ts +3 -0
  190. package/dist/defs/kimi/event-stream.js +46 -0
  191. package/dist/defs/kimi/executable.d.ts +2 -0
  192. package/dist/defs/kimi/executable.js +2 -0
  193. package/dist/defs/kimi.d.ts +13 -13
  194. package/dist/defs/kimi.js +2 -9
  195. package/dist/defs/kiro/executable.d.ts +2 -0
  196. package/dist/defs/kiro/executable.js +2 -0
  197. package/dist/defs/kiro.d.ts +13 -13
  198. package/dist/defs/kiro.js +2 -9
  199. package/dist/defs/mimo/executable.d.ts +2 -0
  200. package/dist/defs/mimo/executable.js +2 -0
  201. package/dist/defs/mimo/model-discovery.d.ts +3 -0
  202. package/dist/defs/mimo/model-discovery.js +7 -0
  203. package/dist/defs/mimo.d.ts +10 -10
  204. package/dist/defs/opencode/event-stream.d.ts +8 -0
  205. package/dist/defs/opencode/event-stream.js +108 -0
  206. package/dist/defs/opencode/executable.d.ts +2 -0
  207. package/dist/defs/opencode/executable.js +2 -0
  208. package/dist/defs/opencode/model-discovery.d.ts +4 -0
  209. package/dist/defs/opencode/model-discovery.js +14 -0
  210. package/dist/defs/opencode-acp.d.ts +42 -0
  211. package/dist/defs/opencode-acp.js +23 -0
  212. package/dist/defs/opencode.d.ts +9 -9
  213. package/dist/defs/pi/executable.d.ts +2 -0
  214. package/dist/defs/pi/executable.js +2 -0
  215. package/dist/defs/pi/model-discovery.d.ts +4 -0
  216. package/dist/defs/pi/model-discovery.js +16 -0
  217. package/dist/defs/pi/options.d.ts +11 -0
  218. package/dist/defs/pi/options.js +5 -0
  219. package/dist/defs/pi.d.ts +10 -10
  220. package/dist/defs/qoder/executable.d.ts +2 -0
  221. package/dist/defs/qoder/executable.js +2 -0
  222. package/dist/defs/qoder/model-discovery.d.ts +3 -0
  223. package/dist/defs/qoder/model-discovery.js +7 -0
  224. package/dist/defs/qoder.d.ts +9 -9
  225. package/dist/defs/qwen/executable.d.ts +2 -0
  226. package/dist/defs/qwen/executable.js +2 -0
  227. package/dist/defs/qwen/model-discovery.d.ts +3 -0
  228. package/dist/defs/qwen/model-discovery.js +7 -0
  229. package/dist/defs/qwen.d.ts +10 -10
  230. package/dist/defs/reasonix/auth.d.ts +13 -0
  231. package/dist/defs/reasonix/auth.js +18 -0
  232. package/dist/defs/reasonix/executable.d.ts +2 -0
  233. package/dist/defs/reasonix/executable.js +2 -0
  234. package/dist/defs/reasonix.d.ts +13 -13
  235. package/dist/defs/reasonix.js +2 -9
  236. package/dist/defs/shared.d.ts +10 -2
  237. package/dist/defs/shared.js +5 -1
  238. package/dist/defs/trae-cli/executable.d.ts +2 -0
  239. package/dist/defs/trae-cli/executable.js +2 -0
  240. package/dist/defs/trae-cli.d.ts +15 -15
  241. package/dist/defs/trae-cli.js +2 -9
  242. package/dist/defs/vibe/executable.d.ts +2 -0
  243. package/dist/defs/vibe/executable.js +2 -0
  244. package/dist/defs/vibe.d.ts +13 -13
  245. package/dist/defs/vibe.js +2 -9
  246. package/dist/detection.d.ts +4 -3
  247. package/dist/detection.js +22 -22
  248. package/dist/diagnostics.d.ts +4 -4
  249. package/dist/diagnostics.js +2 -2
  250. package/dist/env.js +2 -1
  251. package/dist/executable-helpers.d.ts +21 -0
  252. package/dist/executable-helpers.js +2 -0
  253. package/dist/executables.d.ts +2 -2
  254. package/dist/executables.js +68 -114
  255. package/dist/index.d.ts +6 -2
  256. package/dist/index.js +5 -1
  257. package/dist/invocation.d.ts +22 -6
  258. package/dist/invocation.js +19 -17
  259. package/dist/json-event-stream-shared.d.ts +81 -0
  260. package/dist/json-event-stream-shared.js +147 -0
  261. package/dist/json-event-stream.d.ts +2 -4
  262. package/dist/json-event-stream.js +15 -940
  263. package/dist/launch.d.ts +1 -9
  264. package/dist/launch.js +6 -155
  265. package/dist/log-file.d.ts +2 -8
  266. package/dist/log-file.js +1 -1
  267. package/dist/mcp.d.ts +2 -2
  268. package/dist/mcp.js +1 -1
  269. package/dist/mmd-routes.d.ts +7 -7
  270. package/dist/mmd-routes.js +19 -27
  271. package/dist/model-discovery-adapters.d.ts +47 -11
  272. package/dist/model-discovery-adapters.js +47 -41
  273. package/dist/model-discovery-config-types.d.ts +44 -0
  274. package/dist/model-discovery-config-types.js +20 -0
  275. package/dist/model-discovery-config.d.ts +19 -11
  276. package/dist/model-discovery-config.js +64 -87
  277. package/dist/model-discovery-native.d.ts +2 -1
  278. package/dist/model-discovery-native.js +3 -3
  279. package/dist/model-discovery-sdk.d.ts +6 -2
  280. package/dist/model-discovery-sdk.js +2 -2
  281. package/dist/model-discovery-types.d.ts +1 -138
  282. package/dist/model-discovery-yaml.d.ts +3 -1
  283. package/dist/model-discovery-yaml.js +1 -1
  284. package/dist/model-discovery.d.ts +15 -5
  285. package/dist/model-discovery.js +119 -105
  286. package/dist/model-loading-state.d.ts +1 -1
  287. package/dist/model-loading-state.js +1 -1
  288. package/dist/model-registry.d.ts +5 -5
  289. package/dist/model-registry.js +7 -6
  290. package/dist/models.d.ts +4 -3
  291. package/dist/models.js +2 -2
  292. package/dist/native-permissions.d.ts +47 -0
  293. package/dist/native-permissions.js +80 -0
  294. package/dist/native-runtime.d.ts +11 -8
  295. package/dist/native-runtime.js +8 -4
  296. package/dist/native-tool-policy.d.ts +1 -40
  297. package/dist/opencode-log.d.ts +3 -3
  298. package/dist/opencode-log.js +5 -3
  299. package/dist/paths.d.ts +1 -1
  300. package/dist/paths.js +1 -1
  301. package/dist/pi-models.d.ts +12 -2
  302. package/dist/pi-models.js +11 -1
  303. package/dist/prompt-augmenter.d.ts +1 -37
  304. package/dist/prompt-augmenter.js +0 -6
  305. package/dist/prompt-budget.d.ts +3 -3
  306. package/dist/prompt-budget.js +2 -2
  307. package/dist/prompt-file.d.ts +2 -6
  308. package/dist/prompt-file.js +1 -1
  309. package/dist/providers/aihubmix.d.ts +8 -8
  310. package/dist/providers/aihubmix.js +8 -8
  311. package/dist/providers/anthropic-messages.d.ts +22 -23
  312. package/dist/providers/anthropic-messages.js +26 -53
  313. package/dist/providers/azure-chat.d.ts +7 -6
  314. package/dist/providers/azure-chat.js +9 -6
  315. package/dist/providers/connection-guard.d.ts +3 -9
  316. package/dist/providers/connection-guard.js +6 -14
  317. package/dist/providers/connection-test.d.ts +1 -2
  318. package/dist/providers/connection-test.js +51 -51
  319. package/dist/providers/credentials.d.ts +59 -0
  320. package/dist/providers/credentials.js +80 -0
  321. package/dist/providers/elevenlabs.d.ts +2 -6
  322. package/dist/providers/elevenlabs.js +2 -31
  323. package/dist/providers/google-messages.d.ts +11 -10
  324. package/dist/providers/google-messages.js +16 -35
  325. package/dist/providers/google-schema.d.ts +1 -1
  326. package/dist/providers/google-schema.js +1 -1
  327. package/dist/providers/google.d.ts +6 -6
  328. package/dist/providers/google.js +6 -6
  329. package/dist/providers/index.d.ts +5 -2
  330. package/dist/providers/index.js +5 -2
  331. package/dist/providers/model-catalog.d.ts +4 -9
  332. package/dist/providers/model-catalog.js +3 -11
  333. package/dist/providers/oauth-callback-server.js +93 -87
  334. package/dist/providers/oauth-provider.d.ts +1 -1
  335. package/dist/providers/oauth-provider.js +1 -1
  336. package/dist/providers/oauth-tokens.d.ts +5 -5
  337. package/dist/providers/oauth-tokens.js +8 -9
  338. package/dist/providers/ollama-chat.d.ts +13 -12
  339. package/dist/providers/ollama-chat.js +15 -24
  340. package/dist/providers/openai-chat-request.d.ts +34 -0
  341. package/dist/providers/openai-chat-request.js +152 -0
  342. package/dist/providers/openai-chat-stream.d.ts +48 -0
  343. package/dist/providers/openai-chat-stream.js +89 -0
  344. package/dist/providers/openai-chat-tool-results.d.ts +81 -0
  345. package/dist/providers/openai-chat-tool-results.js +124 -0
  346. package/dist/providers/openai-chat-types.d.ts +180 -0
  347. package/dist/providers/openai-chat-types.js +3 -0
  348. package/dist/providers/openai-chat.d.ts +5 -405
  349. package/dist/providers/openai-chat.js +9 -388
  350. package/dist/providers/pkce.d.ts +1 -1
  351. package/dist/providers/pkce.js +1 -1
  352. package/dist/providers/provider-url.d.ts +6 -0
  353. package/dist/providers/provider-url.js +9 -0
  354. package/dist/providers/response-text.d.ts +4 -0
  355. package/dist/providers/response-text.js +16 -0
  356. package/dist/providers/sse-decode.d.ts +4 -0
  357. package/dist/providers/sse-decode.js +11 -0
  358. package/dist/providers/token-params.d.ts +5 -5
  359. package/dist/providers/token-params.js +5 -5
  360. package/dist/providers/tool-loop-verdict.d.ts +1 -1
  361. package/dist/providers/tool-loop-verdict.js +1 -1
  362. package/dist/providers/tool-turn-types.d.ts +2 -1
  363. package/dist/providers/tool-turn.js +30 -50
  364. package/dist/providers/turn-end-guard.d.ts +4 -1
  365. package/dist/providers/turn-end-guard.js +1 -1
  366. package/dist/qoder-stream.d.ts +1 -1
  367. package/dist/qoder-stream.js +1 -1
  368. package/dist/registry.d.ts +5 -5
  369. package/dist/registry.js +4 -4
  370. package/dist/role-marker-guard.d.ts +13 -1
  371. package/dist/role-marker-guard.js +15 -1
  372. package/dist/runtime-def-binding.d.ts +15 -0
  373. package/dist/runtime-def-binding.js +19 -0
  374. package/dist/runtime-port-bindings.d.ts +181 -0
  375. package/dist/runtime-port-bindings.js +95 -0
  376. package/dist/runtime-state.d.ts +2 -11
  377. package/dist/runtime-state.js +0 -13
  378. package/dist/types.d.ts +1 -454
  379. package/package.json +27 -15
  380. package/dist/ai-trace/capture.d.ts +0 -17
  381. package/dist/ai-trace/capture.js +0 -43
  382. package/dist/ai-trace/classify.d.ts +0 -12
  383. package/dist/ai-trace/classify.js +0 -16
  384. package/dist/ai-trace/index.d.ts +0 -13
  385. package/dist/ai-trace/index.js +0 -6
  386. package/dist/ai-trace/recorder.d.ts +0 -64
  387. package/dist/ai-trace/recorder.js +0 -258
  388. package/dist/ai-trace/sinks.d.ts +0 -51
  389. package/dist/ai-trace/sinks.js +0 -153
  390. package/dist/ai-trace/types.d.ts +0 -123
  391. package/dist/ai-trace/types.js +0 -17
  392. package/dist/ai-trace/usage.d.ts +0 -13
  393. package/dist/ai-trace/usage.js +0 -45
  394. package/dist/copilot-stream.d.ts +0 -65
  395. package/dist/copilot-stream.js +0 -131
  396. package/dist/defs/antigravity.d.ts +0 -94
  397. package/dist/defs/antigravity.js +0 -320
  398. package/dist/defs/copilot.d.ts +0 -34
  399. package/dist/defs/copilot.js +0 -96
  400. package/dist/defs/gemini.d.ts +0 -24
  401. package/dist/defs/gemini.js +0 -81
  402. package/dist/model-contracts.d.ts +0 -29
  403. package/dist/model-contracts.js +0 -2
  404. package/dist/providers/types.d.ts +0 -36
  405. package/dist/providers/types.js +0 -13
@@ -36,807 +36,8 @@
36
36
  * a larger, riskier change than this pass makes. They stay as closures,
37
37
  * exercised only through `feed`/`flush` in the test suite.
38
38
  */
39
- import { createBoundedLineStream } from './core/bounded-line-stream.js';
40
- import { readDelegatedResult } from '@jini-ai/protocol';
41
- import { createRoleMarkerGuard } from './role-marker-guard.js';
42
- import { createClaudeSegmentUsage } from './claude-segment-usage.js';
43
- /** The first argument that is a string (possibly empty), or `undefined` when none is. */
44
- function firstString(...values) {
45
- return values.find((value) => typeof value === 'string');
46
- }
47
- function isRecord(value) {
48
- return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
49
- }
50
- const WRITE_TOOL_NAMES = new Set(['Write', 'Edit', 'write_file', 'replace']);
51
- export function toolInputPath(input) {
52
- if (typeof input.file_path === 'string')
53
- return input.file_path;
54
- if (typeof input.path === 'string')
55
- return input.path;
56
- return '';
57
- }
58
- // Runtime-task status aliases the Claude Code wire format has used across
59
- // versions, normalized to the four statuses the UI understands.
60
- const TASK_STATUS_ALIASES = {
61
- completed: 'completed',
62
- in_progress: 'in_progress',
63
- stopped: 'stopped',
64
- complete: 'completed',
65
- done: 'completed',
66
- doing: 'in_progress',
67
- active: 'in_progress',
68
- failed: 'stopped',
69
- canceled: 'stopped',
70
- cancelled: 'stopped',
71
- };
72
- export function normalizeTaskStatus(value) {
73
- if (typeof value !== 'string')
74
- return 'pending';
75
- return TASK_STATUS_ALIASES[value] ?? 'pending';
76
- }
77
- function nextGeneratedRuntimeTaskId(counter) {
78
- // Coverage-driven refactor (2026-07-18, no behavior change): the
79
- // original OD source guarded the returned id with
80
- // `while (runtimeTasks.has(String(nextRuntimeTaskId))) nextRuntimeTaskId += 1;`.
81
- // Tracing every path that can insert a numeric id into `runtimeTasks`
82
- // shows the guard can never trigger: the only two insertion paths are
83
- // (a) this function itself, which always hands out the current
84
- // `nextRuntimeTaskId` and then increments it, so that exact value is
85
- // never in the map yet; and (b) `runtimeTaskIdFromCreate`'s
86
- // explicit-id branch, which bumps `nextRuntimeTaskId` to
87
- // `numericId + 1` (strictly past itself) BEFORE this function could
88
- // ever be asked to reuse that id. Since `nextRuntimeTaskId` only ever
89
- // increases, it can never equal an id already present in the map at
90
- // this point. Removed per the coverage skill's Phase 6.5 "dead
91
- // branch" classification rather than fake a test for an unreachable
92
- // loop; see archived provenance ledger.
93
- const id = String(counter.next);
94
- counter.next += 1;
95
- return id;
96
- }
97
- export function runtimeTaskIdFromCreate(input, counter) {
98
- if (typeof input.taskId === 'string' && input.taskId) {
99
- const numericId = Number(input.taskId);
100
- if (Number.isSafeInteger(numericId) && numericId >= counter.next) {
101
- counter.next = numericId + 1;
102
- }
103
- return input.taskId;
104
- }
105
- return nextGeneratedRuntimeTaskId(counter);
106
- }
107
- export function applyTaskCreate(input, tasks, counter) {
108
- const content = firstString(input.subject, input.description) ?? '';
109
- if (!content)
110
- return false;
111
- const id = runtimeTaskIdFromCreate(input, counter);
112
- const activeForm = typeof input.activeForm === 'string' ? input.activeForm : undefined;
113
- tasks.set(id, {
114
- id,
115
- content,
116
- status: normalizeTaskStatus(input.status),
117
- ...(activeForm ? { activeForm } : {}),
118
- });
119
- return true;
120
- }
121
- export function applyTaskUpdate(input, tasks) {
122
- if (typeof input.taskId !== 'string')
123
- return false;
124
- const existing = tasks.get(input.taskId);
125
- if (!existing)
126
- return false;
127
- const content = firstString(input.subject, input.description) ?? existing.content;
128
- const activeForm = typeof input.activeForm === 'string' ? input.activeForm : existing.activeForm;
129
- tasks.set(input.taskId, {
130
- ...existing,
131
- content,
132
- status: normalizeTaskStatus(input.status),
133
- ...(activeForm ? { activeForm } : {}),
134
- });
135
- return true;
136
- }
137
- export function emitCanonicalTaskSnapshot(toolUseId, name, input, registry, onEvent) {
138
- if (typeof toolUseId !== 'string' || typeof name !== 'string' || !isRecord(input))
139
- return false;
140
- if (registry.seenToolUseIds.has(toolUseId))
141
- return true;
142
- const applied = name === 'TaskCreate'
143
- ? applyTaskCreate(input, registry.tasks, registry.counter)
144
- : name === 'TaskUpdate' && applyTaskUpdate(input, registry.tasks);
145
- if (!applied)
146
- return false;
147
- // Coverage-driven refactor (2026-07-18, no behavior change): the
148
- // original OD source guarded this emission with
149
- // `if (!changed || runtimeTasks.size === 0) return false;`. Tracing
150
- // every path into this point shows both conditions are unreachable —
151
- // the `TaskCreate` and `TaskUpdate` branches above only fall through
152
- // to here after an unconditional `runtimeTasks.set(...)` (so `size`
153
- // can never be 0), and every early-return path above returns before
154
- // reaching here (so the "changed" flag those returns guarded was
155
- // always true here). Removed the dead double-guard per the coverage
156
- // skill's Phase 6.5 "dead branch" classification rather than fake a
157
- // test for an unreachable condition; see archived provenance ledger.
158
- registry.seenToolUseIds.add(toolUseId);
159
- onEvent({
160
- type: 'tool_use',
161
- id: `${toolUseId}:todo-task`,
162
- name: 'TodoWrite',
163
- input: {
164
- todos: Array.from(registry.tasks.values()).map(({ content, status, activeForm }) => ({
165
- content,
166
- status,
167
- ...(activeForm ? { activeForm } : {}),
168
- })),
169
- },
170
- });
171
- return true;
172
- }
173
- export function isFileWriteToolUse(name, input) {
174
- if (typeof name !== 'string' || !isRecord(input))
175
- return false;
176
- if (!WRITE_TOOL_NAMES.has(name))
177
- return false;
178
- if (/\.(html|htm|css|js|jsx|ts|tsx|md)$/iu.test(toolInputPath(input)))
179
- return true;
180
- return typeof input.content === 'string' || typeof input.new_string === 'string';
181
- }
182
- // Coverage-driven refactor (2026-07-18, no behavior change): both
183
- // `fileWriteContent` and `isHtmlWriteToolInput` originally opened with
184
- // their own `if (!isRecord(input)) return ...;` guard. Each function
185
- // has exactly one call site (`emitToolUse`, for both), and both call
186
- // sites already sit inside an `if (isFileWriteToolUse(name, input))`
187
- // block, which itself already asserted `isRecord(input)` before
188
- // returning true. So `input` is always a record by the time either
189
- // function runs — the guards duplicated a check the shared caller
190
- // already made. Removed the runtime early-return per the coverage
191
- // skill's Phase 6.5 "dead branch" classification rather than fake a
192
- // test with a non-record `input` neither function can ever actually
193
- // receive (see archived provenance ledger), replaced by a one-line type assertion
194
- // (classification 4: TS-required, no real runtime path) so the
195
- // parameter can stay `unknown` without disturbing the call sites.
196
- export function fileWriteContent(input) {
197
- const record = input;
198
- if (typeof record.content === 'string')
199
- return record.content;
200
- if (typeof record.new_string === 'string')
201
- return record.new_string;
202
- return null;
203
- }
204
- export function isHtmlWriteToolInput(input) {
205
- const record = input;
206
- const rawPath = record.file_path ?? record.filePath;
207
- if (typeof rawPath === 'string' && /\.(?:html?|xhtml)$/i.test(rawPath))
208
- return true;
209
- const content = fileWriteContent(input);
210
- return typeof content === 'string' && /<!doctype\s+html\b|<html\b/i.test(content);
211
- }
212
- export function artifactOpenCandidateLength(text, openTag) {
213
- const max = Math.min(openTag.length - 1, text.length);
214
- for (let len = max; len > 0; len -= 1) {
215
- if (openTag.startsWith(text.slice(-len)))
216
- return len;
217
- }
218
- return 0;
219
- }
220
- function isHtmlArtifact(candidate) {
221
- const openTag = candidate.slice(0, Math.max(0, candidate.indexOf('>') + 1));
222
- return /\btype\s*=\s*["']text\/html["']/i.test(openTag);
223
- }
224
- function normalizeArtifactEchoContent(value) {
225
- const normalized = value
226
- .replace(/^\uFEFF/, '')
227
- .replace(/\r\n?/g, '\n');
228
- return trimEchoPadding(normalized);
229
- }
230
- /** Length of the padding token (whitespace, or a literal `\r`/`\n` escape) starting at `index`; 0 if none. */
231
- function echoPaddingAt(text, index) {
232
- if (/\s/.test(text.charAt(index)))
233
- return 1;
234
- return text.startsWith('\\r', index) || text.startsWith('\\n', index) ? 2 : 0;
235
- }
236
- /** Length of the padding token ending just before `end`; 0 if none. */
237
- function echoPaddingBefore(text, end) {
238
- if (end > 0 && /\s/.test(text.charAt(end - 1)))
239
- return 1;
240
- return end > 1 && echoPaddingAt(text, end - 2) === 2 ? 2 : 0;
241
- }
242
- /** Strips leading and trailing runs of whitespace and literal `\r`/`\n` escapes. Same result as
243
- * `text.replace(/^(?:\s|\\r|\\n)+|(?:\s|\\r|\\n)+$/g, '')`, without its quadratic backtracking. */
244
- function trimEchoPadding(text) {
245
- let start = 0;
246
- for (let step = echoPaddingAt(text, start); step > 0; step = echoPaddingAt(text, start))
247
- start += step;
248
- let end = text.length;
249
- for (let step = echoPaddingBefore(text, end); step > 0 && end - step >= start; step = echoPaddingBefore(text, end))
250
- end -= step;
251
- return text.slice(start, end);
252
- }
253
- export function isRedundantWrittenArtifact(candidate, ctx) {
254
- const gt = candidate.indexOf('>');
255
- const close = candidate.lastIndexOf('</artifact>');
256
- if (gt === -1 || close === -1 || close <= gt)
257
- return false;
258
- if (ctx.suppressHtmlArtifactsAfterFileWrite && isHtmlArtifact(candidate) && ctx.wroteHtmlFileThisTurn) {
259
- return true;
260
- }
261
- const body = normalizeArtifactEchoContent(candidate.slice(gt + 1, close));
262
- return ctx.recentWriteContents.some((content) => content === body);
263
- }
264
- export function assistantText(content) {
265
- const parts = [];
266
- for (const block of content) {
267
- if (isRecord(block) && block.type === 'text' && typeof block.text === 'string') {
268
- parts.push(block.text);
269
- }
270
- }
271
- return parts.join('\n').trim();
272
- }
273
- export function isUnstreamedTextBlock(block, alreadyStreamed) {
274
- return !alreadyStreamed && block.type === 'text' && typeof block.text === 'string' && block.text.length > 0;
275
- }
276
- export function isUnstreamedThinkingBlock(block, alreadyStreamed) {
277
- return (!alreadyStreamed && block.type === 'thinking' && typeof block.thinking === 'string' && block.thinking.length > 0);
278
- }
279
- /**
280
- * The init frame's `mcp_servers`, reduced to `{name, status}`, or `undefined` when the frame has no
281
- * such list. Kept on the event so a host can tell "its bridge did not connect" from "no bridge was
282
- * configured": Claude Code times a dead MCP server out, reports it `failed` here, and carries on
283
- * without its tools (the 2026-10-01 desktop incident). Entries without a string name and status are
284
- * dropped rather than guessed at.
285
- */
286
- export function initMcpServers(obj) {
287
- if (!Array.isArray(obj.mcp_servers))
288
- return undefined;
289
- return obj.mcp_servers.flatMap((server) => isRecord(server) && typeof server.name === 'string' && typeof server.status === 'string'
290
- ? [{ name: server.name, status: server.status }]
291
- : []);
292
- }
293
- export function handleSystemMessage(obj, onEvent) {
294
- if (obj.subtype === 'init') {
295
- const mcpServers = initMcpServers(obj);
296
- onEvent({
297
- type: 'status',
298
- label: 'initializing',
299
- model: obj.model ?? null,
300
- sessionId: obj.session_id ?? null,
301
- ...(mcpServers !== undefined ? { mcpServers } : {}),
302
- });
303
- return;
304
- }
305
- if (obj.subtype === 'status') {
306
- onEvent({ type: 'status', label: typeof obj.status === 'string' ? obj.status : 'working' });
307
- }
308
- }
309
- export function stringifyToolResult(content) {
310
- if (typeof content === 'string')
311
- return content;
312
- if (Array.isArray(content)) {
313
- return content
314
- .map((c) => (isRecord(c) && c.type === 'text' ? String(c.text) : JSON.stringify(c)))
315
- .join('\n');
316
- }
317
- return JSON.stringify(content);
318
- }
319
- // `user` messages in a stream-json transcript are usually tool_result
320
- // wrappers from prior turns.
321
- export function handleUserMessage(obj, onEvent) {
322
- if (!isRecord(obj.message) || !Array.isArray(obj.message.content))
323
- return;
324
- for (const block of obj.message.content) {
325
- if (!isRecord(block))
326
- continue;
327
- if (block.type === 'tool_result') {
328
- const delegated = readDelegatedResult({ content: block.content });
329
- onEvent({
330
- type: 'tool_result',
331
- toolUseId: block.tool_use_id,
332
- // Keep original pixels until the daemon verifies the run, outcome and digest.
333
- content: stringifyToolResult(block.content),
334
- ...(delegated ? { delegatedToolUseId: delegated.marker.toolUseId, delegatedResultContent: delegated.content } : {}),
335
- isError: Boolean(block.is_error),
336
- });
337
- }
338
- }
339
- }
340
- export function applyInputJsonDelta(state, partialJson, onEvent) {
341
- if (!state || state.type !== 'tool_use')
342
- return;
343
- state.input += partialJson;
344
- if (typeof state.id === 'string' && typeof state.name === 'string') {
345
- onEvent({
346
- type: 'tool_input_delta',
347
- id: state.id,
348
- name: state.name,
349
- delta: partialJson,
350
- });
351
- }
352
- }
353
- export function emitAssistantErrorIfPresent(obj, content, onEvent) {
354
- if (typeof obj.error !== 'string' || !obj.error.trim())
355
- return;
356
- onEvent({
357
- type: 'error',
358
- message: assistantText(content) || obj.error,
359
- code: obj.error,
360
- });
361
- }
39
+ import { createStreamHandlerImpl } from './claude-stream-handler.js';
362
40
  export function createClaudeStreamHandler({ onEvent }, options = {}) {
363
- const lines = createBoundedLineStream({
364
- onLine: line => { const trimmed = line.trim(); if (trimmed)
365
- feedLine(trimmed); },
366
- onOverflow: error => onEvent({ type: 'error', message: error.message, code: 'STREAM_LINE_TOO_LARGE' }),
367
- });
368
- const segmentUsage = createClaudeSegmentUsage({}, {
369
- ...(options.nowMs === undefined ? {} : { nowMs: options.nowMs }),
370
- ...(options.costBasis === undefined ? {} : { costBasis: options.costBasis }),
371
- });
372
- // Per-content-block scratch, keyed by `${messageId}:${blockIndex}`.
373
- const blocks = new Map();
374
- // Tool uses already emitted from streamed `input_json_delta` data OR full wrappers.
375
- // Claude Code still repeats them in the final assistant wrapper, often with
376
- // empty `{}` inputs, so we suppress that duplicate emission.
377
- const streamedToolUseIds = new Set();
378
- // Most recent assistant message id so content_block_* events without an id
379
- // can be attributed correctly.
380
- let currentMessageId = null;
381
- // Message ids that already streamed assistant text/thinking via
382
- // `stream_event` deltas.
383
- // When `--include-partial-messages` is OFF (older Claude Code, e.g. 1.0.84
384
- // pre-flag), no deltas arrive — only the final `assistant` wrapper carries
385
- // content. The fallback below emits that content once, but we must skip it for
386
- // newer builds that already streamed deltas, otherwise the message would
387
- // duplicate.
388
- const textStreamed = new Set();
389
- const thinkingStreamed = new Set();
390
- let currentMessageStreamedText = false;
391
- let currentMessageStreamedThinking = false;
392
- // Newer Claude Code builds put the terminal stop reason in the partial
393
- // stream's `message_delta`, while the accompanying top-level `assistant`
394
- // wrapper carries `stop_reason: null`. Older builds put it on the wrapper.
395
- // Remember the message id that already emitted `turn_end` so accepting
396
- // both wire shapes cannot double-trigger stdin continuation/closure.
397
- let turnEndSignature = null;
398
- // Stands in for `currentMessageId` in the dedup key when a frame carried no
399
- // message id at all. Without it the key is null and the guard below cannot
400
- // fire, so an id-less assistant wrapper plus the same-reason `result` frame
401
- // that follows it emit two identical `turn_end` events. It is bumped only at
402
- // `message_start` and at an id-less `assistant` wrapper — the two frames that
403
- // actually begin a new assistant message — and deliberately NOT at
404
- // `message_delta`/`result`, which report on the message already in flight.
405
- // Bumping it on a real message boundary is what keeps this from over-deduping:
406
- // two consecutive id-less `tool_use` turns still emit twice, and a suppressed
407
- // `tool_use` turn_end would strand the daemon's stdin-close handler.
408
- let anonymousMessageEpoch = 0;
409
- // Per-message role-marker guards for cross-chunk detection (#3247).
410
- const roleGuards = new Map();
411
- const taskRegistry = {
412
- tasks: new Map(),
413
- counter: { next: 1 },
414
- seenToolUseIds: new Set(),
415
- };
416
- let suppressNextArtifactText = false;
417
- let suppressDuplicateArtifactText = false;
418
- let artifactOpenCandidate = '';
419
- let pendingArtifactText = '';
420
- let duplicateArtifactCandidate = '';
421
- const recentWriteContents = [];
422
- let wroteHtmlFileThisTurn = false;
423
- function emitTurnEnd(stopReason) {
424
- // `\u0001` prefixes the synthetic key so it can never collide with a real
425
- // message id, which is why this is safe to compare in the same slot.
426
- const messageKey = currentMessageId ?? `\u0001anon${anonymousMessageEpoch}`;
427
- const signature = `${messageKey}\u0000${stopReason}`;
428
- if (turnEndSignature === signature)
429
- return;
430
- onEvent({ type: 'turn_end', stopReason });
431
- turnEndSignature = signature;
432
- if (stopReason !== 'tool_use') {
433
- recentWriteContents.length = 0;
434
- wroteHtmlFileThisTurn = false;
435
- }
436
- }
437
- function emitToolUse(id, name, input) {
438
- if (typeof id === 'string') {
439
- if (streamedToolUseIds.has(id))
440
- return;
441
- streamedToolUseIds.add(id);
442
- }
443
- if (emitCanonicalTaskSnapshot(id, name, input, taskRegistry, onEvent))
444
- return;
445
- if (isFileWriteToolUse(name, input)) {
446
- suppressNextArtifactText = true;
447
- const content = fileWriteContent(input);
448
- if (content) {
449
- wroteHtmlFileThisTurn = wroteHtmlFileThisTurn || isHtmlWriteToolInput(input);
450
- recentWriteContents.push(normalizeArtifactEchoContent(content));
451
- if (recentWriteContents.length > 5)
452
- recentWriteContents.shift();
453
- }
454
- }
455
- onEvent({
456
- type: 'tool_use',
457
- id,
458
- name,
459
- input,
460
- });
461
- }
462
- function blockKey(index) {
463
- return `${currentMessageId ?? 'anon'}:${index}`;
464
- }
465
- // Per-message role-marker guard (#3247). Covers text_delta ONLY.
466
- //
467
- // Why not thinking_delta: extended thinking is rendered to a
468
- // separate `kind: 'thinking'` payload and is never folded into
469
- // `m.content` by `buildDaemonTranscript` (apps/web/src/providers/daemon.ts),
470
- // so it cannot be re-serialized as a turn boundary on the next
471
- // round-trip — it is not a #3247 re-injection vector. Models
472
- // routinely emit literal `## user` / `## assistant` lines in
473
- // chain-of-thought when reasoning about conversation structure,
474
- // and with kill-on-detection wired in server.ts a guard on the
475
- // thinking channel would abort otherwise-legitimate runs without
476
- // any compensating security benefit. See PR #3303 review
477
- // r3324xxxxxx. Thinking is passed through unguarded; only the
478
- // user-visible text channel is policed.
479
- function getOrCreateRoleGuard(msgId) {
480
- let guard = roleGuards.get(msgId);
481
- if (!guard) {
482
- guard = createRoleMarkerGuard({ messageId: msgId });
483
- roleGuards.set(msgId, guard);
484
- }
485
- return guard;
486
- }
487
- function emitSafeText(msgId, text, eventType = 'text_delta') {
488
- if (eventType === 'text_delta') {
489
- text = stripDuplicateArtifactText(text);
490
- if (!text)
491
- return;
492
- }
493
- if (eventType !== 'text_delta' || !msgId) {
494
- onEvent({ type: eventType, delta: text });
495
- return;
496
- }
497
- const guard = getOrCreateRoleGuard(msgId);
498
- if (guard.contaminated)
499
- return;
500
- const safe = guard.feedText({ text: text });
501
- if (safe.length > 0) {
502
- onEvent({ type: eventType, delta: safe });
503
- }
504
- if (guard.contaminated) {
505
- const warn = guard.warningEvent();
506
- if (warn)
507
- onEvent(warn);
508
- }
509
- }
510
- // Resolves an in-progress `<artifact>...</artifact>` echo once its close
511
- // tag has arrived: drops it if it duplicates a recent file write, then
512
- // resumes stripping on whatever text followed the close tag.
513
- function resolveDuplicateArtifactCandidate(current) {
514
- duplicateArtifactCandidate += current;
515
- const closeIndex = duplicateArtifactCandidate.indexOf('</artifact>');
516
- if (closeIndex === -1)
517
- return '';
518
- const closeEnd = closeIndex + '</artifact>'.length;
519
- const candidate = duplicateArtifactCandidate.slice(0, closeEnd);
520
- const rest = duplicateArtifactCandidate.slice(closeEnd);
521
- duplicateArtifactCandidate = '';
522
- suppressDuplicateArtifactText = false;
523
- suppressNextArtifactText = false;
524
- const duplicate = isRedundantWrittenArtifact(candidate, {
525
- suppressHtmlArtifactsAfterFileWrite: options.suppressHtmlArtifactsAfterFileWrite === true,
526
- wroteHtmlFileThisTurn,
527
- recentWriteContents,
528
- });
529
- if (options.suppressHtmlArtifactsAfterFileWrite !== true) {
530
- recentWriteContents.length = 0;
531
- }
532
- return `${duplicate ? '' : candidate}${stripDuplicateArtifactText(rest)}`;
533
- }
534
- // No open `<artifact` tag has been seen yet: either buffer a partial tag
535
- // prefix at the end of `current` so it can match across chunk boundaries,
536
- // or pass the text through untouched.
537
- function bufferPartialArtifactOpenTag(current, openTag) {
538
- const candidateLength = artifactOpenCandidateLength(current, openTag);
539
- if ((suppressNextArtifactText || recentWriteContents.length > 0) && candidateLength > 0) {
540
- artifactOpenCandidate = current.slice(-candidateLength);
541
- return current.slice(0, -candidateLength);
542
- }
543
- return current;
544
- }
545
- // An `<artifact` open tag just arrived: start accumulating it as a
546
- // duplicate-write candidate and flush whatever text preceded it.
547
- function startDuplicateArtifactCandidate(current, openIndex) {
548
- suppressDuplicateArtifactText = true;
549
- suppressNextArtifactText = false;
550
- duplicateArtifactCandidate = current.slice(openIndex);
551
- const prefix = `${pendingArtifactText}${current.slice(0, openIndex)}`;
552
- pendingArtifactText = '';
553
- return `${prefix}${stripDuplicateArtifactText('')}`;
554
- }
555
- function stripDuplicateArtifactText(text) {
556
- if (!suppressNextArtifactText &&
557
- !suppressDuplicateArtifactText &&
558
- artifactOpenCandidate.length === 0 &&
559
- recentWriteContents.length === 0) {
560
- return text;
561
- }
562
- const openTag = '<artifact';
563
- const current = `${artifactOpenCandidate}${text}`;
564
- artifactOpenCandidate = '';
565
- if (suppressDuplicateArtifactText) {
566
- return resolveDuplicateArtifactCandidate(current);
567
- }
568
- const openIndex = current.indexOf(openTag);
569
- if (openIndex === -1) {
570
- return bufferPartialArtifactOpenTag(current, openTag);
571
- }
572
- return startDuplicateArtifactCandidate(current, openIndex);
573
- }
574
- function feed({ chunk }) {
575
- lines.feed({ chunk: chunk });
576
- }
577
- /** One complete, non-blank line: a JSON object is handled, anything else passes through raw. */
578
- function feedLine(line) {
579
- let obj;
580
- try {
581
- obj = JSON.parse(line);
582
- }
583
- catch {
584
- onEvent({ type: 'raw', line });
585
- return;
586
- }
587
- handleObject(obj);
588
- }
589
- function flush() {
590
- lines.flush();
591
- flushPendingArtifactText();
592
- // A hard cancel has no result frame. Flush only counters actually observed, once.
593
- if (segmentUsage.hasObserved())
594
- onEvent({ type: 'usage', ...segmentUsage.finish({ result: {}, interrupted: true }), stopReason: null });
595
- }
596
- function handleToolUseBlock(block) {
597
- if (typeof block.id === 'string' && streamedToolUseIds.has(block.id))
598
- return;
599
- emitToolUse(block.id, block.name, block.input ?? null);
600
- }
601
- function handleAssistantContentBlock(block, ctx) {
602
- if (!isRecord(block))
603
- return;
604
- if (block.type === 'tool_use') {
605
- handleToolUseBlock(block);
606
- return;
607
- }
608
- if (isUnstreamedTextBlock(block, ctx.textAlreadyStreamed)) {
609
- emitSafeText(ctx.textMsgId, block.text);
610
- return;
611
- }
612
- if (isUnstreamedThinkingBlock(block, ctx.thinkingAlreadyStreamed)) {
613
- emitSafeText(ctx.thinkingMsgId, block.thinking, 'thinking_delta');
614
- }
615
- }
616
- // Resolves the message id assistant text/thinking blocks should be
617
- // attributed to (an explicit id on the wrapper, or the currently-tracked
618
- // streaming id), and whether that channel already streamed via deltas.
619
- // Also owns the message-id/epoch bookkeeping side effects that must
620
- // happen exactly once per assistant wrapper.
621
- function resolveAssistantMessageIds(message) {
622
- const explicitMsgId = typeof message.id === 'string' ? message.id : null;
623
- const textMsgId = explicitMsgId ?? (currentMessageStreamedText ? currentMessageId : null);
624
- const thinkingMsgId = explicitMsgId ?? (currentMessageStreamedThinking ? currentMessageId : null);
625
- if (explicitMsgId)
626
- currentMessageId = explicitMsgId;
627
- // An id-less assistant wrapper is itself a new message boundary: no
628
- // `message_start` announced it, so this is the only place the epoch can
629
- // advance before its own `turn_end` is emitted below. See
630
- // `anonymousMessageEpoch`'s declaration for why message_delta/result must
631
- // NOT advance it.
632
- if (currentMessageId === null)
633
- anonymousMessageEpoch += 1;
634
- return {
635
- textMsgId,
636
- thinkingMsgId,
637
- textAlreadyStreamed: textMsgId ? textStreamed.has(textMsgId) : false,
638
- thinkingAlreadyStreamed: thinkingMsgId ? thinkingStreamed.has(thinkingMsgId) : false,
639
- };
640
- }
641
- // `assistant` messages are the "block finished" signal for the current
642
- // content block. For tool_use blocks whose input finished assembling,
643
- // emit tool_use now with the final parsed input. For text blocks, emit
644
- // the text as a single delta — but only if no streaming deltas already
645
- // covered it (older Claude Code without --include-partial-messages
646
- // delivers text only here; newer builds stream it and would duplicate).
647
- function handleAssistantMessage(obj) {
648
- const message = obj.message;
649
- if (!isRecord(message) || !Array.isArray(message.content))
650
- return;
651
- if (typeof message.model === 'string')
652
- onEvent({ type: 'status', label: 'model', model: message.model });
653
- const { textMsgId, thinkingMsgId, textAlreadyStreamed, thinkingAlreadyStreamed } = resolveAssistantMessageIds(message);
654
- segmentUsage.observe({ messageId: usageMessageKey(), usage: message.usage });
655
- // Per-turn `stop_reason` is emitted as `turn_end` AFTER the content
656
- // blocks have been processed (see below). When `--include-partial-
657
- // messages` is unsupported, tool_use events surface only from the
658
- // assistant wrapper here — emitting `turn_end` before that loop would
659
- // let the daemon's stdin-close handler act on the turn before its
660
- // tool_use blocks were seen, closing stdin mid-tool. Read the
661
- // stop_reason now, emit after.
662
- const stopReason = typeof message.stop_reason === 'string' ? message.stop_reason : null;
663
- for (const block of message.content) {
664
- handleAssistantContentBlock(block, { textMsgId, thinkingMsgId, textAlreadyStreamed, thinkingAlreadyStreamed });
665
- }
666
- // Surface the turn_end signal now that every tool_use in this
667
- // assistant message has been emitted, so the daemon's stdin-close
668
- // handler sees the final `stop_reason` before deciding whether to
669
- // close stream-json input stdin.
670
- if (stopReason) {
671
- emitTurnEnd(stopReason);
672
- }
673
- emitAssistantErrorIfPresent(obj, message.content, onEvent);
674
- currentMessageStreamedText = false;
675
- currentMessageStreamedThinking = false;
676
- }
677
- function handleResultMessage(obj) {
678
- // The first non-empty string of `stop_reason`, then `terminal_reason`; otherwise null.
679
- const stopReason = [obj.stop_reason, obj.terminal_reason].find((reason) => typeof reason === 'string' && reason !== '') ?? null;
680
- // Claude Code 2.1.201 does not always emit a terminal
681
- // stream_event/message_delta. In that wire shape, the top-level result
682
- // is the only frame carrying `end_turn`. Surface it as a turn boundary
683
- // so AgentExecutor can close stream-json stdin and reap the process.
684
- if (stopReason) {
685
- emitTurnEnd(stopReason);
686
- }
687
- onEvent({
688
- type: 'usage',
689
- ...segmentUsage.finish({ result: obj, interrupted: stopReason?.startsWith('aborted') === true }),
690
- stopReason,
691
- });
692
- }
693
- function handleObject(obj) {
694
- if (!isRecord(obj))
695
- return;
696
- segmentUsage.setSession({ id: obj.session_id });
697
- switch (obj.type) {
698
- case 'system':
699
- handleSystemMessage(obj, onEvent);
700
- return;
701
- case 'stream_event':
702
- if (isRecord(obj.event))
703
- handleStreamEvent(obj.event);
704
- return;
705
- case 'assistant':
706
- handleAssistantMessage(obj);
707
- return;
708
- case 'user':
709
- handleUserMessage(obj, onEvent);
710
- return;
711
- case 'result':
712
- handleResultMessage(obj);
713
- return;
714
- }
715
- }
716
- function handleMessageStart(ev) {
717
- if (isRecord(ev.message) && typeof ev.message.model === 'string')
718
- onEvent({ type: 'status', label: 'model', model: ev.message.model });
719
- flushPendingArtifactText();
720
- // Clean up per-message role-marker guard from the previous message.
721
- if (currentMessageId)
722
- roleGuards.delete(currentMessageId);
723
- currentMessageId = isRecord(ev.message) && typeof ev.message.id === 'string' ? ev.message.id : null;
724
- // New message boundary — see `anonymousMessageEpoch`'s declaration.
725
- if (currentMessageId === null)
726
- anonymousMessageEpoch += 1;
727
- segmentUsage.observe({ messageId: usageMessageKey(), usage: isRecord(ev.message) ? ev.message.usage : undefined });
728
- currentMessageStreamedText = false;
729
- currentMessageStreamedThinking = false;
730
- if (typeof ev.ttft_ms === 'number') {
731
- onEvent({ type: 'status', label: 'streaming', ttftMs: ev.ttft_ms });
732
- }
733
- }
734
- function handleContentBlockStart(index, block) {
735
- const key = blockKey(index);
736
- blocks.set(key, {
737
- type: block.type,
738
- name: block.name,
739
- id: block.id,
740
- input: '',
741
- inputValue: 'input' in block ? block.input : undefined,
742
- });
743
- if (block.type === 'thinking') {
744
- onEvent({ type: 'thinking_start' });
745
- }
746
- }
747
- function handleContentBlockDelta(index, delta) {
748
- const state = blocks.get(blockKey(index));
749
- if (delta.type === 'text_delta' && typeof delta.text === 'string') {
750
- if (currentMessageId)
751
- textStreamed.add(currentMessageId);
752
- currentMessageStreamedText = true;
753
- emitSafeText(currentMessageId, delta.text);
754
- return;
755
- }
756
- if (delta.type === 'thinking_delta' && typeof delta.thinking === 'string') {
757
- if (currentMessageId)
758
- thinkingStreamed.add(currentMessageId);
759
- currentMessageStreamedThinking = true;
760
- emitSafeText(currentMessageId, delta.thinking, 'thinking_delta');
761
- return;
762
- }
763
- if (delta.type === 'input_json_delta' && typeof delta.partial_json === 'string') {
764
- applyInputJsonDelta(state, delta.partial_json, onEvent);
765
- }
766
- }
767
- /** Emits a finished tool_use block from its streamed JSON text, else from its complete input value. */
768
- function emitFinishedToolBlock(state, id) {
769
- if (state.input.trim()) {
770
- try {
771
- emitToolUse(id, state.name, JSON.parse(state.input));
772
- streamedToolUseIds.add(id);
773
- }
774
- catch {
775
- // Fall through to the final assistant wrapper's input if the
776
- // streamed JSON is malformed or incomplete.
777
- }
778
- return;
779
- }
780
- if (state.inputValue === undefined)
781
- return;
782
- emitToolUse(id, state.name, state.inputValue);
783
- streamedToolUseIds.add(id);
784
- }
785
- function handleContentBlockStop(ev) {
786
- const key = blockKey(ev.index);
787
- const state = blocks.get(key);
788
- if (state?.type === 'tool_use' && typeof state.id === 'string')
789
- emitFinishedToolBlock(state, state.id);
790
- blocks.delete(key);
791
- }
792
- // Usage is keyed per message; an id-less message is keyed by its epoch.
793
- function usageMessageKey() {
794
- return currentMessageId ?? `anon${anonymousMessageEpoch}`;
795
- }
796
- function handleMessageDeltaStreamEvent(ev) {
797
- segmentUsage.observe({ messageId: usageMessageKey(), usage: ev.usage ?? (isRecord(ev.delta) ? ev.delta.usage : undefined) });
798
- if (isRecord(ev.delta))
799
- handleMessageDeltaEvent(ev.delta);
800
- }
801
- function handleMessageDeltaEvent(delta) {
802
- const stopReason = typeof delta.stop_reason === 'string' ? delta.stop_reason : null;
803
- if (stopReason)
804
- emitTurnEnd(stopReason);
805
- }
806
- function handleStreamEvent(ev) {
807
- switch (ev.type) {
808
- case 'message_start':
809
- handleMessageStart(ev);
810
- return;
811
- case 'content_block_start':
812
- if (isRecord(ev.content_block))
813
- handleContentBlockStart(ev.index, ev.content_block);
814
- return;
815
- case 'content_block_delta':
816
- if (isRecord(ev.delta))
817
- handleContentBlockDelta(ev.index, ev.delta);
818
- return;
819
- case 'content_block_stop':
820
- handleContentBlockStop(ev);
821
- return;
822
- case 'message_delta':
823
- handleMessageDeltaStreamEvent(ev);
824
- return;
825
- }
826
- }
827
- function flushPendingArtifactText() {
828
- const text = `${pendingArtifactText}${artifactOpenCandidate}${duplicateArtifactCandidate}`;
829
- if (!text)
830
- return;
831
- pendingArtifactText = '';
832
- artifactOpenCandidate = '';
833
- duplicateArtifactCandidate = '';
834
- suppressNextArtifactText = false;
835
- suppressDuplicateArtifactText = false;
836
- recentWriteContents.length = 0;
837
- wroteHtmlFileThisTurn = false;
838
- emitSafeText(currentMessageId, text);
839
- }
840
- return { feed, flush };
41
+ return createStreamHandlerImpl({ onEvent, options });
841
42
  }
842
43
  //# sourceMappingURL=claude-stream.js.map