qlogicagent 2.24.1 → 2.24.2

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 (297) hide show
  1. package/README.md +52 -324
  2. package/dist/agent.js +38 -43
  3. package/dist/cli.js +7 -7
  4. package/dist/default-project-knowledge/INSTRUCTIONS.md +7 -7
  5. package/dist/default-project-knowledge/rules/project-workflow.md +6 -6
  6. package/dist/index.js +265 -1018
  7. package/dist/orchestration.js +10 -10
  8. package/dist/types/agent/runtime-vars.d.ts +1 -16
  9. package/dist/types/agent/tool-loop/compression-pipeline.d.ts +0 -2
  10. package/dist/types/agent/tool-loop.d.ts +0 -6
  11. package/dist/types/agent/types.d.ts +3 -22
  12. package/dist/types/cli/acp-commands.d.ts +4 -5
  13. package/dist/types/cli/acp-message-router.d.ts +1 -2
  14. package/dist/types/cli/acp-session-handlers.d.ts +6 -12
  15. package/dist/types/cli/acp-session-host.d.ts +5 -48
  16. package/dist/types/cli/adapter-launch-config.d.ts +14 -0
  17. package/dist/types/cli/agent-runtime-bootstrap.d.ts +2 -23
  18. package/dist/types/cli/agent-runtime-session-state.d.ts +1 -6
  19. package/dist/types/cli/base-tool-bootstrap.d.ts +0 -2
  20. package/dist/types/cli/cli-acp-request-handler.d.ts +3 -5
  21. package/dist/types/cli/core-tool-coordinator.d.ts +0 -4
  22. package/dist/types/cli/core-tools/agent-tool-service.d.ts +0 -3
  23. package/dist/types/cli/core-tools/fork-system-prompt.d.ts +1 -5
  24. package/dist/types/cli/handlers/files-handler.d.ts +0 -6
  25. package/dist/types/cli/handlers/turn-handler.d.ts +7 -83
  26. package/dist/types/cli/main.d.ts +2 -4
  27. package/dist/types/cli/permission-approval-bridge.d.ts +2 -6
  28. package/dist/types/cli/permission-bootstrap.d.ts +2 -12
  29. package/dist/types/cli/plugin-bootstrap.d.ts +2 -4
  30. package/dist/types/cli/runtime-hook-bootstrap.d.ts +0 -21
  31. package/dist/types/cli/session-context.d.ts +4 -14
  32. package/dist/types/cli/session-coordinator.d.ts +1 -9
  33. package/dist/types/cli/stdio-acp-protocol-coordinator.d.ts +2 -9
  34. package/dist/types/cli/stdio-acp-request-host.d.ts +3 -15
  35. package/dist/types/cli/stdio-agent-session-bootstrap.d.ts +3 -23
  36. package/dist/types/cli/stdio-runtime-bootstrap.d.ts +0 -8
  37. package/dist/types/cli/stdio-runtime-services.d.ts +2 -13
  38. package/dist/types/cli/stdio-server.d.ts +6 -128
  39. package/dist/types/cli/tool-bootstrap.d.ts +4 -8
  40. package/dist/types/cli/tool-catalog.d.ts +2 -2
  41. package/dist/types/cli/tool-invoker-factory.d.ts +0 -2
  42. package/dist/types/cli/tool-registry-adapter.d.ts +3 -7
  43. package/dist/types/cli/tool-result-processor.d.ts +0 -1
  44. package/dist/types/cli/turn-core.d.ts +6 -10
  45. package/dist/types/cli/turn-event-forwarder.d.ts +6 -3
  46. package/dist/types/cli/turn-lifecycle.d.ts +0 -3
  47. package/dist/types/cli/turn-project-router.d.ts +0 -7
  48. package/dist/types/contracts/hooks.d.ts +1 -20
  49. package/dist/types/contracts/tool-execution-evidence.d.ts +20 -1
  50. package/dist/types/contracts/turn-event.d.ts +2 -2
  51. package/dist/types/orchestration/index.d.ts +1 -1
  52. package/dist/types/protocol/notifications.d.ts +2 -9
  53. package/dist/types/protocol/wire/acp-protocol.d.ts +12 -186
  54. package/dist/types/protocol/wire/capability-transport.d.ts +0 -2
  55. package/dist/types/protocol/wire/index.d.ts +2 -10
  56. package/dist/types/protocol/wire/notification-payloads.d.ts +4 -989
  57. package/dist/types/protocol/wire/thread-protocol.d.ts +24 -3
  58. package/dist/types/runtime/config/tunable-defaults.d.ts +3 -75
  59. package/dist/types/runtime/execution/forked-agent.d.ts +2 -5
  60. package/dist/types/runtime/execution/streaming-tool-executor.d.ts +0 -2
  61. package/dist/types/runtime/execution/tool-result-storage.d.ts +13 -4
  62. package/dist/types/runtime/infra/agent-paths.d.ts +4 -54
  63. package/dist/types/runtime/infra/agent-project-projection.d.ts +20 -0
  64. package/dist/types/runtime/infra/background-tasks.d.ts +3 -3
  65. package/dist/types/runtime/infra/default-path-service.d.ts +0 -7
  66. package/dist/types/runtime/infra/llmrouter-catalog.d.ts +1 -1
  67. package/dist/types/runtime/infra/model-registry.d.ts +6 -9
  68. package/dist/types/runtime/infra/project-store.d.ts +3 -3
  69. package/dist/types/runtime/infra/subagent-turn-snapshot.d.ts +54 -7
  70. package/dist/types/runtime/infra/task-runtime.d.ts +1 -1
  71. package/dist/types/runtime/ports/agent-runtime-ports.d.ts +1 -3
  72. package/dist/types/runtime/ports/index.d.ts +0 -4
  73. package/dist/types/runtime/ports/path-service.d.ts +1 -9
  74. package/dist/types/runtime/ports/tool-contracts.d.ts +0 -1
  75. package/dist/types/runtime/session/agent-session-projection.d.ts +37 -0
  76. package/dist/types/runtime/tasks/task-types.d.ts +2 -25
  77. package/dist/types/skills/mcp/mcp-manager.d.ts +2 -2
  78. package/dist/types/skills/plugins/plugin-loader.d.ts +1 -1
  79. package/dist/types/skills/skill-system/skill-category.d.ts +4 -2
  80. package/dist/types/skills/tools.d.ts +1 -18
  81. package/dist/types/test-support/project-store-fixture.d.ts +4 -4
  82. package/dist/types/transport/acp-event-emitter.d.ts +1 -20
  83. package/dist/types/transport/acp-server.d.ts +8 -88
  84. package/package.json +4 -96
  85. package/dist/agent-contract.js +0 -1
  86. package/dist/host-contract.js +0 -1
  87. package/dist/host-session-collection-contract.js +0 -1
  88. package/dist/memory-category-contract.js +0 -1
  89. package/dist/permissions.js +0 -1
  90. package/dist/plugin-marketplace-compute.js +0 -1
  91. package/dist/project-memory-host.js +0 -38
  92. package/dist/protocol.js +0 -1
  93. package/dist/skill-category-contract.js +0 -1
  94. package/dist/tunables.js +0 -1
  95. package/dist/types/agent/memory-recall-context.d.ts +0 -22
  96. package/dist/types/agent/memory-recall-injection.d.ts +0 -32
  97. package/dist/types/cli/acp-extended-handlers.d.ts +0 -110
  98. package/dist/types/cli/acp-extended-host-adapter.d.ts +0 -20
  99. package/dist/types/cli/community-resource-installer.d.ts +0 -39
  100. package/dist/types/cli/community-skill-installer.d.ts +0 -18
  101. package/dist/types/cli/community-workflow-installer.d.ts +0 -29
  102. package/dist/types/cli/default-project-bootstrap.d.ts +0 -12
  103. package/dist/types/cli/dream-host-adapter.d.ts +0 -24
  104. package/dist/types/cli/gateway-rpc-connection.d.ts +0 -50
  105. package/dist/types/cli/handlers/community-handler.d.ts +0 -14
  106. package/dist/types/cli/handlers/config-handler.d.ts +0 -19
  107. package/dist/types/cli/handlers/control-handler.d.ts +0 -29
  108. package/dist/types/cli/handlers/dream-handler.d.ts +0 -41
  109. package/dist/types/cli/handlers/goal-handler.d.ts +0 -66
  110. package/dist/types/cli/handlers/memory-handler.d.ts +0 -23
  111. package/dist/types/cli/handlers/product-handler.d.ts +0 -35
  112. package/dist/types/cli/handlers/session-handler.d.ts +0 -29
  113. package/dist/types/cli/handlers/skill-curator-handler.d.ts +0 -8
  114. package/dist/types/cli/handlers/solo-handler.d.ts +0 -25
  115. package/dist/types/cli/handlers/turn-baseline-handler.d.ts +0 -8
  116. package/dist/types/cli/handlers/workflow-compute-handler.d.ts +0 -8
  117. package/dist/types/cli/handlers/working-materials-handler.d.ts +0 -9
  118. package/dist/types/cli/idle-dream-coordinator.d.ts +0 -57
  119. package/dist/types/cli/memory-background-coordinator.d.ts +0 -26
  120. package/dist/types/cli/memory-candidate-service.d.ts +0 -75
  121. package/dist/types/cli/memory-coordinator.d.ts +0 -40
  122. package/dist/types/cli/multi-agent-handler-host.d.ts +0 -16
  123. package/dist/types/cli/multi-agent-state-coordinator.d.ts +0 -8
  124. package/dist/types/cli/orchestration-memory-context.d.ts +0 -23
  125. package/dist/types/cli/product-acp-params.d.ts +0 -30
  126. package/dist/types/cli/product-coordinator.d.ts +0 -21
  127. package/dist/types/cli/project-memory-store-factory.d.ts +0 -12
  128. package/dist/types/cli/project-template-seeder.d.ts +0 -5
  129. package/dist/types/cli/rpc-registry.d.ts +0 -56
  130. package/dist/types/cli/session-history-coordinator.d.ts +0 -8
  131. package/dist/types/cli/session-query-service.d.ts +0 -27
  132. package/dist/types/cli/stdio-rpc-handler-hosts.d.ts +0 -56
  133. package/dist/types/cli/stdio-session-runtime-coordinator.d.ts +0 -17
  134. package/dist/types/cli/task-distillation-coordinator.d.ts +0 -146
  135. package/dist/types/cli/turn-ask-user-setup.d.ts +0 -24
  136. package/dist/types/cli/turn-suggestion-generator.d.ts +0 -15
  137. package/dist/types/contracts/memory-recall-packet.d.ts +0 -31
  138. package/dist/types/contracts/memory-response-contract.d.ts +0 -2
  139. package/dist/types/host-contract/fts-segment.d.ts +0 -20
  140. package/dist/types/host-contract/index.d.ts +0 -1819
  141. package/dist/types/host-contract/memory-category.d.ts +0 -8
  142. package/dist/types/host-contract/skill-category.d.ts +0 -5
  143. package/dist/types/host-session-collection-contract.d.ts +0 -65
  144. package/dist/types/orchestration/agent-instance.d.ts +0 -215
  145. package/dist/types/orchestration/agent-roster.d.ts +0 -32
  146. package/dist/types/orchestration/dag-scheduler.d.ts +0 -219
  147. package/dist/types/orchestration/delegate-approval-policy.d.ts +0 -8
  148. package/dist/types/orchestration/delegate-bridge.d.ts +0 -8
  149. package/dist/types/orchestration/goal-acceptance.d.ts +0 -17
  150. package/dist/types/orchestration/goal-context-envelope.d.ts +0 -7
  151. package/dist/types/orchestration/goal-loop-coordinator.d.ts +0 -151
  152. package/dist/types/orchestration/goal-mode-adapters.d.ts +0 -152
  153. package/dist/types/orchestration/goal-run-persistence.d.ts +0 -21
  154. package/dist/types/orchestration/goal-run-types.d.ts +0 -225
  155. package/dist/types/orchestration/planner-memory-brief.d.ts +0 -39
  156. package/dist/types/orchestration/product-budget.d.ts +0 -94
  157. package/dist/types/orchestration/product-checkpoint.d.ts +0 -50
  158. package/dist/types/orchestration/product-dag-mutation-applier.d.ts +0 -10
  159. package/dist/types/orchestration/product-persistence.d.ts +0 -90
  160. package/dist/types/orchestration/product-planner.d.ts +0 -332
  161. package/dist/types/orchestration/product-run-coordinator.d.ts +0 -49
  162. package/dist/types/orchestration/product-worktree.d.ts +0 -19
  163. package/dist/types/orchestration/run-state-host-authority.d.ts +0 -7
  164. package/dist/types/orchestration/solo-evaluator.d.ts +0 -179
  165. package/dist/types/orchestration/solo-persistence.d.ts +0 -47
  166. package/dist/types/orchestration/solo-spec-builder.d.ts +0 -58
  167. package/dist/types/orchestration/testing/delegate-test-bridge.d.ts +0 -23
  168. package/dist/types/orchestration/testing/host-agent-provider-directory-fixture.d.ts +0 -7
  169. package/dist/types/orchestration/testing/run-state-client-double.d.ts +0 -13
  170. package/dist/types/orchestration/workflow/budget-permission-gate.d.ts +0 -94
  171. package/dist/types/orchestration/workflow/builtin-capabilities.d.ts +0 -3
  172. package/dist/types/orchestration/workflow/builtin-executors.d.ts +0 -18
  173. package/dist/types/orchestration/workflow/capability-catalog.d.ts +0 -72
  174. package/dist/types/orchestration/workflow/cron-schedule.d.ts +0 -36
  175. package/dist/types/orchestration/workflow/data-item.d.ts +0 -39
  176. package/dist/types/orchestration/workflow/expression.d.ts +0 -60
  177. package/dist/types/orchestration/workflow/host-executors.d.ts +0 -15
  178. package/dist/types/orchestration/workflow/n8n-expression.d.ts +0 -48
  179. package/dist/types/orchestration/workflow/n8n-import.d.ts +0 -64
  180. package/dist/types/orchestration/workflow/n8n-template-compat.d.ts +0 -5
  181. package/dist/types/orchestration/workflow/node-registry.d.ts +0 -32
  182. package/dist/types/orchestration/workflow/node-schema.d.ts +0 -249
  183. package/dist/types/orchestration/workflow/params-schema.d.ts +0 -69
  184. package/dist/types/orchestration/workflow/qla-executor-host.d.ts +0 -63
  185. package/dist/types/orchestration/workflow/run-checkpoint-store.d.ts +0 -53
  186. package/dist/types/orchestration/workflow/run-history-store.d.ts +0 -103
  187. package/dist/types/orchestration/workflow/semantic-acceptance.d.ts +0 -65
  188. package/dist/types/orchestration/workflow/trigger-validation.d.ts +0 -22
  189. package/dist/types/orchestration/workflow/workflow-audit-store.d.ts +0 -31
  190. package/dist/types/orchestration/workflow/workflow-authoring.d.ts +0 -74
  191. package/dist/types/orchestration/workflow/workflow-bundle.d.ts +0 -51
  192. package/dist/types/orchestration/workflow/workflow-controller.d.ts +0 -237
  193. package/dist/types/orchestration/workflow/workflow-edit-context.d.ts +0 -46
  194. package/dist/types/orchestration/workflow/workflow-error.d.ts +0 -28
  195. package/dist/types/orchestration/workflow/workflow-intent-contract.d.ts +0 -56
  196. package/dist/types/orchestration/workflow/workflow-patch.d.ts +0 -122
  197. package/dist/types/orchestration/workflow/workflow-render.d.ts +0 -40
  198. package/dist/types/orchestration/workflow/workflow-runtime.d.ts +0 -184
  199. package/dist/types/orchestration/workflow/workflow-scheduler.d.ts +0 -122
  200. package/dist/types/orchestration/workflow/workflow-store.d.ts +0 -85
  201. package/dist/types/orchestration/workflow/workflow-template-setup.d.ts +0 -65
  202. package/dist/types/orchestration/workflow/workflow-trigger.d.ts +0 -43
  203. package/dist/types/orchestration/workflow-chat-builder.d.ts +0 -152
  204. package/dist/types/orchestration/worktree-task-prompt.d.ts +0 -1
  205. package/dist/types/permissions.d.ts +0 -4
  206. package/dist/types/project-memory-host.d.ts +0 -4
  207. package/dist/types/protocol/agent-contract.d.ts +0 -93
  208. package/dist/types/protocol/methods.d.ts +0 -645
  209. package/dist/types/protocol/wire/acp-agent-management.d.ts +0 -533
  210. package/dist/types/protocol/wire/agent-events.d.ts +0 -1
  211. package/dist/types/protocol/wire/agent-methods.d.ts +0 -500
  212. package/dist/types/protocol/wire/agent-rpc.d.ts +0 -100
  213. package/dist/types/protocol/wire/gateway-contract.d.ts +0 -61
  214. package/dist/types/protocol/wire/gateway-rpc.d.ts +0 -1177
  215. package/dist/types/protocol/wire/memory-provider-lifecycle.d.ts +0 -31
  216. package/dist/types/protocol/wire/turn.d.ts +0 -208
  217. package/dist/types/runtime/community/autonomy-budget.d.ts +0 -26
  218. package/dist/types/runtime/community/community-consent-client.d.ts +0 -55
  219. package/dist/types/runtime/community/package-materialize.d.ts +0 -19
  220. package/dist/types/runtime/community/ranged-download.d.ts +0 -21
  221. package/dist/types/runtime/community/registry-signature.d.ts +0 -48
  222. package/dist/types/runtime/execution/dream-agent.d.ts +0 -273
  223. package/dist/types/runtime/execution/dream-category-context.d.ts +0 -47
  224. package/dist/types/runtime/execution/memory-decay.d.ts +0 -73
  225. package/dist/types/runtime/execution/turn-progress-notifier.d.ts +0 -16
  226. package/dist/types/runtime/hooks/memory-hooks.d.ts +0 -111
  227. package/dist/types/runtime/infra/acp-host-handler.d.ts +0 -31
  228. package/dist/types/runtime/infra/acp-protocol-adapter.d.ts +0 -209
  229. package/dist/types/runtime/infra/acp-usage-tracker.d.ts +0 -46
  230. package/dist/types/runtime/infra/cloud-auth-host-authority.d.ts +0 -4
  231. package/dist/types/runtime/infra/feedback-distillation-worker.d.ts +0 -20
  232. package/dist/types/runtime/infra/feedback-distillation.d.ts +0 -32
  233. package/dist/types/runtime/infra/feedback-event-store.d.ts +0 -179
  234. package/dist/types/runtime/infra/feedback-host-authority.d.ts +0 -4
  235. package/dist/types/runtime/infra/feedback-outbox.d.ts +0 -26
  236. package/dist/types/runtime/infra/feedback-redaction.d.ts +0 -71
  237. package/dist/types/runtime/infra/feedback-upload-client.d.ts +0 -39
  238. package/dist/types/runtime/infra/feedback-upload-worker.d.ts +0 -11
  239. package/dist/types/runtime/infra/host-agent-provider-directory.d.ts +0 -17
  240. package/dist/types/runtime/infra/project-authority-facade.d.ts +0 -11
  241. package/dist/types/runtime/infra/project-data-paths.d.ts +0 -24
  242. package/dist/types/runtime/infra/project-host-authority.d.ts +0 -11
  243. package/dist/types/runtime/infra/project-instructions-store.d.ts +0 -30
  244. package/dist/types/runtime/infra/turn-baseline-store.d.ts +0 -102
  245. package/dist/types/runtime/infra/turn-telemetry-store.d.ts +0 -100
  246. package/dist/types/runtime/infra/working-materials-store.d.ts +0 -29
  247. package/dist/types/runtime/memory/find-relevant-memories.d.ts +0 -26
  248. package/dist/types/runtime/memory/implicit-extraction.d.ts +0 -69
  249. package/dist/types/runtime/memory/memory-recall-attribution.d.ts +0 -24
  250. package/dist/types/runtime/ports/memory-provider.d.ts +0 -219
  251. package/dist/types/runtime/ports/memory-recall-source.d.ts +0 -14
  252. package/dist/types/runtime/ports/memory-writer.d.ts +0 -70
  253. package/dist/types/runtime/ports/project-memory-store.d.ts +0 -49
  254. package/dist/types/runtime/prompt/host-skill-directory.d.ts +0 -16
  255. package/dist/types/runtime/session/group-session-split.d.ts +0 -38
  256. package/dist/types/runtime/session/inbound-upload-persistence.d.ts +0 -47
  257. package/dist/types/runtime/session/session-catalog.d.ts +0 -12
  258. package/dist/types/runtime/session/session-deletion-guard.d.ts +0 -4
  259. package/dist/types/runtime/session/session-locator.d.ts +0 -26
  260. package/dist/types/runtime/session/session-metadata-store.d.ts +0 -8
  261. package/dist/types/runtime/session/session-paths.d.ts +0 -8
  262. package/dist/types/runtime/session/session-permission-store.d.ts +0 -6
  263. package/dist/types/runtime/session/session-persistence.d.ts +0 -37
  264. package/dist/types/runtime/session/session-recovery.d.ts +0 -62
  265. package/dist/types/runtime/session/session-resource-key.d.ts +0 -28
  266. package/dist/types/runtime/session/session-resume.d.ts +0 -9
  267. package/dist/types/runtime/session/session-schema.d.ts +0 -10
  268. package/dist/types/runtime/session/session-summary.d.ts +0 -7
  269. package/dist/types/runtime/session/session-title.d.ts +0 -9
  270. package/dist/types/runtime/session/session-transcript-store.d.ts +0 -30
  271. package/dist/types/runtime/session/session-types.d.ts +0 -113
  272. package/dist/types/runtime/session/session-write-queue.d.ts +0 -3
  273. package/dist/types/skills/memory/host-memory-provider.d.ts +0 -235
  274. package/dist/types/skills/memory/memdir.d.ts +0 -111
  275. package/dist/types/skills/memory/memory-content-safety.d.ts +0 -1
  276. package/dist/types/skills/memory/memory-vector-utils.d.ts +0 -2
  277. package/dist/types/skills/memory/task-distillation.d.ts +0 -183
  278. package/dist/types/skills/plugins/plugin-marketplace.d.ts +0 -43
  279. package/dist/types/skills/skill-system/skill-bundles.d.ts +0 -8
  280. package/dist/types/skills/skill-system/skill-lifecycle.d.ts +0 -89
  281. package/dist/types/test-support/run-state-authority-setup.d.ts +0 -1
  282. package/dist/types/transport/delegate-client.d.ts +0 -82
  283. package/dist/types/transport/host-capability-client.d.ts +0 -21
  284. package/dist/types/transport/host-cloud-auth-client.d.ts +0 -10
  285. package/dist/types/transport/host-community-client.d.ts +0 -7
  286. package/dist/types/transport/host-feedback-client.d.ts +0 -25
  287. package/dist/types/transport/host-profile-client.d.ts +0 -19
  288. package/dist/types/transport/host-project-client.d.ts +0 -16
  289. package/dist/types/transport/host-request-client.d.ts +0 -42
  290. package/dist/types/transport/host-run-state-client.d.ts +0 -23
  291. package/dist/types/transport/host-session-client.d.ts +0 -30
  292. package/dist/types/tunables.d.ts +0 -2
  293. package/dist/types/workflow-host.d.ts +0 -38
  294. package/dist/workflow-host.js +0 -11
  295. /package/dist/types/{host-contract → protocol/wire}/acp-content.d.ts +0 -0
  296. /package/dist/types/{host-contract → runtime/infra}/project-id.d.ts +0 -0
  297. /package/dist/types/{host-contract → runtime/infra}/provider-profile.d.ts +0 -0
@@ -1,29 +1,29 @@
1
- function be(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Re(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{},...t.contentBlocks!==void 0?{contentBlocks:t.contentBlocks}:{},...t.structuredContent!==void 0?{structuredContent:t.structuredContent}:{},...t.mcpMeta!==void 0?{mcpMeta:t.mcpMeta}:{},...t.mcpIsError!==void 0?{mcpIsError:t.mcpIsError}:{}}}var xe=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,T={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Ae=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Se=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,ke=512,Ee=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Me=new Set([500,502,503,504,521,522,523,524,529]),Ie=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],ve=["upgrade your plan","upgrade plan","current plan","subscription"],we=["daily","weekly","monthly"],Oe=["try again","retry","temporary","cooldown"],Le=["usage limit","rate limit","organization usage"],Pe=["organization","workspace"],Ne=["billing period","exceeded","reached","exhausted"],De=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,Fe=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function h(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Be(e){return h(e,T.format)}function Q(e){return h(e,T.rateLimit)}function Ue(e){return h(e,T.timeout)}function Ge(e){return xe.test(e)}function P(e){let t=e.toLowerCase();return t?e.length>ke?Se.test(t):h(t,T.billing)?!0:Ae.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function ee(e){return h(e,T.authPermanent)}function $e(e){return h(e,T.auth)}function te(e){return h(e,T.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function je(e){return y(e,Ie)||y(e,ve)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function ze(e){let t=y(e,we),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,Pe);return y(e,Oe)&&y(e,Le)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,Ne))}function qe(e){return e.trim().toLowerCase().replace(Fe,"").trim()}function ne(e){let t=qe(e);return!t||je(t)?"billing":Q(t)||ze(t)?"rate_limit":"billing"}function He(e){return De.test(e)?ne(e):null}function oe(e){let t=e.match(Ee);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Ye(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Xe(e){let t=e.trim();if(!t)return!1;let n=oe(t);return n?Me.has(n.code):!1}function re(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?ne(t):"billing":e===429?"rate_limit":e===401||e===403?t&&ee(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&te(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&P(t)?"billing":"format":null}function We(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function Ke(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function se(e){if(Ke(e))return"session_expired";if(We(e))return"model_not_found";let t=He(e);return t||(Ge(e)?P(e)?"billing":"rate_limit":Q(e)?"rate_limit":te(e)?"overloaded":Xe(e)?oe(e.trim())?.code===529?"overloaded":"timeout":Ye(e)?"timeout":Be(e)?"format":P(e)?"billing":Ue(e)?"timeout":ee(e)?"auth_permanent":$e(e)?"auth":null)}var Ve=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ie(e){return Ve.has(e)}var Je={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"};function Ze(e,t){let n=re(e,t)??(t?se(t):null);return n?Je[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function q(e){return typeof e.compressAsync=="function"}var E="[Context capsule v1]";function C(e){return e.replace(/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|password|passwd|secret)\b\s*[:=]\s*["']?[^\s"',;]+/giu,"$1=[REDACTED]").replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}\b/gu,"[REDACTED_TOKEN]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}\b/giu,"Bearer [REDACTED]")}function Qe(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function A(e){if(!(!e||typeof e.content!="string"||!e.content.startsWith(E)))try{let t=JSON.parse(e.content.slice(E.length).trim());return t?.receipt?.version===1&&typeof t.receipt.digest=="string"?t:void 0}catch{return}}function ce(e,t,n,o){let r=e.map(c=>c.itemId).filter(c=>!!c),i={...o?.state.anchors??{}};for(let c of e)for(let u of c.contextAnchors??[]){let p=i[u.category]??[];i[u.category]=[...new Set([...p,C(u.value)])].slice(-50)}let s=[...o?.state.userRequests??[],...e.filter(c=>c.role==="user").map(c=>C(typeof c.content=="string"?c.content:JSON.stringify(c.content??"")))].slice(-50),a={summary:C(t),userRequests:s,anchors:i},l={version:1,sourceMessageCount:(o?.receipt.sourceMessageCount??0)+e.length,sourceItemIds:[...new Set([...o?.receipt.sourceItemIds??[],...r])].slice(-200),firstItemId:o?.receipt.firstItemId??r[0],lastItemId:r.at(-1)??o?.receipt.lastItemId,priorDigest:o?.receipt.digest,tokensBefore:(o?.receipt.tokensBefore??0)+e.reduce((c,u)=>c+n(u),0)};return{receipt:{...l,digest:Qe(JSON.stringify({receipt:l,state:a}))},state:a}}function ue(e){return{role:"system",content:`${E}
2
- ${JSON.stringify(e)}`}}var ae=4;function le(e){return{role:"system",content:`[${e} earlier messages removed to fit the context budget]`}}var N=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let p of t)p.role==="system"?o.push(p):r.push(p);let i=n;for(let p of o)i-=this.estimateTokens(p);let s;for(let p of r)if(p.role==="user"){s=p;break}if(s&&(i-=this.estimateTokens(s)),i<=0){let p=r.length-(s?1:0),d=s?[...o,s]:[...o];return p>0&&d.push(le(p)),{messages:d,droppedCount:p,strategy:"sliding-window"}}let a=[],l=0;for(let p=r.length-1;p>=0;p--){let d=r[p];if(d===s)continue;let m=this.estimateTokens(d);if(i-m<0&&l>=ae)break;if(i-m<0&&l<ae){a.unshift(d),l++;continue}i-=m,a.unshift(d),l++}let c=r.length-(a.length+(s&&!a.includes(s)?1:0)),u=[...o];return s&&!a.includes(s)&&u.push(s),c>0&&u.push(le(c)),u.push(...a),{messages:u,droppedCount:c,strategy:"sliding-window"}}},D=class{constructor(t,n){this.recentCount=t;this.summarize=n}recentCount;summarize;compress(t,n){let o=t.filter(l=>l.role==="system"),r=t.filter(l=>l.role!=="system");if(r.length<=this.recentCount)return{messages:t,droppedCount:0,strategy:"summarize-old"};let i=r.slice(0,r.length-this.recentCount),s=r.slice(r.length-this.recentCount),a=this.summarize(i);return{messages:[...o,{role:"system",content:`[Conversation summary]
3
- ${a}`},...s],droppedCount:i.length,strategy:"summarize-old"}}},F=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(i=>i.role!=="tool"||typeof i.content!="string"||i.content.length<=this.maxToolResultChars?i:(o++,{...i,content:et(i.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function et(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let i=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
1
+ function _e(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Re(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{},...t.contentBlocks!==void 0?{contentBlocks:t.contentBlocks}:{},...t.structuredContent!==void 0?{structuredContent:t.structuredContent}:{},...t.mcpMeta!==void 0?{mcpMeta:t.mcpMeta}:{},...t.mcpIsError!==void 0?{mcpIsError:t.mcpIsError}:{}}}var xe=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,h={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},ke=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Ae=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Se=512,Ee=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Me=new Set([500,502,503,504,521,522,523,524,529]),ve=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ie=["upgrade your plan","upgrade plan","current plan","subscription"],we=["daily","weekly","monthly"],Oe=["try again","retry","temporary","cooldown"],Le=["usage limit","rate limit","organization usage"],Pe=["organization","workspace"],Ne=["billing period","exceeded","reached","exhausted"],Fe=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,De=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function T(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Be(e){return T(e,h.format)}function Q(e){return T(e,h.rateLimit)}function Ue(e){return T(e,h.timeout)}function Ge(e){return xe.test(e)}function P(e){let t=e.toLowerCase();return t?e.length>Se?Ae.test(t):T(t,h.billing)?!0:ke.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function ee(e){return T(e,h.authPermanent)}function $e(e){return T(e,h.auth)}function te(e){return T(e,h.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function je(e){return y(e,ve)||y(e,Ie)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function ze(e){let t=y(e,we),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,Pe);return y(e,Oe)&&y(e,Le)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,Ne))}function qe(e){return e.trim().toLowerCase().replace(De,"").trim()}function ne(e){let t=qe(e);return!t||je(t)?"billing":Q(t)||ze(t)?"rate_limit":"billing"}function He(e){return Fe.test(e)?ne(e):null}function oe(e){let t=e.match(Ee);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Ye(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function We(e){let t=e.trim();if(!t)return!1;let n=oe(t);return n?Me.has(n.code):!1}function re(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?ne(t):"billing":e===429?"rate_limit":e===401||e===403?t&&ee(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&te(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&P(t)?"billing":"format":null}function Xe(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function Ke(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function se(e){if(Ke(e))return"session_expired";if(Xe(e))return"model_not_found";let t=He(e);return t||(Ge(e)?P(e)?"billing":"rate_limit":Q(e)?"rate_limit":te(e)?"overloaded":We(e)?oe(e.trim())?.code===529?"overloaded":"timeout":Ye(e)?"timeout":Be(e)?"format":P(e)?"billing":Ue(e)?"timeout":ee(e)?"auth_permanent":$e(e)?"auth":null)}var Ve=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ie(e){return Ve.has(e)}var Je={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"};function Ze(e,t){let n=re(e,t)??(t?se(t):null);return n?Je[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function q(e){return typeof e.compressAsync=="function"}var E="[Context capsule v1]";function C(e){return e.replace(/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|password|passwd|secret)\b\s*[:=]\s*["']?[^\s"',;]+/giu,"$1=[REDACTED]").replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}\b/gu,"[REDACTED_TOKEN]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}\b/giu,"Bearer [REDACTED]")}function Qe(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function k(e){if(!(!e||typeof e.content!="string"||!e.content.startsWith(E)))try{let t=JSON.parse(e.content.slice(E.length).trim());return t?.receipt?.version===1&&typeof t.receipt.digest=="string"?t:void 0}catch{return}}function ce(e,t,n,o){let r=e.map(c=>c.itemId).filter(c=>!!c),i={...o?.state.anchors??{}};for(let c of e)for(let u of c.contextAnchors??[]){let p=i[u.category]??[];i[u.category]=[...new Set([...p,C(u.value)])].slice(-50)}let s=[...o?.state.userRequests??[],...e.filter(c=>c.role==="user").map(c=>C(typeof c.content=="string"?c.content:JSON.stringify(c.content??"")))].slice(-50),a={summary:C(t),userRequests:s,anchors:i},l={version:1,sourceMessageCount:(o?.receipt.sourceMessageCount??0)+e.length,sourceItemIds:[...new Set([...o?.receipt.sourceItemIds??[],...r])].slice(-200),firstItemId:o?.receipt.firstItemId??r[0],lastItemId:r.at(-1)??o?.receipt.lastItemId,priorDigest:o?.receipt.digest,tokensBefore:(o?.receipt.tokensBefore??0)+e.reduce((c,u)=>c+n(u),0)};return{receipt:{...l,digest:Qe(JSON.stringify({receipt:l,state:a}))},state:a}}function ue(e){return{role:"system",content:`${E}
2
+ ${JSON.stringify(e)}`}}var ae=4;function le(e){return{role:"system",content:`[${e} earlier messages removed to fit the context budget]`}}var N=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let p of t)p.role==="system"?o.push(p):r.push(p);let i=n;for(let p of o)i-=this.estimateTokens(p);let s;for(let p of r)if(p.role==="user"){s=p;break}if(s&&(i-=this.estimateTokens(s)),i<=0){let p=r.length-(s?1:0),d=s?[...o,s]:[...o];return p>0&&d.push(le(p)),{messages:d,droppedCount:p,strategy:"sliding-window"}}let a=[],l=0;for(let p=r.length-1;p>=0;p--){let d=r[p];if(d===s)continue;let m=this.estimateTokens(d);if(i-m<0&&l>=ae)break;if(i-m<0&&l<ae){a.unshift(d),l++;continue}i-=m,a.unshift(d),l++}let c=r.length-(a.length+(s&&!a.includes(s)?1:0)),u=[...o];return s&&!a.includes(s)&&u.push(s),c>0&&u.push(le(c)),u.push(...a),{messages:u,droppedCount:c,strategy:"sliding-window"}}},F=class{constructor(t,n){this.recentCount=t;this.summarize=n}recentCount;summarize;compress(t,n){let o=t.filter(l=>l.role==="system"),r=t.filter(l=>l.role!=="system");if(r.length<=this.recentCount)return{messages:t,droppedCount:0,strategy:"summarize-old"};let i=r.slice(0,r.length-this.recentCount),s=r.slice(r.length-this.recentCount),a=this.summarize(i);return{messages:[...o,{role:"system",content:`[Conversation summary]
3
+ ${a}`},...s],droppedCount:i.length,strategy:"summarize-old"}}},D=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(i=>i.role!=="tool"||typeof i.content!="string"||i.content.length<=this.maxToolResultChars?i:(o++,{...i,content:et(i.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function et(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let i=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
4
4
  `),n.lastIndexOf(`]
5
5
  `));if(i>t*.5)return n.slice(0,i+1)+`
6
6
  [...truncated: ${e.length-i-1} chars omitted]`}let r=n.lastIndexOf(`
7
7
  `);return r>t*.7?n.slice(0,r)+`
8
8
  [...truncated: ${e.length-r} chars omitted]`:n+`
9
9
  [...truncated: ${e.length-t} chars omitted]`}function tt(...e){return{compress(t,n){let o=t,r=0,i=[];for(let s of e){let a=s.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&i.push(a.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}}}}function nt(...e){return{compress(t,n){let o=t,r=0,i=[];for(let s of e){let a=s.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&i.push(a.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}},async compressAsync(t,n){let o=t,r=0,i=[],s=0,a=!1,l=!1;for(let c of e){let u=q(c)?await c.compressAsync(o,n):c.compress(o,n);o=u.messages,r+=u.droppedCount,u.droppedCount>0&&i.push(u.strategy),u.metrics&&(s+=u.metrics.latencyMs,a=a||u.metrics.usedLlm,l=l||!!u.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none",metrics:s>0||a?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:s,usedLlm:a,cacheInvalidated:l}:void 0}}}}function H(e,t){let n=e.filter(s=>s.role==="user"),o=e.filter(s=>s.tool_calls!=null),r=e.filter(s=>s.role==="tool"),i=["You are a conversation summarizer. Produce a structured summary of the conversation history below.","","## Instructions","Analyze the conversation and produce a summary with these sections:","","### 1. Primary Objective","What is the user's main goal or task? State it in one sentence.","","### 2. Key Decisions Made","List the important decisions, choices, or conclusions reached during the conversation.","","### 3. Current Progress",`Describe the current state. ${o.length>0?`${o.length} tool calls and ${r.length} tool results were exchanged.`:"No tools were used."}`,"","### 4. Pending Tasks","List any tasks that are in-progress or planned but not yet completed.","","### 5. Important Context","Preserve exact non-secret operational facts: file paths, URLs, port numbers, numeric values, version numbers, proper nouns, identifiers, and user-provided constraints. Never reproduce passwords, API keys, bearer tokens, cookies, or credentials; write [REDACTED] instead.","","### 6. All User Messages",`List ALL ${n.length} user messages chronologically, each as 1-2 sentences capturing the core request. Include exact non-secret values, identifiers, and keywords. Redact every secret even if the user asked to remember it. Do NOT omit any user message \u2014 every user request must be traceable in this summary.`,"","### 7. Error & Recovery History","Summarize any errors encountered and how they were resolved.","","### 8. User Preferences Expressed","Note any stated preferences about style, approach, or constraints.","","### 9. Technical State","Note file paths, variable names, API endpoints, or configuration values that were discussed.","","### 10. Conversation Flow","Briefly describe the overall flow: what happened first, what changed, where we are now."];return t?.taskContext&&i.push("","## Additional Context",t.taskContext),i.push("","## Conversation to Summarize","",...e.map(s=>{let a=C(typeof s.content=="string"?s.content:JSON.stringify(s.content??"")),l=s.role==="user"?a:a.length>2e3?a.slice(0,2e3)+"...":a;return`[${s.role}]: ${l}`}),"","## Output Format","Respond with a concise summary covering all 10 sections above. Use markdown headers.","Keep the total summary under 1000 words. Focus on actionable information and exact user requests."),i.join(`
10
- `)}var B=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??M,taskContext:t.taskContext}}compress(t,n){return{messages:t,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=de(t),s=r.findIndex(f=>A(f)!==void 0),a=A(s>=0?r[s]:void 0),l=s>=0?[...r.slice(0,s),...r.slice(s+1)]:r,c=t.reduce((f,L)=>f+this.config.estimateTokens(L),0);if(c<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let u=0,p=0;for(let f=0;f<i.length&&(i[f].role==="user"&&p++,!(p>this.config.protectedHeadExchanges));f++)u=f+1;let d=Math.max(this.config.protectedTailMessages,Math.floor(i.length*.4)),m=Math.max(u,i.length-d);if(m<=u)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let _=i.slice(0,u),b=i.slice(u,m),v=i.slice(m),w=H(b,{taskContext:[this.config.taskContext,a?`Prior verified capsule:
10
+ `)}var B=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??M,taskContext:t.taskContext}}compress(t,n){return{messages:t,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=de(t),s=r.findIndex(f=>k(f)!==void 0),a=k(s>=0?r[s]:void 0),l=s>=0?[...r.slice(0,s),...r.slice(s+1)]:r,c=t.reduce((f,L)=>f+this.config.estimateTokens(L),0);if(c<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let u=0,p=0;for(let f=0;f<i.length&&(i[f].role==="user"&&p++,!(p>this.config.protectedHeadExchanges));f++)u=f+1;let d=Math.max(this.config.protectedTailMessages,Math.floor(i.length*.4)),m=Math.max(u,i.length-d);if(m<=u)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let b=i.slice(0,u),_=i.slice(u,m),I=i.slice(m),w=H(_,{taskContext:[this.config.taskContext,a?`Prior verified capsule:
11
11
  ${JSON.stringify(a.state)}`:void 0].filter(Boolean).join(`
12
12
 
13
- `)||void 0}),S=C(await this.config.summarize(b,w)),O=ue(ce(b,S,this.config.estimateTokens,a)),x=[...l,..._,O,...v],g=Date.now()-o,R=x.reduce((f,L)=>f+this.config.estimateTokens(L),0);return{messages:x,droppedCount:b.length,strategy:"head-tail-protected",metrics:{tokensBefore:c,tokensAfter:R,compressionRatio:c>0?R/c:1,latencyMs:g,usedLlm:!0,cacheInvalidated:!0}}}},U=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??M}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=de(t),s=r.findIndex(g=>A(g)!==void 0),a=s>=0?r[s]:void 0,l=A(a),c=s>=0?[...r.slice(0,s),...r.slice(s+1)]:r,u=Math.max(0,i.length-this.config.preserveRecentCount);if(u<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let p=t.reduce((g,R)=>g+this.config.estimateTokens(R),0);if(p<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=i.slice(0,u),m=i.slice(u),_=l?`Prior verified capsule state:
13
+ `)||void 0}),A=C(await this.config.summarize(_,w)),O=ue(ce(_,A,this.config.estimateTokens,a)),x=[...l,...b,O,...I],g=Date.now()-o,R=x.reduce((f,L)=>f+this.config.estimateTokens(L),0);return{messages:x,droppedCount:_.length,strategy:"head-tail-protected",metrics:{tokensBefore:c,tokensAfter:R,compressionRatio:c>0?R/c:1,latencyMs:g,usedLlm:!0,cacheInvalidated:!0}}}},U=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??M}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=de(t),s=r.findIndex(g=>k(g)!==void 0),a=s>=0?r[s]:void 0,l=k(a),c=s>=0?[...r.slice(0,s),...r.slice(s+1)]:r,u=Math.max(0,i.length-this.config.preserveRecentCount);if(u<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let p=t.reduce((g,R)=>g+this.config.estimateTokens(R),0);if(p<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=i.slice(0,u),m=i.slice(u),b=l?`Prior verified capsule state:
14
14
  ${JSON.stringify(l.state)}
15
15
 
16
- Integrate only the new messages below:`:void 0,b=H(d,{taskContext:_}),v=C(await this.config.summarize(d,b)),w=ue(ce(d,v,this.config.estimateTokens,l)),S=[...c,w,...m],O=Date.now()-o,x=S.reduce((g,R)=>g+this.config.estimateTokens(R),0);return{messages:S,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:p,tokensAfter:x,compressionRatio:p>0?x/p:1,latencyMs:O,usedLlm:!0,cacheInvalidated:!0}}}},G=class{config;constructor(t){this.config=t}compress(t,n){let o=k(t),r=this.config.inner.compress(t,n),i=k(r.messages),s=o!==i&&r.droppedCount>0;return s&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:s}}}async compressAsync(t,n){let o=k(t),r=q(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),i=k(r.messages),s=o!==i&&r.droppedCount>0;return s&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:s}}}},pe={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function ot(e={}){let t={...pe,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function rt(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var $=class{events=[];maxEvents;constructor(t=100){this.maxEvents=t}record(t){this.events.push(t),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let t=this.events.length;if(t===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let n=0,o=0,r=0,i=0,s=0;for(let a of this.events)n+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,o+=a.latencyMs,r+=Math.max(0,a.tokensBefore-a.tokensAfter),a.usedLlm&&i++,a.cacheInvalidated&&s++;return{totalCompressions:t,totalLlmCalls:i,totalCacheInvalidations:s,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},j=class{engines=new Map;activeId;register(t){this.engines.set(t.id,t)}activate(t){return this.engines.has(t)?(this.activeId=t,!0):!1}getActive(){return this.activeId?this.engines.get(this.activeId):void 0}listEngines(){return Array.from(this.engines.values()).map(t=>({id:t.id,label:t.label,active:t.id===this.activeId}))}};function de(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function M(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function k(e){let t=Math.min(e.length,5),n=[];for(let o=0;o<t;o++){let r=e[o],i=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${i}`)}return n.join("|")}var st=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),z=class{constructor(t=20,n=M){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=new Map;for(let l of t){let c=l.tool_calls;if(Array.isArray(c))for(let u of c)u?.id&&u.function?.name&&o.set(u.id,u.function.name)}let r=t.length-this.preserveRecentCount,i=0,s=0;return{messages:t.map((l,c)=>{if(c>=r||l.role!=="tool"||typeof l.content!="string")return l;let u=l.name??o.get(l.tool_call_id??"");if(!u||!st.has(u)||l.content.length<=200)return l;let p=this.estimateTokens(l);return s+=p,i++,{...l,content:`[result cleared \u2014 ${l.content.length} chars]`}}),droppedCount:i,strategy:"micro-compact",metrics:i>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function it(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let i=r.function?.name??"";if(/read|edit|write|file/i.test(i)&&r.function?.arguments)try{let s=JSON.parse(r.function.arguments),a=s.path??s.filePath??s.file_path??s.file;a&&typeof a=="string"&&t.set(a,n)}catch{}}o.role==="tool"&&o.name&&/read|edit|write|file/i.test(o.name)}return[...t.entries()].sort((n,o)=>o[1]-n[1]).map(([n])=>n)}async function at(e,t,n){let o=n.estimateTokens??(d=>Math.ceil(d.length/4)),r=it(t);if(r.length===0)return e;let i=e.map(d=>typeof d.content=="string"?d.content:"").join(`
17
- `),s=r.filter(d=>!i.includes(d));if(s.length===0)return e;let a=n.maxTokenBudget,l=[],c=0;for(let d of s){if(c>=n.maxFiles||a<=0)break;let m=await n.readFile(d);if(!m)continue;let _=o(m);_>a||(a-=_,c++,l.push({role:"system",content:`[Post-compact file recovery: ${d}]
16
+ Integrate only the new messages below:`:void 0,_=H(d,{taskContext:b}),I=C(await this.config.summarize(d,_)),w=ue(ce(d,I,this.config.estimateTokens,l)),A=[...c,w,...m],O=Date.now()-o,x=A.reduce((g,R)=>g+this.config.estimateTokens(R),0);return{messages:A,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:p,tokensAfter:x,compressionRatio:p>0?x/p:1,latencyMs:O,usedLlm:!0,cacheInvalidated:!0}}}},G=class{config;constructor(t){this.config=t}compress(t,n){let o=S(t),r=this.config.inner.compress(t,n),i=S(r.messages),s=o!==i&&r.droppedCount>0;return s&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:s}}}async compressAsync(t,n){let o=S(t),r=q(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),i=S(r.messages),s=o!==i&&r.droppedCount>0;return s&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:s}}}},pe={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function ot(e={}){let t={...pe,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function rt(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var $=class{events=[];maxEvents;constructor(t=100){this.maxEvents=t}record(t){this.events.push(t),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let t=this.events.length;if(t===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let n=0,o=0,r=0,i=0,s=0;for(let a of this.events)n+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,o+=a.latencyMs,r+=Math.max(0,a.tokensBefore-a.tokensAfter),a.usedLlm&&i++,a.cacheInvalidated&&s++;return{totalCompressions:t,totalLlmCalls:i,totalCacheInvalidations:s,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},j=class{engines=new Map;activeId;register(t){this.engines.set(t.id,t)}activate(t){return this.engines.has(t)?(this.activeId=t,!0):!1}getActive(){return this.activeId?this.engines.get(this.activeId):void 0}listEngines(){return Array.from(this.engines.values()).map(t=>({id:t.id,label:t.label,active:t.id===this.activeId}))}};function de(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function M(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function S(e){let t=Math.min(e.length,5),n=[];for(let o=0;o<t;o++){let r=e[o],i=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${i}`)}return n.join("|")}var st=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),z=class{constructor(t=20,n=M){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=new Map;for(let l of t){let c=l.tool_calls;if(Array.isArray(c))for(let u of c)u?.id&&u.function?.name&&o.set(u.id,u.function.name)}let r=t.length-this.preserveRecentCount,i=0,s=0;return{messages:t.map((l,c)=>{if(c>=r||l.role!=="tool"||typeof l.content!="string")return l;let u=l.name??o.get(l.tool_call_id??"");if(!u||!st.has(u)||l.content.length<=200)return l;let p=this.estimateTokens(l);return s+=p,i++,{...l,content:`[result cleared \u2014 ${l.content.length} chars]`}}),droppedCount:i,strategy:"micro-compact",metrics:i>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function it(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let i=r.function?.name??"";if(/read|edit|write|file/i.test(i)&&r.function?.arguments)try{let s=JSON.parse(r.function.arguments),a=s.path??s.filePath??s.file_path??s.file;a&&typeof a=="string"&&t.set(a,n)}catch{}}o.role==="tool"&&o.name&&/read|edit|write|file/i.test(o.name)}return[...t.entries()].sort((n,o)=>o[1]-n[1]).map(([n])=>n)}async function at(e,t,n){let o=n.estimateTokens??(d=>Math.ceil(d.length/4)),r=it(t);if(r.length===0)return e;let i=e.map(d=>typeof d.content=="string"?d.content:"").join(`
17
+ `),s=r.filter(d=>!i.includes(d));if(s.length===0)return e;let a=n.maxTokenBudget,l=[],c=0;for(let d of s){if(c>=n.maxFiles||a<=0)break;let m=await n.readFile(d);if(!m)continue;let b=o(m);b>a||(a-=b,c++,l.push({role:"system",content:`[Post-compact file recovery: ${d}]
18
18
 
19
- ${m}`}))}if(l.length===0)return e;let u=[...e],p=-1;for(let d=0;d<u.length;d++)u[d].role==="system"&&(p=d);return u.splice(p+1,0,...l),u}function lt(e,t,n=M){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let a of e){let l=a.tool_call_id??"";if(l&&t.has(l)){o+=n(a),r++,t.delete(l);continue}i.push(a)}let s=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:s}}function ct(){return{stages:[]}}function ut(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=me(e,t),s=dt(i,t,o);if(s.length===0)return{messages:i,stagedCount:0};for(let a of s)t.stages.push(a);return i=me(e,t),{messages:i,stagedCount:s.length}}function pt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:fe(e,t),committed:n}}function me(e,t){return t.stages.filter(o=>o.committed).length===0?e:fe(e,t)}function fe(e,t){let n=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),o=[...e];for(let r of n){let[i,s]=r.range;if(i>=o.length)continue;let a=Math.min(s,o.length),l={role:"system",content:r.summary};o.splice(i,a-i,l)}return o}function dt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),s=-1,a=0;for(let l=0;l<o;l++){let c=e[l];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")s<0&&(s=l),a++;else{if(a>=3){let p=`${s}-${s+a}`;i.has(p)||r.push({id:`collapse_${s}_${s+a}`,range:[s,s+a],summary:`[${a} tool results collapsed]`,committed:!1})}s=-1,a=0}}if(a>=3){let l=`${s}-${s+a}`;i.has(l)||r.push({id:`collapse_${s}_${s+a}`,range:[s,s+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}function mt(e){return[...new Set(e.map(I).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function ge(e){let t=mt(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not invent or attempt any tool outside this list. If the request needs a capability none of these tools cover, do not silently refuse: consider exec-based scripts/OS commands, and otherwise state plainly which capability is missing.`}function ft(e){let t=[...new Set(e.map(I).filter(Boolean))].sort((s,a)=>s.localeCompare(a)),n=new Set(t),o=ge(e),r=n.has("exec"),i=["read","search","write","edit","patch"].some(s=>n.has(s));return!r||!i?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function I(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function gt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function yt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Tt(e){if(!e.eligibility?.length)return[...e.tools];let t=yt(e.eligibility);return e.tools.filter(n=>{let o=I(n);if(!o)return!1;let r=t.get(o);return!r||gt(r.status)})}function ht(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function Ct(e){let t=ht({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Tt({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:ge(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:ft(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,s=typeof i?.name=="string"?i.name.trim():"";if(!s)throw new Error("tool_choice.function.name is required");let a=r.filter(l=>I(l)===s);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${s}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:s}},extraSystemPrompt:`You must call the ${s} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var _t=["stop","aborted","timeout","cancelled","interrupted","error"],bt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function ye(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Rt(e,t){return{...e,content:[...ye(e.content),...ye(t.content)]}}function xt(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function At(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let i=xt(r);if(i.size!==0)for(let s=o+1;s<e.length;s+=1){if(t.has(s))continue;let a=e[s];a?.role==="tool"&&typeof a.tool_call_id=="string"&&i.has(a.tool_call_id)&&(n.push(a),t.add(s))}}return n}function St(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function kt(e){return new Set((e??_t).map(t=>t.trim().toLowerCase()))}function Te(e,t){return e?kt(t).has(e.trim().toLowerCase()):!1}function Et(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function Y(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(l=>{if(l.role==="assistant"&&Array.isArray(l.tool_calls)){let c=l.tool_calls.filter(u=>St(u));return{...l,...c.length>0?{tool_calls:c}:{tool_calls:void 0}}}return{...l}}),n=new Set;for(let l of t)if(!(l.role!=="assistant"||!Array.isArray(l.tool_calls)))for(let c of l.tool_calls)typeof c.id=="string"&&c.id&&n.add(c.id);let o=t.filter(l=>l.role!=="tool"?!0:!!(l.tool_call_id&&n.has(l.tool_call_id))),r=new Set;for(let l of o)l.role==="tool"&&typeof l.tool_call_id=="string"&&l.tool_call_id&&r.add(l.tool_call_id);let i=[];for(let l of o){if(l.role==="assistant"&&Array.isArray(l.tool_calls)&&l.tool_calls.length>0){let c=l.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(c.length===0){let{tool_calls:u,...p}=l;p.content!=null&&p.content!==""&&i.push(p);continue}if(c.length<l.tool_calls.length){i.push({...l,tool_calls:c});continue}}i.push(l)}let s=At(i),a=[];for(let l of s){let c=a.length>0?a[a.length-1]:void 0;if(l.role==="user"&&c?.role==="user"){a[a.length-1]=Rt(c,l);continue}a.push(l)}return a}function X(e,t){return Te(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of bt)delete o[r];return o}):[...e]}function W(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&o.add(i.tool_call_id);let r=[];for(let i of e)if(r.push({...i}),!(i.role!=="assistant"||!Array.isArray(i.tool_calls)||i.tool_calls.length===0))for(let s of i.tool_calls)typeof s.id!="string"||!s.id||o.has(s.id)||(o.add(s.id),r.push({role:"tool",tool_call_id:s.id,content:n}));return r}function Mt(e,t){let n=Y(e),o=X(n,t);return W(o,t)}function he(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=Te(t?.stopReason,t?.forcedStopReasons),r=[];for(let c=0;c<e.length;c+=1){let u=e[c];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(c+1).some(m=>m&&typeof m=="object"&&m.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let p={...u};if(typeof p.id=="string"){let d=Et(p.id);d.itemId?.startsWith("fc_")&&(p.id=d.callId)}r.push(p)}let i=new Set,s=new Map;for(let c of r){if(c.type!=="function_call")continue;let u=typeof c.call_id=="string"&&c.call_id?c.call_id:typeof c.id=="string"?c.id:void 0;u&&(i.add(u),s.set(u,c))}let a=new Set,l=[];for(let c of r)if(!(o&&c.type==="function_call")){if(c.type==="function_call_output"){let u=typeof c.call_id=="string"?c.call_id:"";if(!u||!i.has(u))continue;a.add(u)}l.push(c)}for(let[c]of s)a.has(c)||o||l.push({type:"function_call_output",call_id:c,output:n});return l}function It(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function vt(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function wt(e){let t=new Set,n=new Set;for(let o of e){if(o.type==="function_call"){let r=typeof o.call_id=="string"&&o.call_id?o.call_id:typeof o.id=="string"?o.id:"";r&&t.add(r)}o.type==="function_call_output"&&typeof o.call_id=="string"&&o.call_id&&n.add(o.call_id)}return[...t].filter(o=>!n.has(o))}function Ot(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function Ce(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Lt(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Pt(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Nt(e){let t=[],n=Y(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=X(n,e.options);o.some((i,s)=>i!==n[s])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=W(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Ce({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:It(r),completedToolCallIds:vt(r)}),recoveryActions:t}}function Dt(e){let t=he(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:Ce({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:wt(t),completedToolCallIds:Ot(t)}),recoveryActions:n}}var Ft=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Bt(e){return e?Ft.has(e):!0}function Ut(e){return e===429||e===529}function Gt(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var Mn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function $t(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var K=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var vn=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),wn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var On=720*60*60*1e3,V=4;var Ln=3600*1e3;var Pn=50*1024,Nn=500*1024,Dn=500*1024*1024,Fn=50*1024*1024;var Bn=60*1024;var J="<fork-child-context>",_e="Fork started \u2014 processing in background";function jt(e){return JSON.stringify(e).includes(J)}function zt(e){return e<V}function qt(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
19
+ ${m}`}))}if(l.length===0)return e;let u=[...e],p=-1;for(let d=0;d<u.length;d++)u[d].role==="system"&&(p=d);return u.splice(p+1,0,...l),u}function lt(e,t,n=M){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let a of e){let l=a.tool_call_id??"";if(l&&t.has(l)){o+=n(a),r++,t.delete(l);continue}i.push(a)}let s=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:s}}function ct(){return{stages:[]}}function ut(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=me(e,t),s=dt(i,t,o);if(s.length===0)return{messages:i,stagedCount:0};for(let a of s)t.stages.push(a);return i=me(e,t),{messages:i,stagedCount:s.length}}function pt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:fe(e,t),committed:n}}function me(e,t){return t.stages.filter(o=>o.committed).length===0?e:fe(e,t)}function fe(e,t){let n=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),o=[...e];for(let r of n){let[i,s]=r.range;if(i>=o.length)continue;let a=Math.min(s,o.length),l={role:"system",content:r.summary};o.splice(i,a-i,l)}return o}function dt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),s=-1,a=0;for(let l=0;l<o;l++){let c=e[l];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")s<0&&(s=l),a++;else{if(a>=3){let p=`${s}-${s+a}`;i.has(p)||r.push({id:`collapse_${s}_${s+a}`,range:[s,s+a],summary:`[${a} tool results collapsed]`,committed:!1})}s=-1,a=0}}if(a>=3){let l=`${s}-${s+a}`;i.has(l)||r.push({id:`collapse_${s}_${s+a}`,range:[s,s+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}function mt(e){return[...new Set(e.map(v).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function ge(e){let t=mt(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not invent or attempt any tool outside this list. If the request needs a capability none of these tools cover, do not silently refuse: consider exec-based scripts/OS commands, and otherwise state plainly which capability is missing.`}function ft(e){let t=[...new Set(e.map(v).filter(Boolean))].sort((s,a)=>s.localeCompare(a)),n=new Set(t),o=ge(e),r=n.has("exec"),i=["read","search","write","edit","patch"].some(s=>n.has(s));return!r||!i?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function v(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function gt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function yt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function ht(e){if(!e.eligibility?.length)return[...e.tools];let t=yt(e.eligibility);return e.tools.filter(n=>{let o=v(n);if(!o)return!1;let r=t.get(o);return!r||gt(r.status)})}function Tt(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function Ct(e){let t=Tt({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=ht({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:ge(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:ft(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,s=typeof i?.name=="string"?i.name.trim():"";if(!s)throw new Error("tool_choice.function.name is required");let a=r.filter(l=>v(l)===s);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${s}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:s}},extraSystemPrompt:`You must call the ${s} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var bt=["stop","aborted","timeout","cancelled","interrupted","error"],_t=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function ye(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Rt(e,t){return{...e,content:[...ye(e.content),...ye(t.content)]}}function xt(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function kt(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let i=xt(r);if(i.size!==0)for(let s=o+1;s<e.length;s+=1){if(t.has(s))continue;let a=e[s];a?.role==="tool"&&typeof a.tool_call_id=="string"&&i.has(a.tool_call_id)&&(n.push(a),t.add(s))}}return n}function At(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function St(e){return new Set((e??bt).map(t=>t.trim().toLowerCase()))}function he(e,t){return e?St(t).has(e.trim().toLowerCase()):!1}function Et(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function Y(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(l=>{if(l.role==="assistant"&&Array.isArray(l.tool_calls)){let c=l.tool_calls.filter(u=>At(u));return{...l,...c.length>0?{tool_calls:c}:{tool_calls:void 0}}}return{...l}}),n=new Set;for(let l of t)if(!(l.role!=="assistant"||!Array.isArray(l.tool_calls)))for(let c of l.tool_calls)typeof c.id=="string"&&c.id&&n.add(c.id);let o=t.filter(l=>l.role!=="tool"?!0:!!(l.tool_call_id&&n.has(l.tool_call_id))),r=new Set;for(let l of o)l.role==="tool"&&typeof l.tool_call_id=="string"&&l.tool_call_id&&r.add(l.tool_call_id);let i=[];for(let l of o){if(l.role==="assistant"&&Array.isArray(l.tool_calls)&&l.tool_calls.length>0){let c=l.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(c.length===0){let{tool_calls:u,...p}=l;p.content!=null&&p.content!==""&&i.push(p);continue}if(c.length<l.tool_calls.length){i.push({...l,tool_calls:c});continue}}i.push(l)}let s=kt(i),a=[];for(let l of s){let c=a.length>0?a[a.length-1]:void 0;if(l.role==="user"&&c?.role==="user"){a[a.length-1]=Rt(c,l);continue}a.push(l)}return a}function W(e,t){return he(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of _t)delete o[r];return o}):[...e]}function X(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&o.add(i.tool_call_id);let r=[];for(let i of e)if(r.push({...i}),!(i.role!=="assistant"||!Array.isArray(i.tool_calls)||i.tool_calls.length===0))for(let s of i.tool_calls)typeof s.id!="string"||!s.id||o.has(s.id)||(o.add(s.id),r.push({role:"tool",tool_call_id:s.id,content:n}));return r}function Mt(e,t){let n=Y(e),o=W(n,t);return X(o,t)}function Te(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=he(t?.stopReason,t?.forcedStopReasons),r=[];for(let c=0;c<e.length;c+=1){let u=e[c];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(c+1).some(m=>m&&typeof m=="object"&&m.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let p={...u};if(typeof p.id=="string"){let d=Et(p.id);d.itemId?.startsWith("fc_")&&(p.id=d.callId)}r.push(p)}let i=new Set,s=new Map;for(let c of r){if(c.type!=="function_call")continue;let u=typeof c.call_id=="string"&&c.call_id?c.call_id:typeof c.id=="string"?c.id:void 0;u&&(i.add(u),s.set(u,c))}let a=new Set,l=[];for(let c of r)if(!(o&&c.type==="function_call")){if(c.type==="function_call_output"){let u=typeof c.call_id=="string"?c.call_id:"";if(!u||!i.has(u))continue;a.add(u)}l.push(c)}for(let[c]of s)a.has(c)||o||l.push({type:"function_call_output",call_id:c,output:n});return l}function vt(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function It(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function wt(e){let t=new Set,n=new Set;for(let o of e){if(o.type==="function_call"){let r=typeof o.call_id=="string"&&o.call_id?o.call_id:typeof o.id=="string"?o.id:"";r&&t.add(r)}o.type==="function_call_output"&&typeof o.call_id=="string"&&o.call_id&&n.add(o.call_id)}return[...t].filter(o=>!n.has(o))}function Ot(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function Ce(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Lt(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Pt(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Nt(e){let t=[],n=Y(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=W(n,e.options);o.some((i,s)=>i!==n[s])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=X(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Ce({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:vt(r),completedToolCallIds:It(r)}),recoveryActions:t}}function Ft(e){let t=Te(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:Ce({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:wt(t),completedToolCallIds:Ot(t)}),recoveryActions:n}}var Dt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Bt(e){return e?Dt.has(e):!0}function Ut(e){return e===429||e===529}function Gt(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var Mn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function $t(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var K=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var In=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),wn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var V=4;var On=50*1024,Ln=500*1024,Pn=500*1024*1024,Nn=50*1024*1024;var J="<fork-child-context>",be="Fork started \u2014 processing in background";function jt(e){return JSON.stringify(e).includes(J)}function zt(e){return e<V}function qt(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
20
20
 
21
21
  Your working directory is: ${e.worktreePath}
22
22
  All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${J}
23
23
 
24
24
  You are the "${t.agent.name}" agent.${o}
25
25
 
26
- ${t.taskPrompt}`}]};return n.push(r),n}function Ht(e){return e.map(t=>({role:"tool",tool_call_id:t,content:_e}))}function Yt(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolCapabilityProfile==="no_tools")return[];if(t.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent")}function Xt(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var Wt={name:"general",label:"General Purpose",description:"A general-purpose sub-agent that can perform any task with full tool access.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!1},Kt={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolCapabilityProfile:"read_tools",allowedTools:["read","search","web_search","web_fetch","memory"],canFork:!1,systemPromptSuffix:"You are READ-ONLY: never attempt to modify files or run mutating commands. Locate and understand code, then report concrete findings with file:line references. Read excerpts rather than whole files; surface conclusions, not raw dumps."},Vt={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolCapabilityProfile:"read_tools",allowedTools:["read","search","web_search","web_fetch","memory","task"],canFork:!1,systemPromptSuffix:"You PLAN but do not execute: never write files or run commands. Investigate enough to ground the plan in the real code, then return a concrete, step-by-step implementation plan naming the specific files and changes involved."},Jt={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!0,systemPromptSuffix:"Implement the task directly by editing files. Read existing code before changing it, match the surrounding conventions, and verify your change compiles/passes where possible."},Zt={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolCapabilityProfile:"read_tools",allowedTools:["web_search","web_fetch","read","search","memory"],canFork:!1,systemPromptSuffix:"Gather information from multiple sources before concluding. Distinguish facts from inferences, cite where each claim comes from, and synthesize \u2014 do not just dump search results."},Qt={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolCapabilityProfile:"all_tools",allowedTools:["exec","read","search","task"],canFork:!1,systemPromptSuffix:"Verify by RUNNING things (tests, builds, type-checks) and reading the actual output \u2014 do not assume. Report a clear verdict (pass/fail) with the evidence that supports it."},Z=[Wt,Kt,Vt,Jt,Zt,Qt];function en(){return[...Z]}function tn(e){return Z.find(t=>t.name===e)}function nn(e){return Z.some(t=>t.name===e)}function on(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolCapabilityProfile==="no_tools")return[];if(e.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(o=>!n.has(o))}return e.canFork?[...t]:t.filter(n=>n!=="agent")}function rn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function sn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function an(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function ln(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function cn(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function un(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}function pn(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
26
+ ${t.taskPrompt}`}]};return n.push(r),n}function Ht(e){return e.map(t=>({role:"tool",tool_call_id:t,content:be}))}function Yt(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolCapabilityProfile==="no_tools")return[];if(t.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent")}function Wt(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var Xt={name:"general",label:"General Purpose",description:"A general-purpose sub-agent that can perform any task with full tool access.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!1},Kt={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolCapabilityProfile:"read_tools",allowedTools:["read","search","web_search","web_fetch","memory"],canFork:!1,systemPromptSuffix:"You are READ-ONLY: never attempt to modify files or run mutating commands. Locate and understand code, then report concrete findings with file:line references. Read excerpts rather than whole files; surface conclusions, not raw dumps."},Vt={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolCapabilityProfile:"read_tools",allowedTools:["read","search","web_search","web_fetch","memory","task"],canFork:!1,systemPromptSuffix:"You PLAN but do not execute: never write files or run commands. Investigate enough to ground the plan in the real code, then return a concrete, step-by-step implementation plan naming the specific files and changes involved."},Jt={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!0,systemPromptSuffix:"Implement the task directly by editing files. Read existing code before changing it, match the surrounding conventions, and verify your change compiles/passes where possible."},Zt={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolCapabilityProfile:"read_tools",allowedTools:["web_search","web_fetch","read","search","memory"],canFork:!1,systemPromptSuffix:"Gather information from multiple sources before concluding. Distinguish facts from inferences, cite where each claim comes from, and synthesize \u2014 do not just dump search results."},Qt={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolCapabilityProfile:"all_tools",allowedTools:["exec","read","search","task"],canFork:!1,systemPromptSuffix:"Verify by RUNNING things (tests, builds, type-checks) and reading the actual output \u2014 do not assume. Report a clear verdict (pass/fail) with the evidence that supports it."},Z=[Xt,Kt,Vt,Jt,Zt,Qt];function en(){return[...Z]}function tn(e){return Z.find(t=>t.name===e)}function nn(e){return Z.some(t=>t.name===e)}function on(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolCapabilityProfile==="no_tools")return[];if(e.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(o=>!n.has(o))}return e.canFork?[...t]:t.filter(n=>n!=="agent")}function rn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function sn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function an(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function ln(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function cn(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function un(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}function pn(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
27
27
  ${n.join(`
28
28
  `)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
29
29
  Step ${e.activeSkillContext.step}:
@@ -34,4 +34,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
34
34
 
35
35
  ${t.join(`
36
36
 
37
- `)}`}function dn(){return{attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function mn(e){return!e.attemptedThisTurn}export{E as CONTEXT_CAPSULE_MARKER,G as CacheAwareCompressionStrategy,$ as CompressionMetricsCollector,j as ContextEngineRegistry,pe as DEFAULT_ADAPTIVE_BUDGET_CONFIG,_e as FORK_PLACEHOLDER_RESULT,J as FORK_SENTINEL_TAG,K as FallbackTriggeredError,B as HeadTailProtectedStrategy,U as IncrementalCompactStrategy,V as MAX_FORK_DEPTH,z as MicroCompactStrategy,N as SlidingWindowStrategy,D as SummarizeOldStrategy,F as ToolResultTrimStrategy,Lt as advanceToolLoopState,ut as applyContextCollapsesIfNeeded,Ct as applyToolChoicePolicy,be as buildAssistantToolCallMessage,Ht as buildForkPlaceholderResults,qt as buildForkedMessages,pn as buildPostCompactRestorationMessage,H as buildStructuredSummaryPrompt,Re as buildToolResultMessage,an as calculateTokenWarningState,zt as canForkAtDepth,Ze as classifyError,nt as composeAsyncStrategies,tt as composeStrategies,ot as computeAdaptiveBudget,Gt as computeRetryBackoff,ct as createCollapseStore,dn as createReactiveCompactState,rn as createTaskState,sn as createTurnLoopGuardState,Xt as generateForkChildAgentId,tn as getBuiltInAgent,en as getBuiltInAgents,q as isAsyncCompressionStrategy,nn as isBuiltInAgent,Bt as isForegroundSource,jt as isInForkChild,$t as isPersistentRetryEnabled,ie as isRetryableCategory,Ut as isTransientCapacityError,A as parseContextCapsule,at as postCompactFileRecovery,pt as recoverContextCollapseFromOverflow,Nt as recoverToolLoopStateFromChatConversation,Dt as recoverToolLoopStateFromResponsesItems,C as redactCompressionSecrets,Mt as repairOpenAiChatConversation,on as resolveAgentToolSet,ln as resolveApiErrorRecovery,Yt as resolveForkChildTools,cn as resolveOutputTokenEscalation,rt as selectCompressionTier,Pt as settleToolLoopState,un as shouldAbortTurn,mn as shouldAttemptReactiveCompact,lt as snipCompactIfNeeded};
37
+ `)}`}function dn(){return{attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function mn(e){return!e.attemptedThisTurn}export{E as CONTEXT_CAPSULE_MARKER,G as CacheAwareCompressionStrategy,$ as CompressionMetricsCollector,j as ContextEngineRegistry,pe as DEFAULT_ADAPTIVE_BUDGET_CONFIG,be as FORK_PLACEHOLDER_RESULT,J as FORK_SENTINEL_TAG,K as FallbackTriggeredError,B as HeadTailProtectedStrategy,U as IncrementalCompactStrategy,V as MAX_FORK_DEPTH,z as MicroCompactStrategy,N as SlidingWindowStrategy,F as SummarizeOldStrategy,D as ToolResultTrimStrategy,Lt as advanceToolLoopState,ut as applyContextCollapsesIfNeeded,Ct as applyToolChoicePolicy,_e as buildAssistantToolCallMessage,Ht as buildForkPlaceholderResults,qt as buildForkedMessages,pn as buildPostCompactRestorationMessage,H as buildStructuredSummaryPrompt,Re as buildToolResultMessage,an as calculateTokenWarningState,zt as canForkAtDepth,Ze as classifyError,nt as composeAsyncStrategies,tt as composeStrategies,ot as computeAdaptiveBudget,Gt as computeRetryBackoff,ct as createCollapseStore,dn as createReactiveCompactState,rn as createTaskState,sn as createTurnLoopGuardState,Wt as generateForkChildAgentId,tn as getBuiltInAgent,en as getBuiltInAgents,q as isAsyncCompressionStrategy,nn as isBuiltInAgent,Bt as isForegroundSource,jt as isInForkChild,$t as isPersistentRetryEnabled,ie as isRetryableCategory,Ut as isTransientCapacityError,k as parseContextCapsule,at as postCompactFileRecovery,pt as recoverContextCollapseFromOverflow,Nt as recoverToolLoopStateFromChatConversation,Ft as recoverToolLoopStateFromResponsesItems,C as redactCompressionSecrets,Mt as repairOpenAiChatConversation,on as resolveAgentToolSet,ln as resolveApiErrorRecovery,Yt as resolveForkChildTools,cn as resolveOutputTokenEscalation,rt as selectCompressionTier,Pt as settleToolLoopState,un as shouldAbortTurn,mn as shouldAttemptReactiveCompact,lt as snipCompactIfNeeded};
@@ -4,9 +4,7 @@
4
4
  * Mutable runtime state owned by agent-internal logic should live here. This avoids
5
5
  * scattering mutable state as private fields across stdio-server.ts.
6
6
  *
7
- * Categories:
8
- * 1. Budget — aggregate token usage tracking and limits
9
- * 2. Dream — idle dream scheduling parameters
7
+ * Tracks aggregate sub-agent token usage and limits.
10
8
  *
11
9
  * Usage:
12
10
  * import { runtimeVars } from "../agent/runtime-vars.js";
@@ -19,18 +17,6 @@ export interface TeamBudgetState {
19
17
  /** Maximum total tokens allowed across all forks. 0 = unlimited. */
20
18
  budgetTokens: number;
21
19
  }
22
- export interface DreamState {
23
- /** Idle threshold before triggering dream (minutes). */
24
- idleMinutes: number;
25
- /** Whether idle dream is enabled. */
26
- enabled: boolean;
27
- /** Last dream timestamp (ms since epoch). */
28
- lastDreamAt: number;
29
- /** Cooldown between dreams (ms). */
30
- cooldownMs: number;
31
- /** Max duration for a single dream run (ms). */
32
- maxDurationMs: number;
33
- }
34
20
  export declare class RuntimeVars {
35
21
  readonly teamBudget: TeamBudgetState;
36
22
  /** Check if team aggregate budget is exceeded. */
@@ -39,7 +25,6 @@ export declare class RuntimeVars {
39
25
  recordForkTokens(tokens: number): number;
40
26
  /** Format budget-exceeded error message. */
41
27
  teamBudgetExceededError(): string;
42
- readonly dream: DreamState;
43
28
  /** Reset all accumulated state (e.g. on session end). */
44
29
  resetAccumulators(): void;
45
30
  }
@@ -30,8 +30,6 @@ export interface CompressionPipelineDeps {
30
30
  turnId: string;
31
31
  };
32
32
  sessionId: string;
33
- /** Turn workspace/cwd — routes oversized tool-result spillover to the session's reachable data dir. */
34
- projectRoot: string | undefined;
35
33
  currentModel: string;
36
34
  log: AgentLogger;
37
35
  /** Build + record a recovery event (centralized in the loop's recovery trace). */
@@ -94,12 +94,6 @@ export interface ToolLoopParams {
94
94
  * Mutates in place; called before each tool result enters the model context.
95
95
  */
96
96
  sanitizeToolResultMedia?: (message: Record<string, unknown>) => Promise<void>;
97
- /**
98
- * Persist a model-visible tool-stream message (assistant tool_calls / role:"tool" result) to the
99
- * transcript. Fired by pushTranscriptMessage for EVERY such push. Host must synchronously clone
100
- * before enqueueing. Keeps src/agent/** I/O-free.
101
- */
102
- persistTurnMessage?: (message: ChatMessage) => void;
103
97
  /**
104
98
  * Post-sampling hooks -fire-and-forget after LLM response completes (CC executePostSamplingHooks parity).
105
99
  * Cannot modify messages. Used for background tasks (memory extraction, skill learning, etc.).
@@ -7,7 +7,8 @@
7
7
  */
8
8
  import type { HookRegistry } from "../contracts/hooks.js";
9
9
  import type { AccumulatedToolCall, LLMChunk, LLMRequest, LLMTransport } from "../runtime/ports/index.js";
10
- import type { ChatMessage as WireChatMessage, ChatMessageRole as WireChatMessageRole, ThinkingBlock as WireThinkingBlock, ToolCallMessage as WireToolCallMessage, ToolDefinition as WireToolDefinition, WireTokenUsage, FinalAnswerEvidence as WireFinalAnswerEvidence, ToolCallExecutionEvidence as WireToolCallExecutionEvidence } from "../protocol/wire/index.js";
10
+ import type { ChatMessage as WireChatMessage, ChatMessageRole as WireChatMessageRole, ThinkingBlock as WireThinkingBlock, ToolCallMessage as WireToolCallMessage, ToolDefinition as WireToolDefinition, WireTokenUsage } from "../protocol/wire/index.js";
11
+ import type { FinalAnswerEvidence, ToolCallExecutionEvidence } from "../contracts/tool-execution-evidence.js";
11
12
  export type ChatMessageRole = WireChatMessageRole;
12
13
  export type ThinkingBlock = WireThinkingBlock;
13
14
  export type ToolCallMessage = WireToolCallMessage;
@@ -74,27 +75,10 @@ export type ToolLoopTerminal = {
74
75
  } | {
75
76
  reason: "hook_stopped";
76
77
  };
77
- /**
78
- * 提前发起的长期记忆召回。
79
- *
80
- * 召回实测每轮 1.5 秒,而它只依赖"最后一条用户消息",不依赖 MCP 就绪、工具清单或系统提示组装。
81
- * 由 turn-handler 在这些前置工作**之前**发起,回合因此少串行等待一次召回。
82
- *
83
- * query 必须随 promise 一起带出:召回是有副作用的(before/after_recall 钩子、每轮字节预算、
84
- * surfacedPaths 去重、召回决策账本),不能"查询串不符就再跑一次"—— 那会二次消耗预算并使
85
- * 结果依赖执行顺序。消费端只做校验,不做补救。
86
- */
87
- export interface MemoryRecallPrefetch {
88
- /** 发起预取时使用的查询串,供消费端断言与最终查询串一致。 */
89
- query: string;
90
- promise: Promise<string | null>;
91
- }
92
78
  export interface TurnRequest {
93
79
  turnId: string;
94
80
  sessionId: string;
95
81
  messages: ChatMessage[];
96
- /** 见 MemoryRecallPrefetch。缺省时 Agent 自行同步召回(旧路径,语义不变)。 */
97
- memoryRecallPrefetch?: MemoryRecallPrefetch;
98
82
  /** Full registered tool surface before per-turn policy filtering. */
99
83
  availableTools?: ToolDefinition[];
100
84
  /** Exact tool names whose full parameter schemas are loaded only after Agent selection. */
@@ -129,8 +113,6 @@ export interface TurnRequest {
129
113
  * and drops the raw media. Forwarded to the tool loop; mutates the message in place.
130
114
  */
131
115
  sanitizeToolResultMedia?: (message: Record<string, unknown>) => Promise<void>;
132
- /** Persist each model-visible tool-stream message to the transcript — forwarded to the tool loop. */
133
- persistTurnMessage?: (message: ChatMessage) => void;
134
116
  systemPrompt?: string;
135
117
  config?: TurnConfig;
136
118
  }
@@ -200,8 +182,7 @@ export interface TurnConfig {
200
182
  /** MCP server configurations (stdio/sse/http). Passed from host to agent per-turn. */
201
183
  mcpServers?: Record<string, unknown>;
202
184
  }
203
- export type FinalAnswerEvidence = WireFinalAnswerEvidence;
204
- export type ToolCallExecutionEvidence = WireToolCallExecutionEvidence;
185
+ export type { FinalAnswerEvidence, ToolCallExecutionEvidence };
205
186
  /**
206
187
  * ToolInvoker: request tool execution from the host process (Gateway).
207
188
  * In CLI mode this sends a JSON-RPC notification over stdio and waits for result.
@@ -4,12 +4,11 @@
4
4
  * `buildAvailableCommands` (the list advertised via `available_commands_update` and summarized by
5
5
  * `/help`) and `dispatchSlashCommand` (execution) share one source of truth — `BUILTIN_COMMANDS`.
6
6
  * Each command's `dispatch` calls the same underlying data service the equivalent RPC handler uses
7
- * (model-registry / tool-catalog / Host Capability client / project-store / Host Provider directory / memory store) and
7
+ * (model-registry / tool-catalog) and
8
8
  * formats the result as a text reply. No half-wiring: a command is only listed if it can run.
9
9
  *
10
- * Command-set decision (per plan): 9 direct commands + `/init` (degraded to a prompt, no automatic
11
- * function). `/compact` is intentionally NOT registered context compaction is triggered
12
- * automatically by reactive-compact, so exposing it as an explicit command would be misleading.
10
+ * The adapter exposes only commands backed by its own current session state. `/init` degrades to
11
+ * a prompt, and `/compact` is intentionally not registered because compaction is automatic.
13
12
  * This codebase produces no user-invocable skill commands, so that enumeration is empty.
14
13
  */
15
14
  import type { AcpSessionHost } from "./acp-session-host.js";
@@ -26,6 +25,6 @@ export interface AcpCommandDef {
26
25
  export declare const BUILTIN_COMMANDS: AcpCommandDef[];
27
26
  export declare function buildAvailableCommands(host: AcpSessionHost): Array<{
28
27
  name: string;
29
- description?: string;
28
+ description: string;
30
29
  }>;
31
30
  export declare function dispatchSlashCommand(host: AcpSessionHost, text: string, args: string): Promise<AcpCommandReply>;
@@ -1,8 +1,7 @@
1
- export type IncomingRoute = "acp" | "legacy" | "ignore";
1
+ export type IncomingRoute = "acp" | "ignore";
2
2
  /**
3
3
  * Classify a parsed inbound frame.
4
4
  * - "acp" → hand to the ACP server (only when ACP is active)
5
- * - "legacy" → hand to the native gateway handler (a valid AgentRpcRequest)
6
5
  * - "ignore" → neither; drop with a warning
7
6
  */
8
7
  export declare function classifyIncomingMessage(parsed: unknown, acpActive: boolean): IncomingRoute;
@@ -1,24 +1,19 @@
1
1
  import type { AcpSessionHost } from "./acp-session-host.js";
2
2
  import { type AcpInitializeParams, type AcpInitializeResult, type AcpSessionCloseParams, type AcpSessionLoadParams, type AcpSessionMeta, type AcpSessionNewParams, type AcpSessionNewResult, type AcpSessionPromptParams, type AcpSessionPromptResult, type AcpSessionSetConfigParams, type AcpSessionSetConfigResult } from "../protocol/wire/index.js";
3
- export declare const ACP_TURN_HEARTBEAT_INTERVAL_MS = 10000;
4
3
  export type { AcpSessionHost };
5
4
  /**
6
- * Resolve the _meta a prompt must inherit: prefer the meta registered for THIS session (session/new)
7
- * over the per-connection singleton, so multiplexed sessions (desktop × WeChat on one connection)
8
- * never swap each other's config. Falls back to the legacy singleton for unregistered sessions
9
- * (old-gateway compat), then to an empty bag.
5
+ * Resolve only the metadata registered for this canonical ACP session. Unknown sessions have no inherited context.
10
6
  */
11
7
  export declare function resolveSessionMetaForPrompt(host: AcpSessionHost, sessionId: string): AcpSessionMeta;
12
8
  export declare function handleAcpInitialize(host: AcpSessionHost, params: AcpInitializeParams, packageVersion: string): Promise<AcpInitializeResult>;
13
9
  export declare function handleAcpSessionNew(host: AcpSessionHost, params: AcpSessionNewParams): Promise<AcpSessionNewResult>;
14
10
  /**
15
- * Standard ACP session/load: point the host at an existing session and return its persisted
16
- * history as display-only chunks for the server to replay. The backend turn context is NOT
17
- * rebuilt here every session/prompt hydrates history from disk via the turn pipeline's
18
- * withResumedHistory, so load only needs to (a) make this the active session and (b) hand back
19
- * the transcript for the host to render. Returns data only; the server owns the send path.
11
+ * Standard ACP session/load: select an existing native ACP identity and reset
12
+ * turn-local runtime state. A still-live process may replay its bounded in-memory
13
+ * projection; after restart the next session/prompt receives the authoritative
14
+ * Host history snapshot. The adapter never reads a parallel durable transcript.
20
15
  */
21
- export declare function handleAcpSessionLoad(host: AcpSessionHost, params: AcpSessionLoadParams): Promise<{
16
+ export declare function handleAcpSessionLoad(host: AcpSessionHost, params: AcpSessionLoadParams): Promise<AcpSessionNewResult & {
22
17
  replay: Array<{
23
18
  type: "user_message_chunk" | "agent_message_chunk";
24
19
  content: string;
@@ -38,7 +33,6 @@ export declare function tryDispatchCommand(host: AcpSessionHost, params: AcpSess
38
33
  export declare function handleAcpSessionPrompt(host: AcpSessionHost, params: AcpSessionPromptParams): Promise<AcpSessionPromptResult>;
39
34
  export declare function handleAcpSessionClose(host: AcpSessionHost, params: AcpSessionCloseParams): Promise<void>;
40
35
  export declare function handleAcpSessionSetConfig(host: AcpSessionHost, params: AcpSessionSetConfigParams): Promise<AcpSessionSetConfigResult>;
41
- export declare function handleAcpSessionSetModel(host: AcpSessionHost, _sessionId: string, model: string): Promise<void>;
42
36
  /**
43
37
  * Standard ACP session/set_mode: validate the requested permission mode and record it on the
44
38
  * session-level acpSessionMeta.permissions bag. The rule engine is NOT touched here — the next
@@ -1,52 +1,22 @@
1
1
  import type { HookRegistry } from "../contracts/hooks.js";
2
+ import type { NotificationMethod, NotificationMethodMap } from "../protocol/notifications.js";
2
3
  import type { AcpSessionMeta } from "../protocol/wire/index.js";
3
- import { createMemoryPrefetchState } from "../runtime/hooks/memory-hooks.js";
4
4
  import type { SessionState } from "../runtime/session/session-state.js";
5
- import type { SessionHistoryCoordinator } from "./session-history-coordinator.js";
6
- import type { HostCapabilityClient } from "../transport/host-capability-client.js";
7
- import type { HostAgentProviderDirectory } from "../runtime/infra/host-agent-provider-directory.js";
8
5
  /**
9
- * LLM config pinned on the session by the host (session/set_config_option /
10
- * session/set_model / the /model command). This is host-supplied INPUT — distinct
11
- * from the host's resolved-agent snapshot (stdio-server current*), which is
12
- * derived state and gets invalidated on every ModelRegistry change. Pinned config
13
- * must survive registry churn: a spawned team member is provisioned exactly this
14
- * way, and a background catalog hydration firing between the pin and the first
15
- * prompt must not wipe it (that wipe was the standalone NO_PROVIDER bug).
6
+ * Agent-native model choice for the current session. Host-managed model changes
7
+ * are immutable launch configuration and restart/resume the ordinary ACP adapter.
16
8
  */
17
9
  export interface SessionLlmConfig {
18
- provider?: string;
19
10
  model?: string;
20
- apiKey?: string;
21
- baseUrl?: string;
22
- }
23
- export interface MaterializedSessionBinding extends SessionLlmConfig {
24
- routing?: string;
25
- }
26
- /** Gateway-materialized session-private profile. apiKey exists in memory only. */
27
- export interface MaterializedSessionProfile {
28
- bindingRevision: string;
29
- bindings: Record<string, MaterializedSessionBinding>;
30
- permissions: Record<string, unknown>;
31
11
  }
32
12
  export interface AcpSessionHost {
33
- /** Gateway-supplied per-session context (_meta from session/new).
34
- * LEGACY fallback: a per-CONNECTION singleton overwritten by the last session/new — kept only
35
- * for old-gateway compat. Multiplexed connections must read via acpSessionMetaBySession instead. */
36
- acpSessionMeta: AcpSessionMeta | null;
37
13
  /** Per-session gateway _meta(session/new 注册;prompt 按 sessionId 取,消除跨会话串扰)。 */
38
14
  acpSessionMetaBySession: Map<string, AcpSessionMeta>;
39
- /** Legacy per-option pins, keyed by session (never a connection singleton). */
15
+ /** Agent-native model selections keyed by session. */
40
16
  sessionLlmConfigBySession: Map<string, SessionLlmConfig>;
41
- /** F2 full gateway profile, keyed by session; secrets are memory-only. */
42
- materializedSessionProfiles: Map<string, MaterializedSessionProfile>;
43
17
  currentHooks: HookRegistry | null;
44
18
  currentSessionId: string;
45
- memoryPrefetchState: ReturnType<typeof createMemoryPrefetchState>;
46
- sessionHistory: Pick<SessionHistoryCoordinator, "saveResumedSession" | "withResumedHistory">;
47
19
  sessionState: SessionState | null;
48
- cancelIdleDreamTimer(): void;
49
- disposeSessionRuntime?(): void;
50
20
  /** Retire only the named session's in-memory permission checker/rules/hooks. */
51
21
  disposeSessionPermissions?(sessionId: string): void;
52
22
  /** Dispose only the named canonical session's MCP manager and tool overlay. */
@@ -59,21 +29,8 @@ export interface AcpSessionHost {
59
29
  beginForegroundTurn?(): void;
60
30
  /** Release a foreground-priority reservation on every terminal path. */
61
31
  endForegroundTurn?(): void;
62
- enableIdleDream(): void;
63
- ensureDefaultProject(): void | Promise<void>;
64
- initializeHostProjectAuthority?(): Promise<void>;
65
- /**
66
- * Ensure the model-registry catalog (this.models) is hydrated from the owner profile +
67
- * built-in/llmrouter catalog. A spawned/headless qlogicagent only runs load() (bindings +
68
- * enabled-overrides) — its catalog is empty, so getActiveModel() returns null and the turn fails
69
- * "No LLM provider". Awaiting this before a turn resolves the model lets the agent self-resolve its
70
- * own configured model (idempotent; the promise is cached).
71
- */
72
- ensureModelRegistryHydrated?(): Promise<void>;
73
32
  getActiveProjectRoot(): string;
74
- getHostCapabilityClient?(): HostCapabilityClient | undefined;
75
- getHostAgentProviderDirectory?(): HostAgentProviderDirectory | undefined;
76
33
  log(message: string): void;
77
- sendNotification(method: string, params: Record<string, unknown>): void;
34
+ sendNotification<M extends NotificationMethod>(method: M, params: NotificationMethodMap[M]): void;
78
35
  setActiveWorkdir(dir: string): void;
79
36
  }
@@ -0,0 +1,14 @@
1
+ export declare const ADAPTER_PROVIDER_ENV = "QLOGIC_ADAPTER_PROVIDER";
2
+ export declare const ADAPTER_MODEL_ENV = "QLOGIC_ADAPTER_MODEL";
3
+ export declare const ADAPTER_API_KEY_ENV = "QLOGIC_ADAPTER_API_KEY";
4
+ export declare const ADAPTER_BASE_URL_ENV = "QLOGIC_ADAPTER_BASE_URL";
5
+ export interface AdapterLaunchLlmConfig {
6
+ provider: string;
7
+ model: string;
8
+ apiKey: string;
9
+ baseUrl?: string;
10
+ }
11
+ /** Immutable ACP adapter process configuration; never persisted by qlogicagent. */
12
+ export declare function readAdapterLaunchLlmConfig(env?: NodeJS.ProcessEnv): AdapterLaunchLlmConfig | undefined;
13
+ /** The spawning Host is the only provider/profile authority for this ordinary ACP adapter. */
14
+ export declare function requireAdapterLaunchLlmConfig(env?: NodeJS.ProcessEnv): AdapterLaunchLlmConfig;
@@ -1,18 +1,15 @@
1
1
  import type { AgentLogger, ToolInvoker } from "../agent/types.js";
2
2
  import type { HookRegistry } from "../contracts/hooks.js";
3
- import type { NotificationMethod, NotificationMethodMap } from "../protocol/notifications.js";
4
3
  import type { AcpPermissionRequestParams } from "../protocol/wire/index.js";
5
- import type { MemoryPrefetchState } from "../runtime/hooks/memory-hooks.js";
6
4
  import type { BackgroundTaskManager } from "../runtime/infra/background-tasks.js";
7
5
  import type { TaskStore } from "../runtime/infra/task-runtime.js";
8
- import type { MemoryDreamRuntimeProvider, MemoryHandlerProvider, PermissionMetadataResolver, PermissionRuleEnginePort, PathService, ProjectMemoryStore, ToolCatalog } from "../runtime/ports/index.js";
6
+ import type { PermissionMetadataResolver, PermissionRuleEnginePort, PathService, ToolCatalog } from "../runtime/ports/index.js";
9
7
  import type { McpManager } from "../skills/mcp/mcp-manager.js";
10
8
  import type { PluginLoader } from "../skills/plugins/plugin-loader.js";
11
9
  import type { CliAgentClient } from "./cli-agent-builder.js";
12
10
  import { type CliCoreToolHostDeps } from "./core-tool-coordinator.js";
13
11
  import { type PermissionBootstrapDeps } from "./permission-bootstrap.js";
14
12
  import type { RuntimePermissionRuleEngine } from "./permission-runtime-service.js";
15
- import type { LLMTransport } from "./provider-core-facade.js";
16
13
  import { type FileWatcher } from "./runtime-watcher-bootstrap.js";
17
14
  export type { FileWatcher };
18
15
  export interface AgentRuntimeBootstrapDeps {
@@ -25,18 +22,6 @@ export interface AgentRuntimeBootstrapDeps {
25
22
  projectRoot: string;
26
23
  pathService: PathService;
27
24
  getActiveWorkdir?: () => string;
28
- memdir: ProjectMemoryStore;
29
- getMemdir?: () => ProjectMemoryStore | null;
30
- currentUserId: string;
31
- memoryPrefetchState: MemoryPrefetchState;
32
- getLastUserMessage(): string | undefined;
33
- getLastAssistantMessage(): string | undefined;
34
- resolveSmallModelClient(): {
35
- transport: LLMTransport;
36
- apiKey: string;
37
- model: string;
38
- } | null;
39
- scheduleBackgroundMemoryWork(label: string, work: (signal: AbortSignal) => Promise<void>): Promise<boolean>;
40
25
  agentClient: CliAgentClient;
41
26
  toolCatalog: ToolCatalog;
42
27
  currentMcpManager: McpManager | null;
@@ -49,11 +34,8 @@ export interface AgentRuntimeBootstrapDeps {
49
34
  getPluginSkills(): ReturnType<PluginLoader["getPluginSkills"]>;
50
35
  getAcpPermissionSession(): {
51
36
  sessionId: string;
52
- requestPermission(params: AcpPermissionRequestParams): Promise<{
53
- optionId?: string;
54
- }>;
37
+ requestPermission(params: AcpPermissionRequestParams): Promise<import("../protocol/wire/index.js").AcpPermissionRequestResult>;
55
38
  } | undefined;
56
- sendNotification<M extends NotificationMethod>(method: M, params: NotificationMethodMap[M]): void;
57
39
  existingPermissionRuleEngine?: RuntimePermissionRuleEngine;
58
40
  resolveSandboxPermissionSnapshot?: PermissionBootstrapDeps["resolveSandboxPermissionSnapshot"];
59
41
  coreToolHost: CliCoreToolHostDeps;
@@ -63,9 +45,6 @@ export interface AgentRuntimeBootstrapDeps {
63
45
  }
64
46
  export interface AgentRuntimeBootstrapResult {
65
47
  hooks: HookRegistry;
66
- memoryHandlerProvider: MemoryHandlerProvider | null;
67
- memoryDreamProvider: MemoryDreamRuntimeProvider | null;
68
- memoryUserId: string;
69
48
  permissionChecker: PermissionMetadataResolver;
70
49
  permissionUnregister: () => void;
71
50
  ruleEngine: PermissionRuleEnginePort;