qlogicagent 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +24 -23
  2. package/dist/agent.js +13 -13
  3. package/dist/cli.js +210 -186
  4. package/dist/contracts.js +1 -1
  5. package/dist/index.js +381 -20
  6. package/dist/orchestration.js +14 -105
  7. package/dist/types/agent/agent.d.ts +1 -1
  8. package/dist/types/agent/constants.d.ts +2 -2
  9. package/dist/types/agent/tool-access.d.ts +30 -0
  10. package/dist/types/agent/tool-loop.d.ts +2 -4
  11. package/dist/types/agent/types.d.ts +1 -13
  12. package/dist/types/cli/main.d.ts +3 -3
  13. package/dist/types/cli/stdio-server.d.ts +29 -7
  14. package/dist/types/cli/tool-bootstrap.d.ts +24 -5
  15. package/dist/types/cli/transport.d.ts +40 -0
  16. package/dist/types/contracts/index.d.ts +0 -1
  17. package/dist/types/contracts/todo.d.ts +9 -0
  18. package/dist/types/index.d.ts +3 -0
  19. package/dist/types/llm/model-catalog.d.ts +1 -1
  20. package/dist/types/orchestration/index.d.ts +14 -112
  21. package/dist/types/orchestration/skill-improvement.d.ts +2 -2
  22. package/dist/types/orchestration/{fork-subagent.d.ts → subagent/fork-subagent.d.ts} +2 -4
  23. package/dist/types/runtime/execution/dream-agent.d.ts +1 -1
  24. package/dist/types/runtime/execution/forked-agent.d.ts +1 -3
  25. package/dist/types/runtime/hooks/context-compression.d.ts +1 -1
  26. package/dist/types/runtime/infra/agent-paths.d.ts +57 -0
  27. package/dist/types/runtime/infra/checkpoint-backend.d.ts +8 -0
  28. package/dist/types/runtime/infra/disk-storage.d.ts +36 -0
  29. package/dist/types/runtime/infra/file-watcher.d.ts +2 -2
  30. package/dist/types/runtime/infra/index.d.ts +2 -0
  31. package/dist/types/runtime/infra/secure-storage.d.ts +1 -1
  32. package/dist/types/runtime/infra/task-runtime.d.ts +1 -1
  33. package/dist/types/runtime/prompt/instruction-loader.d.ts +6 -6
  34. package/dist/types/runtime/session/session-memory.d.ts +0 -1
  35. package/dist/types/runtime/session/session-persistence.d.ts +1 -1
  36. package/dist/types/skills/index.d.ts +20 -26
  37. package/dist/types/skills/mcp/mcp-manager.d.ts +3 -4
  38. package/dist/types/skills/mcp/mcp-stdio-client.d.ts +1 -1
  39. package/dist/types/skills/{memory-store.d.ts → memory/memory-store.d.ts} +20 -0
  40. package/dist/types/skills/{memory-tool.d.ts → memory/memory-tool.d.ts} +20 -0
  41. package/dist/types/skills/permissions/hook-runner.d.ts +1 -1
  42. package/dist/types/skills/permissions/settings-watcher.d.ts +2 -2
  43. package/dist/types/skills/plugins/plugin-api.d.ts +1 -1
  44. package/dist/types/skills/plugins/plugin-loader.d.ts +1 -4
  45. package/dist/types/skills/plugins/plugin-marketplace.d.ts +1 -1
  46. package/dist/types/skills/portable-tool.d.ts +34 -1
  47. package/dist/types/skills/todo-tool.d.ts +51 -42
  48. package/dist/types/skills/tools/instructions-tool.d.ts +20 -58
  49. package/dist/types/skills/tools/skill-invoke-tool.d.ts +2 -2
  50. package/dist/types/skills/tools.d.ts +65 -0
  51. package/package.json +2 -2
  52. package/dist/types/contracts/skill-candidate.d.ts +0 -63
  53. package/dist/types/orchestration/curator-scheduler.d.ts +0 -119
  54. package/dist/types/orchestration/memory-provider.d.ts +0 -14
  55. package/dist/types/orchestration/skill-candidate.d.ts +0 -52
  56. package/dist/types/orchestration/skill-consolidation.d.ts +0 -123
  57. package/dist/types/orchestration/skill-similarity.d.ts +0 -98
  58. package/dist/types/orchestration/team-orchestration.d.ts +0 -195
  59. package/dist/types/orchestration/team-tool-loop-wiring.d.ts +0 -92
  60. package/dist/types/skills/memory-query-tool.d.ts +0 -43
  61. package/dist/types/skills/tool-registry.d.ts +0 -29
  62. package/dist/types/skills/tools/memory-tool.d.ts +0 -74
  63. package/dist/types/skills/tools/pdf-tool.d.ts +0 -66
  64. /package/dist/types/orchestration/{context-collapse.d.ts → context/context-collapse.d.ts} +0 -0
  65. /package/dist/types/orchestration/{context-compression.d.ts → context/context-compression.d.ts} +0 -0
  66. /package/dist/types/orchestration/{reactive-compact.d.ts → context/reactive-compact.d.ts} +0 -0
  67. /package/dist/types/orchestration/{turn-loop-guard.d.ts → context/turn-loop-guard.d.ts} +0 -0
  68. /package/dist/types/orchestration/{error-classification.d.ts → error-handling/error-classification.d.ts} +0 -0
  69. /package/dist/types/orchestration/{failover-classification.d.ts → error-handling/failover-classification.d.ts} +0 -0
  70. /package/dist/types/orchestration/{failover-error.d.ts → error-handling/failover-error.d.ts} +0 -0
  71. /package/dist/types/orchestration/{retry-loop.d.ts → error-handling/retry-loop.d.ts} +0 -0
  72. /package/dist/types/orchestration/{agent-registry.d.ts → subagent/agent-registry.d.ts} +0 -0
  73. /package/dist/types/orchestration/{task-types.d.ts → subagent/task-types.d.ts} +0 -0
  74. /package/dist/types/orchestration/{conversation-repair.d.ts → tool-loop/conversation-repair.d.ts} +0 -0
  75. /package/dist/types/orchestration/{tool-choice-policy.d.ts → tool-loop/tool-choice-policy.d.ts} +0 -0
  76. /package/dist/types/orchestration/{tool-loop-state.d.ts → tool-loop/tool-loop-state.d.ts} +0 -0
  77. /package/dist/types/orchestration/{tool-schema.d.ts → tool-loop/tool-schema.d.ts} +0 -0
  78. /package/dist/types/skills/{memory-extractor.d.ts → memory/memory-extractor.d.ts} +0 -0
  79. /package/dist/types/skills/{qmemory-adapter.d.ts → memory/qmemory-adapter.d.ts} +0 -0
  80. /package/dist/types/skills/{skill-frontmatter.d.ts → skill-system/skill-frontmatter.d.ts} +0 -0
  81. /package/dist/types/skills/{skill-guard.d.ts → skill-system/skill-guard.d.ts} +0 -0
  82. /package/dist/types/skills/{skill-loader.d.ts → skill-system/skill-loader.d.ts} +0 -0
  83. /package/dist/types/skills/{skill-source.d.ts → skill-system/skill-source.d.ts} +0 -0
  84. /package/dist/types/skills/{skill-types.d.ts → skill-system/skill-types.d.ts} +0 -0
package/README.md CHANGED
@@ -79,7 +79,7 @@ qlogicagent 不独立运行,需要由 openclaw Gateway 或其他 JSON-RPC 宿
79
79
  cd ../openclaw && node scripts/run-node.mjs gateway --port 18789
80
80
 
81
81
  # 手动测试(开发调试用)
82
- node dist/cli/main.js
82
+ node dist/cli.js
83
83
  ```
84
84
 
85
85
  启动后 agent 等待 stdin 接收 JSON-RPC 请求。
@@ -92,22 +92,23 @@ node dist/cli/main.js
92
92
 
93
93
  | 方法 | 说明 | 参数 |
94
94
  |------|------|------|
95
- | `agent.hello` | 协议握手 | `{ protocolVersion, hostName, hostVersion }` |
95
+ | `initialize` | 协议握手 | `{ protocolVersion, host: { name, version } }` |
96
96
  | `agent.ping` | 心跳检测 | — |
97
- | `agent.turn` | 执行一轮对话 | 见下方详细说明 |
97
+ | `thread.turn` | 执行一轮对话 | 见下方详细说明 |
98
98
  | `agent.abort` | 中止当前 turn | `{ turnId }` |
99
- | `session.list` | 列出历史会话 | `{ limit? }` |
99
+ | `thread.list` | 列出历史会话 | `{ limit? }` |
100
+ | `thread.create` | 创建新线程 | `{ id?, title?, cwd? }` |
100
101
  | `session.resume` | 恢复会话 | `{ sessionId }` |
101
102
  | `memory.dream` | 触发记忆整合 | — |
102
103
  | `tool.approval.response` | 工具审批响应 | `{ approvalId, decision }` |
103
104
 
104
- ### agent.turn 参数
105
+ ### thread.turn 参数
105
106
 
106
107
  ```json
107
108
  {
108
109
  "jsonrpc": "2.0",
109
110
  "id": 1,
110
- "method": "agent.turn",
111
+ "method": "thread.turn",
111
112
  "params": {
112
113
  "turnId": "turn-001",
113
114
  "sessionId": "sess-001",
@@ -202,7 +203,7 @@ src/
202
203
 
203
204
  ├── skills/ # 工具与技能层
204
205
  │ ├── portable-tool.ts # PortableTool 契约接口
205
- │ ├── tool-registry.ts # 工具注册表
206
+ │ ├── tools.ts # CC-aligned 工具池 (setToolPool/findTool/getToolManifest)
206
207
  │ ├── tools/ # 44 个内置工具
207
208
  │ │ ├── shell/ # 命令执行子系统 (11 文件)
208
209
  │ │ ├── exec-tool.ts # Shell 执行
@@ -242,9 +243,9 @@ qlogicagent 通过 HTTP 连接本地 QMemory 服务实现语义长期记忆。
242
243
 
243
244
  | 层 | 说明 | 存储 |
244
245
  |----|------|------|
245
- | **MD 记忆** | Agent 主动管理的笔记 (add/replace/remove) | `~/.openclaw/session-memory.md` |
246
+ | **MD 记忆** | Agent 主动管理的笔记 (add/replace/remove) | `~/.qlogicagent/session-memory.md` |
246
247
  | **QMemory** | 语义向量记忆,自动提取 + 语义召回 | QMemory 服务 (SQLite + embedding) |
247
- | **会话转录** | JSONL 对话记录,用于会话恢复 | `~/.openclaw/sessions/<id>/` |
248
+ | **会话转录** | JSONL 对话记录,用于会话恢复 | `~/.qlogicagent/sessions/<id>/` |
248
249
 
249
250
  ### 启用步骤
250
251
 
@@ -278,25 +279,25 @@ qlogicagent 通过 HTTP 连接本地 QMemory 服务实现语义长期记忆。
278
279
  | `QMEMORY_API_KEY` | QMemory 认证 Key | — |
279
280
  | `QLOGICAGENT_QMEMORY_BASE_URL` | QMemory 地址 (备选变量名) | — |
280
281
 
281
- ### 用户级配置(`~/.openclaw/`)
282
+ ### 用户级配置(`~/.qlogicagent/`)
282
283
 
283
284
  | 路径 | 说明 |
284
285
  |------|------|
285
- | `~/.openclaw/settings.json` | 权限规则、行为模式 |
286
- | `~/.openclaw/mcp.json` | 全局 MCP 服务器配置 |
287
- | `~/.openclaw/plugins/` | 用户级插件目录 |
288
- | `~/.openclaw/INSTRUCTIONS.md` | 用户级指令 |
289
- | `~/.openclaw/session-memory.md` | MD 记忆文件 |
290
- | `~/.openclaw/sessions/` | 会话持久化目录 |
291
- | `~/.openclaw/.credentials.json` | 安全凭据存储 (0o600) |
286
+ | `~/.qlogicagent/settings.json` | 权限规则、行为模式 |
287
+ | `~/.qlogicagent/mcp.json` | 全局 MCP 服务器配置 |
288
+ | `~/.qlogicagent/plugins/` | 用户级插件目录 |
289
+ | `~/.qlogicagent/INSTRUCTIONS.md` | 用户级指令 |
290
+ | `~/.qlogicagent/session-memory.md` | MD 记忆文件 |
291
+ | `~/.qlogicagent/sessions/` | 会话持久化目录 |
292
+ | `~/.qlogicagent/.credentials.json` | 安全凭据存储 (0o600) |
292
293
 
293
294
  ### 项目级配置
294
295
 
295
296
  | 路径 | 说明 |
296
297
  |------|------|
297
- | `.openclaw/settings.json` | 项目权限规则 |
298
- | `.openclaw/plugins/` | 项目级插件 |
299
- | `.openclaw/INSTRUCTIONS.md` | 项目指令 |
298
+ | `.qlogicagent/settings.json` | 项目权限规则 |
299
+ | `.qlogicagent/plugins/` | 项目级插件 |
300
+ | `.qlogicagent/INSTRUCTIONS.md` | 项目指令 |
300
301
  | `INSTRUCTIONS.md` | 项目指令 (根目录) |
301
302
  | `INSTRUCTIONS.local.md` | 本地私有指令 |
302
303
 
@@ -304,7 +305,7 @@ qlogicagent 通过 HTTP 连接本地 QMemory 服务实现语义长期记忆。
304
305
 
305
306
  ## MCP 配置
306
307
 
307
- ### 全局 MCP(`~/.openclaw/mcp.json`)
308
+ ### 全局 MCP(`~/.qlogicagent/mcp.json`)
308
309
 
309
310
  ```json
310
311
  {
@@ -341,7 +342,7 @@ MCP 工具自动注入到 Agent 工具列表,前缀格式:`mcp__servername__
341
342
 
342
343
  ## 权限配置
343
344
 
344
- ### `~/.openclaw/settings.json`
345
+ ### `~/.qlogicagent/settings.json`
345
346
 
346
347
  ```json
347
348
  {
@@ -377,7 +378,7 @@ pnpm dev # tsx watch 开发模式
377
378
  pnpm test # vitest 运行测试
378
379
  pnpm test:watch # vitest watch 模式
379
380
  pnpm lint # oxlint 代码检查
380
- pnpm start # 启动 CLI (node dist/cli/main.js)
381
+ pnpm start # 启动 CLI (node dist/cli.js)
381
382
  ```
382
383
 
383
384
  ## 测试
package/dist/agent.js CHANGED
@@ -1,18 +1,18 @@
1
- var Jt=Object.defineProperty;var Qt=(e,t)=>()=>(e&&(t=e(e=0)),t);var Zt=(e,t)=>{for(var o in t)Jt(e,o,{get:t[o],enumerable:!0})};var jt={};Zt(jt,{resolveToolEligibility:()=>Oo});function Mo(e,t){if(wo.some(o=>o.test(e)))return!0;if(t)for(let o of t)try{if(new RegExp(o,"i").test(e))return!0}catch{}return!1}function Io(e,t){let o=e.function.name,n=e.meta,r=[];return t.blockedToolNames?.includes(o)?(r.push("policy_blocked"),{level:5,reasons:r}):n?.isReadOnly?(r.push("always_allowed"),{level:1,reasons:r}):n?.requiresApproval?(r.push("approval_required"),{level:4,reasons:r}):n?.isDangerous||Mo(o,t.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function Lo(e){switch(e){case 1:return"eligible";case 2:return"eligible";case 3:return"dangerous-notify";case 4:return"approval-required";case 5:return"blocked-by-policy"}}function Oo(e,t={}){let o=new Map,n=[],r=[],i=[];for(let a of e){let s=a.function.name,{level:u,reasons:g}=Io(a,t),p=Lo(u),m={toolName:s,status:p,permissionLevel:u,approvalRequired:u===4,reasonCodes:g};o.set(s,m),u===5?r.push(m):(n.push(a),u===4&&i.push(m))}return{eligibleTools:n,blockedTools:r,approvalRequiredTools:i,eligibilityByName:o}}var wo,Ht=Qt(()=>{"use strict";wo=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function Te(e){return{role:"assistant",content:"",tool_calls:e}}function Q(e,t){return{role:"tool",tool_call_id:e,content:JSON.stringify(t.ok?{ok:!0,payload:t.payload}:{ok:!1,error:t.error??"Tool invoke failed"})}}var en=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,U={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]},tn=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,nn=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,on=512,rn=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var sn=new Set([500,502,503,504,521,522,523,524,529]),an=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],ln=["upgrade your plan","upgrade plan","current plan","subscription"],cn=["daily","weekly","monthly"],un=["try again","retry","temporary","cooldown"],dn=["usage limit","rate limit","organization usage"],pn=["organization","workspace"],mn=["billing period","exceeded","reached","exhausted"],gn=/["']?(?: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,fn=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function z(e,t){if(!e)return!1;let o=e.toLowerCase();return t.some(n=>n instanceof RegExp?n.test(o):o.includes(n))}function yn(e){return z(e,U.format)}function tt(e){return z(e,U.rateLimit)}function hn(e){return z(e,U.timeout)}function Tn(e){return en.test(e)}function Ce(e){let t=e.toLowerCase();return t?e.length>on?nn.test(t):z(t,U.billing)?!0:tn.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function nt(e){return z(e,U.authPermanent)}function Cn(e){return z(e,U.auth)}function ot(e){return z(e,U.overloaded)}function B(e,t){return t.some(o=>e.includes(o))}function bn(e){return B(e,an)||B(e,ln)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function kn(e){let t=B(e,cn),o=e.includes("spend limit")||e.includes("spending limit"),n=B(e,pn);return B(e,un)&&B(e,dn)||t&&(e.includes("usage limit")||o)||t&&e.includes("limit")&&e.includes("reset")||n&&e.includes("limit")&&(o||B(e,mn))}function Sn(e){return e.trim().toLowerCase().replace(fn,"").trim()}function rt(e){let t=Sn(e);return!t||bn(t)?"billing":tt(t)||kn(t)?"rate_limit":"billing"}function xn(e){return gn.test(e)?rt(e):null}function st(e){let t=e.match(rn);if(!t)return null;let o=Number(t[1]);return Number.isFinite(o)?{code:o,rest:(t[2]??"").trim()}:null}function Rn(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function _n(e){let t=e.trim();if(!t)return!1;let o=st(t);return o?sn.has(o.code):!1}function it(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?rt(t):"billing":e===429?"rate_limit":e===401||e===403?t&&nt(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&ot(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&Ce(t)?"billing":"format":null}function vn(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 An(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 at(e){if(An(e))return"session_expired";if(vn(e))return"model_not_found";let t=xn(e);return t||(Tn(e)?Ce(e)?"billing":"rate_limit":tt(e)?"rate_limit":ot(e)?"overloaded":_n(e)?st(e.trim())?.code===529?"overloaded":"timeout":Rn(e)?"timeout":yn(e)?"format":Ce(e)?"billing":hn(e)?"timeout":nt(e)?"auth_permanent":Cn(e)?"auth":null)}var En={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"},wn={RETRYABLE_TRANSIENT:{retryable:!0,maxRetries:3,baseDelayMs:1e3,backoffMultiplier:2,switchProvider:!0},RETRYABLE_DEGRADED:{retryable:!0,maxRetries:2,baseDelayMs:5e3,backoffMultiplier:3,switchProvider:!0},NON_RETRYABLE_AUTH:{retryable:!1,maxRetries:0,baseDelayMs:0,backoffMultiplier:1,switchProvider:!0},NON_RETRYABLE_CONTENT:{retryable:!1,maxRetries:0,baseDelayMs:0,backoffMultiplier:1,switchProvider:!1},NON_RETRYABLE_QUOTA:{retryable:!1,maxRetries:0,baseDelayMs:0,backoffMultiplier:1,switchProvider:!0},TOOL_EXECUTION_FAILED:{retryable:!0,maxRetries:1,baseDelayMs:500,backoffMultiplier:1,switchProvider:!1}};function Z(e,t){let o=it(e,t)??(t?at(t):null);return o?En[o]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function be(e){return wn[e]}var lt=4,ee=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,o){let n=[],r=[];for(let p of t)p.role==="system"?n.push(p):r.push(p);let i=o;for(let p of n)i-=this.estimateTokens(p);let a;for(let p of r)if(p.role==="user"){a=p;break}if(a&&(i-=this.estimateTokens(a)),i<=0)return{messages:a?[...n,a]:n,droppedCount:r.length-(a?1:0),strategy:"sliding-window"};let s=[],u=0;for(let p=r.length-1;p>=0;p--){let m=r[p];if(m===a)continue;let b=this.estimateTokens(m);if(i-b<0&&u>=lt)break;if(i-b<0&&u<lt){s.unshift(m),u++;continue}i-=b,s.unshift(m),u++}let g=[...n];return a&&!s.includes(a)&&g.push(a),g.push(...s),{messages:g,droppedCount:r.length-(s.length+(a&&!s.includes(a)?1:0)),strategy:"sliding-window"}}};var te=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,o){let n=0;return{messages:t.map(i=>i.role!=="tool"||typeof i.content!="string"||i.content.length<=this.maxToolResultChars?i:(n++,{...i,content:Mn(i.content,this.maxToolResultChars)})),droppedCount:n,strategy:"tool-result-trim"}}};function Mn(e,t){if(e.length<=t)return e;let o=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let i=Math.max(o.lastIndexOf("},"),o.lastIndexOf("],"),o.lastIndexOf(`}
2
- `),o.lastIndexOf(`]
3
- `));if(i>t*.5)return o.slice(0,i+1)+`
4
- [...truncated: ${e.length-i-1} chars omitted]`}let r=o.lastIndexOf(`
5
- `);return r>t*.7?o.slice(0,r)+`
6
- [...truncated: ${e.length-r} chars omitted]`:o+`
7
- [...truncated: ${e.length-t} chars omitted]`}function ke(...e){return{compress(t,o){let n=t,r=0,i=[];for(let a of e){let s=a.compress(n,o);n=s.messages,r+=s.droppedCount,s.droppedCount>0&&i.push(s.strategy)}return{messages:n,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}}}}var ct={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function Se(e={}){let t={...ct,...e},o=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(o,t.maxBudget))}function xe(e,t){let o=e/t;return o<=.8?"none":o<=1?"trim-only":o<=1.5?"sliding-window":"llm-summarize"}var ne=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 o=0,n=0,r=0,i=0,a=0;for(let s of this.events)o+=s.tokensBefore>0?s.tokensAfter/s.tokensBefore:1,n+=s.latencyMs,r+=Math.max(0,s.tokensBefore-s.tokensAfter),s.usedLlm&&i++,s.cacheInvalidated&&a++;return{totalCompressions:t,totalLlmCalls:i,totalCacheInvalidations:a,averageCompressionRatio:o/t,averageLatencyMs:n/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},oe=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 ut(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var In=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"]),j=class{constructor(t=20,o=ut){this.preserveRecentCount=t;this.estimateTokens=o}preserveRecentCount;estimateTokens;compress(t,o){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let n=t.length-this.preserveRecentCount,r=0,i=0;return{messages:t.map((s,u)=>{if(u>=n||s.role!=="tool"||typeof s.content!="string"||!s.name||!In.has(s.name)||s.content.length<=200)return s;let g=this.estimateTokens(s);return i+=g,r++,{...s,content:`[result cleared \u2014 ${s.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function Re(e,t,o=ut){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let n=0,r=0,i=[];for(let s of e){let u=s.tool_call_id??"";if(u&&t.has(u)){n+=o(s),r++,t.delete(u);continue}i.push(s)}let a=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:n,removedCount:r,boundaryMessage:a}}function _e(){return{stages:[]}}function ve(e,t,o){let n=o?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=n)return{messages:e,stagedCount:0};let i=dt(e,t),a=Ln(i,t,n);if(a.length===0)return{messages:i,stagedCount:0};for(let s of a)t.stages.push(s);return i=dt(e,t),{messages:i,stagedCount:a.length}}function Ae(e,t){let o=0;for(let n of t.stages)n.committed||(n.committed=!0,o++);return o===0?{messages:e,committed:0}:{messages:pt(e,t),committed:o}}function dt(e,t){return t.stages.filter(n=>n.committed).length===0?e:pt(e,t)}function pt(e,t){let o=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),n=[...e];for(let r of o){let[i,a]=r.range;if(i>=n.length)continue;let s=Math.min(a,n.length),u={role:"system",content:r.summary};n.splice(i,s-i,u)}return n}function Ln(e,t,o){let n=Math.max(0,e.length-Math.floor(o/2)),r=[],i=new Set(t.stages.map(u=>`${u.range[0]}-${u.range[1]}`)),a=-1,s=0;for(let u=0;u<n;u++){let g=e[u];if(g.role==="tool"||g.role==="assistant"&&typeof g.content=="string"&&g.content==="")a<0&&(a=u),s++;else{if(s>=3){let m=`${a}-${a+s}`;i.has(m)||r.push({id:`collapse_${a}_${a+s}`,range:[a,a+s],summary:`[${s} tool results collapsed]`,committed:!1})}a=-1,s=0}}if(s>=3){let u=`${a}-${a+s}`;i.has(u)||r.push({id:`collapse_${a}_${a+s}`,range:[a,a+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}function On(e){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<3||e.distinctToolCount<2)}function Pn(e){return e.existingSkillName?e.feedback==="negative":!1}function ue(e,t){return Pn(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:On(e)?{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}:null}function mt(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 Nn(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Dn(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Fn(e){if(!e.eligibility?.length)return[...e.tools];let t=Dn(e.eligibility);return e.tools.filter(o=>{let n=mt(o);if(!n)return!1;let r=t.get(n);return!r||Nn(r.status)})}function $n(e){let t=[],o=e.compatibility??{},n=e.toolChoice;if(e.thinkingEnabled&&o.requireAutoWhenThinking){let r=typeof n=="object"&&n&&!Array.isArray(n)?String(n.type??""):n;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),n="auto")}if(n==="required"&&o.allowRequiredToolChoice===!1){let r=o.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),n=r}if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&o.allowNamedToolChoice===!1){let r=o.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),n=r}return{normalizedToolChoice:n,warnings:t}}function Ee(e){let t=$n({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),o=t.normalizedToolChoice,n=[...t.warnings],r=Fn({tools:e.tools,eligibility:e.eligibility});if(!o||o==="auto")return{tools:r,normalizedToolChoice:o,warnings:n};if(o==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(o==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:n}}if(typeof o=="object"&&!Array.isArray(o)&&o.type==="function"){let i=o.function??void 0,a=typeof i?.name=="string"?i.name.trim():"";if(!a)throw new Error("tool_choice.function.name is required");let s=r.filter(u=>mt(u)===a);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${a}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:a}},extraSystemPrompt:`You must call the ${a} tool before responding.`,warnings:n}}return{tools:r,normalizedToolChoice:o,warnings:n}}var Bn=["stop","aborted","timeout","cancelled","interrupted","error"],Un=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function gt(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function zn(e,t){return{...e,content:[...gt(e.content),...gt(t.content)]}}function jn(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 Hn(e){return new Set((e??Bn).map(t=>t.trim().toLowerCase()))}function qn(e,t){return e?Hn(t).has(e.trim().toLowerCase()):!1}function we(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(s=>{if(s.role==="assistant"&&Array.isArray(s.tool_calls)){let u=s.tool_calls.filter(g=>jn(g));return{...s,...u.length>0?{tool_calls:u}:{tool_calls:void 0}}}return{...s}}),o=new Set;for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let u of s.tool_calls)typeof u.id=="string"&&u.id&&o.add(u.id);let n=t.filter(s=>s.role!=="tool"?!0:!!(s.tool_call_id&&o.has(s.tool_call_id))),r=new Set;for(let s of n)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&r.add(s.tool_call_id);let i=[];for(let s of n){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let u=s.tool_calls.filter(g=>typeof g.id=="string"&&r.has(g.id));if(u.length===0){let{tool_calls:g,...p}=s;p.content!=null&&p.content!==""&&i.push(p);continue}if(u.length<s.tool_calls.length){i.push({...s,tool_calls:u});continue}}i.push(s)}let a=[];for(let s of i){let u=a.length>0?a[a.length-1]:void 0;if(s.role==="user"&&u?.role==="user"){a[a.length-1]=zn(u,s);continue}a.push(s)}return a}function Me(e,t){return qn(t?.stopReason,t?.forcedStopReasons)?e.map(o=>{if(o.role!=="assistant")return{...o};let n={...o};for(let r of Un)delete n[r];return n}):[...e]}function Ie(e,t){let o=t?.placeholderToolResult??JSON.stringify({ok:!1,error:"Tool loop interrupted before the tool result was replayed."}),n=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&n.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 a of i.tool_calls)typeof a.id!="string"||!a.id||n.has(a.id)||(n.add(a.id),r.push({role:"tool",tool_call_id:a.id,content:o}));return r}function Le(e,t){let o=we(e),n=Me(o,t);return Ie(n,t)}function Gn(e){let t=new Set,o=new Set;for(let n of e){if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let r of n.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&o.add(n.tool_call_id)}return[...t].filter(n=>!o.has(n))}function Wn(e){let t=new Set;for(let o of e)o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&t.add(o.tool_call_id);return[...t]}function Yn(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Oe(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 de(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 pe(e){let t=[],o=we(e.replayMessages);o.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let n=Me(o,e.options);n.some((i,a)=>i!==o[a])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=Ie(n,e.options);return r.length>n.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Yn({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Gn(r),completedToolCallIds:Wn(r)}),recoveryActions:t}}import{MEMORY_OBSERVATION_HOOK_VALUES as Kn,MEMORY_OBSERVATION_SOURCE_VALUES as Xn,MEMORY_WRITE_ACCESS_VALUES as Vn}from"qlogicagent-runtime-contracts";var Jn=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Pe(e){return e?Jn.has(e):!0}function Ne(e){return e===429||e===529}function me(e,t=500,o=32e3){let n=Math.min(t*Math.pow(2,e-1),o);return n+Math.floor(Math.random()*n*.25)}var mr={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function De(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var re=class extends Error{constructor(o,n){super(`Model fallback triggered: ${o} -> ${n}`);this.originalModel=o;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function Fe(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function $e(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let o=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,n=o>0?e.promptTokens/o*100:100;return e.promptTokens>=o?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:n>=85?{level:"warning",usagePercent:n,remainingTokens:o-e.promptTokens}:{level:"ok"}}function Be(e,t,o){let n=e.message?.toLowerCase()??"",r=e.status??0;return r===413||n.includes("prompt_too_long")||n.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&o.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"}:{action:"abort",reason:n||"unknown_error"}}function Ue(e,t,o){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let n=Math.min(e.currentMaxOutputTokens*2,o);return n<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:n}}function ze(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Qn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function je(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function G(e,t=Qn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}var so={research:{type:"research",label:"Research",description:"Independent retrieval or evidence gathering branches.",mergePolicy:"summary-only",budgetTier:"medium",budgetWeight:2,preferFullContext:!1,preserveConversationHistory:!0,toolAccessMode:"read-only"},planner:{type:"planner",label:"Planner",description:"Planning and tool orchestration branches that may return structured context.",mergePolicy:"append-messages",budgetTier:"high",budgetWeight:3,preferFullContext:!0,preserveConversationHistory:!0,toolAccessMode:"none"},"plan-repair":{type:"plan-repair",label:"Plan Repair",description:"Failure repair or fallback branches that re-plan tool choice, ordering, or approval strategy.",mergePolicy:"replace-context",budgetTier:"medium",budgetWeight:2,preferFullContext:!0,preserveConversationHistory:!1,toolAccessMode:"none"},"code-repair":{type:"code-repair",label:"Code Repair",description:"Recovery branches focused on file edits, patch validation, or workspace mutation repair.",mergePolicy:"replace-context",budgetTier:"high",budgetWeight:3,preferFullContext:!0,preserveConversationHistory:!1,toolAccessMode:"full"},"media-prep":{type:"media-prep",label:"Media Prep",description:"Preparation branches for media generation, normalization, or staging.",mergePolicy:"summary-only",budgetTier:"low",budgetWeight:1,preferFullContext:!1,preserveConversationHistory:!1,toolAccessMode:"read-only"}},He=["gateway","agents_list","whatsapp_login","session_status","cron","memory_query","sessions_send"],io=["sessions_list","sessions_history","sessions_spawn"],ft=["file_edit","create_file","replace_string_in_file","multi_replace_string_in_file","create_directory","run_in_terminal","run_command","delete_file","rename_file","move_file","git_commit","git_push","manage_todo_list"];function ao(e={}){let t=Math.max(1,Math.floor(e.maxDepth??2)),o=typeof e.depth=="number"&&Number.isFinite(e.depth)?Math.max(0,Math.floor(e.depth)):t,n=e.role?e.role==="leaf":o>=t,r=n?[...He,...io]:[...He],i=new Set(r),a=Array.isArray(e.toolNames)?e.toolNames:e.toolNames?Array.from(e.toolNames):[],s=Array.from(new Set(a.map(u=>u.trim()).filter(Boolean))).map(u=>{let g=i.has(u);return{toolName:u,decision:g?"denied":"allowed",inheritance:g?"shrink":"inherit",reason:g?He.includes(u)?"always-deny":"leaf-deny":"default-allow"}});return{deniedTools:r,canSpawnChildren:!n,defaultDecision:"allowed",defaultInheritance:"inherit",tools:s}}function yt(e){let t=lo(e.type),o=ao({depth:e.depth,maxDepth:e.maxDepth,role:e.role,toolNames:e.toolNames});if(t.toolAccessMode==="full")return o;if(t.toolAccessMode==="none"){let i=Array.isArray(e.toolNames)?e.toolNames:e.toolNames?Array.from(e.toolNames):[],a=[...new Set(i.map(s=>s.trim()).filter(Boolean))];return{deniedTools:a,canSpawnChildren:!1,defaultDecision:"allowed",defaultInheritance:"inherit",tools:a.map(s=>({toolName:s,decision:"denied",inheritance:"shrink",reason:"always-deny"}))}}let n=new Set(ft),r=[...new Set([...o.deniedTools,...ft])];return{...o,deniedTools:r,tools:o.tools.map(i=>i.decision==="denied"?i:n.has(i.toolName)?{...i,decision:"denied",inheritance:"shrink",reason:"always-deny"}:i)}}function ht(e,t){let o=new Set(t.deniedTools),n=new Map(t.tools.map(a=>[a.toolName,a])),r=[],i=[];for(let a of e){let s=a.function.name,u=n.get(s);u?.decision==="denied"?i.push({toolCall:a,reason:`tool "${s}" denied by sidechain policy: ${u.reason}`}):o.has(s)?i.push({toolCall:a,reason:`tool "${s}" is in sidechain deny list`}):r.push(a)}return{allowed:r,denied:i}}function lo(e){return so[e]}function Tt(e,t){let o=e.get(t.index);o||(o={id:"",name:"",arguments:""},e.set(t.index,o)),t.id&&(o.id=t.id),t.name&&(o.name+=t.name),o.arguments+=t.arguments}import{mkdir as co,writeFile as uo}from"fs/promises";import{join as It}from"path";import{tmpdir as po}from"os";var Ct=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),bt=3,W=2,kt=128e3,St=13e3,xt=16384,Rt=65536,_t=3,vt=65536,At=3e4,Et=3,wt=5e4,Mt=2e5,qe=2e3;var mo="tool-results",Lt="<persisted-output>",go="</persisted-output>";function Ot(){return{seenIds:new Set,replacements:new Map}}function Pt(e){return It(po(),"qlogicagent-sessions",e,mo)}async function fo(e){try{await co(Pt(e),{recursive:!0})}catch{}}function yo(e,t){let o=t.replace(/[^a-zA-Z0-9_-]/g,"_");return It(Pt(e),`${o}.txt`)}function ho(e,t){if(e.length<=t)return{preview:e,hasMore:!1};let n=e.slice(0,t).lastIndexOf(`
8
- `),r=n>t*.5?n:t;return{preview:e.slice(0,r),hasMore:!0}}function Nt(e){return e.includes(Lt)}async function Dt(e,t,o){await fo(o);let n=yo(o,t);try{await uo(n,e,{encoding:"utf-8",flag:"wx"})}catch(a){if(a.code!=="EEXIST")return null}let{preview:r,hasMore:i}=ho(e,qe);return{filepath:n,originalSize:e.length,preview:r,hasMore:i}}function Ft(e){let t=`${Lt}
1
+ var Ht=Object.defineProperty;var qt=(e,t)=>()=>(e&&(t=e(e=0)),t);var Wt=(e,t)=>{for(var n in t)Ht(e,n,{get:t[n],enumerable:!0})};var Nt={};Wt(Nt,{resolveToolEligibility:()=>Cn});function yn(e,t){if(fn.some(n=>n.test(e)))return!0;if(t)for(let n of t)try{if(new RegExp(n,"i").test(e))return!0}catch{}return!1}function Tn(e,t){let n=e.function.name,o=e.meta,r=[];return t.blockedToolNames?.includes(n)?(r.push("policy_blocked"),{level:5,reasons:r}):o?.isReadOnly?(r.push("always_allowed"),{level:1,reasons:r}):o?.requiresApproval?(r.push("approval_required"),{level:4,reasons:r}):o?.isDangerous||yn(n,t.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function hn(e){switch(e){case 1:return"eligible";case 2:return"eligible";case 3:return"dangerous-notify";case 4:return"approval-required";case 5:return"blocked-by-policy"}}function Cn(e,t={}){let n=new Map,o=[],r=[],i=[];for(let l of e){let s=l.function.name,{level:d,reasons:g}=Tn(l,t),p=hn(d),m={toolName:s,status:p,permissionLevel:d,approvalRequired:d===4,reasonCodes:g};n.set(s,m),d===5?r.push(m):(o.push(l),d===4&&i.push(m))}return{eligibleTools:o,blockedTools:r,approvalRequiredTools:i,eligibilityByName:n}}var fn,Ft=qt(()=>{"use strict";fn=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function fe(e){return{role:"assistant",content:"",tool_calls:e}}function J(e,t){return{role:"tool",tool_call_id:e,content:JSON.stringify(t.ok?{ok:!0,payload:t.payload}:{ok:!1,error:t.error??"Tool invoke failed"})}}var Kt=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,$={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]},Xt=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Yt=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Jt=512,Vt=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Qt=new Set([500,502,503,504,521,522,523,524,529]),Zt=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],eo=["upgrade your plan","upgrade plan","current plan","subscription"],to=["daily","weekly","monthly"],oo=["try again","retry","temporary","cooldown"],no=["usage limit","rate limit","organization usage"],ro=["organization","workspace"],so=["billing period","exceeded","reached","exhausted"],io=/["']?(?: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,ao=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function U(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function lo(e){return U(e,$.format)}function Ve(e){return U(e,$.rateLimit)}function co(e){return U(e,$.timeout)}function uo(e){return Kt.test(e)}function ye(e){let t=e.toLowerCase();return t?e.length>Jt?Yt.test(t):U(t,$.billing)?!0:Xt.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Qe(e){return U(e,$.authPermanent)}function po(e){return U(e,$.auth)}function Ze(e){return U(e,$.overloaded)}function B(e,t){return t.some(n=>e.includes(n))}function mo(e){return B(e,Zt)||B(e,eo)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function go(e){let t=B(e,to),n=e.includes("spend limit")||e.includes("spending limit"),o=B(e,ro);return B(e,oo)&&B(e,no)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||B(e,so))}function fo(e){return e.trim().toLowerCase().replace(ao,"").trim()}function et(e){let t=fo(e);return!t||mo(t)?"billing":Ve(t)||go(t)?"rate_limit":"billing"}function yo(e){return io.test(e)?et(e):null}function tt(e){let t=e.match(Vt);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function To(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function ho(e){let t=e.trim();if(!t)return!1;let n=tt(t);return n?Qt.has(n.code):!1}function ot(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?et(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Qe(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&Ze(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&ye(t)?"billing":"format":null}function Co(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 bo(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 nt(e){if(bo(e))return"session_expired";if(Co(e))return"model_not_found";let t=yo(e);return t||(uo(e)?ye(e)?"billing":"rate_limit":Ve(e)?"rate_limit":Ze(e)?"overloaded":ho(e)?tt(e.trim())?.code===529?"overloaded":"timeout":To(e)?"timeout":lo(e)?"format":ye(e)?"billing":co(e)?"timeout":Qe(e)?"auth_permanent":po(e)?"auth":null)}var ko={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"},_o={RETRYABLE_TRANSIENT:{retryable:!0,maxRetries:3,baseDelayMs:1e3,backoffMultiplier:2,switchProvider:!0},RETRYABLE_DEGRADED:{retryable:!0,maxRetries:2,baseDelayMs:5e3,backoffMultiplier:3,switchProvider:!0},NON_RETRYABLE_AUTH:{retryable:!1,maxRetries:0,baseDelayMs:0,backoffMultiplier:1,switchProvider:!0},NON_RETRYABLE_CONTENT:{retryable:!1,maxRetries:0,baseDelayMs:0,backoffMultiplier:1,switchProvider:!1},NON_RETRYABLE_QUOTA:{retryable:!1,maxRetries:0,baseDelayMs:0,backoffMultiplier:1,switchProvider:!0},TOOL_EXECUTION_FAILED:{retryable:!0,maxRetries:1,baseDelayMs:500,backoffMultiplier:1,switchProvider:!1}};function G(e,t){let n=ot(e,t)??(t?nt(t):null);return n?ko[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Te(e){return _o[e]}var rt=4,V=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 l;for(let p of r)if(p.role==="user"){l=p;break}if(l&&(i-=this.estimateTokens(l)),i<=0)return{messages:l?[...o,l]:o,droppedCount:r.length-(l?1:0),strategy:"sliding-window"};let s=[],d=0;for(let p=r.length-1;p>=0;p--){let m=r[p];if(m===l)continue;let k=this.estimateTokens(m);if(i-k<0&&d>=rt)break;if(i-k<0&&d<rt){s.unshift(m),d++;continue}i-=k,s.unshift(m),d++}let g=[...o];return l&&!s.includes(l)&&g.push(l),g.push(...s),{messages:g,droppedCount:r.length-(s.length+(l&&!s.includes(l)?1:0)),strategy:"sliding-window"}}};var Q=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:Ro(i.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function Ro(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(`}
2
+ `),n.lastIndexOf(`]
3
+ `));if(i>t*.5)return n.slice(0,i+1)+`
4
+ [...truncated: ${e.length-i-1} chars omitted]`}let r=n.lastIndexOf(`
5
+ `);return r>t*.7?n.slice(0,r)+`
6
+ [...truncated: ${e.length-r} chars omitted]`:n+`
7
+ [...truncated: ${e.length-t} chars omitted]`}function he(...e){return{compress(t,n){let o=t,r=0,i=[];for(let l of e){let s=l.compress(o,n);o=s.messages,r+=s.droppedCount,s.droppedCount>0&&i.push(s.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}}}}var st={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function Ce(e={}){let t={...st,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function be(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var Z=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,l=0;for(let s of this.events)n+=s.tokensBefore>0?s.tokensAfter/s.tokensBefore:1,o+=s.latencyMs,r+=Math.max(0,s.tokensBefore-s.tokensAfter),s.usedLlm&&i++,s.cacheInvalidated&&l++;return{totalCompressions:t,totalLlmCalls:i,totalCacheInvalidations:l,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},ee=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 it(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var xo=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"]),j=class{constructor(t=20,n=it){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=t.length-this.preserveRecentCount,r=0,i=0;return{messages:t.map((s,d)=>{if(d>=o||s.role!=="tool"||typeof s.content!="string"||!s.name||!xo.has(s.name)||s.content.length<=200)return s;let g=this.estimateTokens(s);return i+=g,r++,{...s,content:`[result cleared \u2014 ${s.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function ke(e,t,n=it){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let s of e){let d=s.tool_call_id??"";if(d&&t.has(d)){o+=n(s),r++,t.delete(d);continue}i.push(s)}let l=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:l}}function _e(){return{stages:[]}}function Re(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=at(e,t),l=So(i,t,o);if(l.length===0)return{messages:i,stagedCount:0};for(let s of l)t.stages.push(s);return i=at(e,t),{messages:i,stagedCount:l.length}}function xe(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:lt(e,t),committed:n}}function at(e,t){return t.stages.filter(o=>o.committed).length===0?e:lt(e,t)}function lt(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,l]=r.range;if(i>=o.length)continue;let s=Math.min(l,o.length),d={role:"system",content:r.summary};o.splice(i,s-i,d)}return o}function So(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(d=>`${d.range[0]}-${d.range[1]}`)),l=-1,s=0;for(let d=0;d<o;d++){let g=e[d];if(g.role==="tool"||g.role==="assistant"&&typeof g.content=="string"&&g.content==="")l<0&&(l=d),s++;else{if(s>=3){let m=`${l}-${l+s}`;i.has(m)||r.push({id:`collapse_${l}_${l+s}`,range:[l,l+s],summary:`[${s} tool results collapsed]`,committed:!1})}l=-1,s=0}}if(s>=3){let d=`${l}-${l+s}`;i.has(d)||r.push({id:`collapse_${l}_${l+s}`,range:[l,l+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}function vo(e){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<3||e.distinctToolCount<2)}function Ao(e){return e.existingSkillName?e.feedback==="negative":!1}function le(e,t){return Ao(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:vo(e)?{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}:null}function ct(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 Eo(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Mo(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function wo(e){if(!e.eligibility?.length)return[...e.tools];let t=Mo(e.eligibility);return e.tools.filter(n=>{let o=ct(n);if(!o)return!1;let r=t.get(o);return!r||Eo(r.status)})}function Io(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 Se(e){let t=Io({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=wo({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,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:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,l=typeof i?.name=="string"?i.name.trim():"";if(!l)throw new Error("tool_choice.function.name is required");let s=r.filter(d=>ct(d)===l);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${l}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:l}},extraSystemPrompt:`You must call the ${l} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Lo=["stop","aborted","timeout","cancelled","interrupted","error"],Oo=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function ut(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Po(e,t){return{...e,content:[...ut(e.content),...ut(t.content)]}}function No(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 Fo(e){return new Set((e??Lo).map(t=>t.trim().toLowerCase()))}function Do(e,t){return e?Fo(t).has(e.trim().toLowerCase()):!1}function ve(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(s=>{if(s.role==="assistant"&&Array.isArray(s.tool_calls)){let d=s.tool_calls.filter(g=>No(g));return{...s,...d.length>0?{tool_calls:d}:{tool_calls:void 0}}}return{...s}}),n=new Set;for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let d of s.tool_calls)typeof d.id=="string"&&d.id&&n.add(d.id);let o=t.filter(s=>s.role!=="tool"?!0:!!(s.tool_call_id&&n.has(s.tool_call_id))),r=new Set;for(let s of o)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&r.add(s.tool_call_id);let i=[];for(let s of o){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let d=s.tool_calls.filter(g=>typeof g.id=="string"&&r.has(g.id));if(d.length===0){let{tool_calls:g,...p}=s;p.content!=null&&p.content!==""&&i.push(p);continue}if(d.length<s.tool_calls.length){i.push({...s,tool_calls:d});continue}}i.push(s)}let l=[];for(let s of i){let d=l.length>0?l[l.length-1]:void 0;if(s.role==="user"&&d?.role==="user"){l[l.length-1]=Po(d,s);continue}l.push(s)}return l}function Ae(e,t){return Do(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Oo)delete o[r];return o}):[...e]}function Ee(e,t){let n=t?.placeholderToolResult??JSON.stringify({ok:!1,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 l of i.tool_calls)typeof l.id!="string"||!l.id||o.has(l.id)||(o.add(l.id),r.push({role:"tool",tool_call_id:l.id,content:n}));return r}function Me(e,t){let n=ve(e),o=Ae(n,t);return Ee(o,t)}function Bo(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 $o(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 Uo(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function we(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 ce(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 ue(e){let t=[],n=ve(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=Ae(n,e.options);o.some((i,l)=>i!==n[l])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=Ee(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:Uo({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Bo(r),completedToolCallIds:$o(r)}),recoveryActions:t}}var jo=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Ie(e){return e?jo.has(e):!0}function Le(e){return e===429||e===529}function de(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 zn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Oe(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var te=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function Pe(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Ne(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 Fe(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"}:{action:"abort",reason:o||"unknown_error"}}function De(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 Be(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var zo={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function $e(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function H(e,t=zo){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function dt(e,t){let n=e.get(t.index);n||(n={id:"",name:"",arguments:""},e.set(t.index,n)),t.id&&(n.id=t.id),t.name&&(n.name+=t.name),n.arguments+=t.arguments}import{mkdir as Yo,writeFile as Jo}from"fs/promises";import{join as xt}from"path";import{tmpdir as Vo}from"os";var pt=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),mt=3,gt=128e3,ft=13e3,yt=16384,Tt=65536,ht=3,Ct=65536,bt=3e4,kt=3,oe=5,_t=5e4,Rt=2e5,Ue=2e3;var Qo="tool-results",St="<persisted-output>",Zo="</persisted-output>";function vt(){return{seenIds:new Set,replacements:new Map}}function At(e){return xt(Vo(),"qlogicagent-sessions",e,Qo)}async function en(e){try{await Yo(At(e),{recursive:!0})}catch{}}function tn(e,t){let n=t.replace(/[^a-zA-Z0-9_-]/g,"_");return xt(At(e),`${n}.txt`)}function on(e,t){if(e.length<=t)return{preview:e,hasMore:!1};let o=e.slice(0,t).lastIndexOf(`
8
+ `),r=o>t*.5?o:t;return{preview:e.slice(0,r),hasMore:!0}}function Et(e){return e.includes(St)}async function Mt(e,t,n){await en(n);let o=tn(n,t);try{await Jo(o,e,{encoding:"utf-8",flag:"wx"})}catch(l){if(l.code!=="EEXIST")return null}let{preview:r,hasMore:i}=on(e,Ue);return{filepath:o,originalSize:e.length,preview:r,hasMore:i}}function wt(e){let t=`${St}
9
9
  `;return t+=`Output too large (${e.originalSize} chars). Full output saved to: ${e.filepath}
10
10
 
11
- `,t+=`Preview (first ${qe} bytes):
11
+ `,t+=`Preview (first ${Ue} bytes):
12
12
  `,t+=e.preview,t+=e.hasMore?`
13
13
  ...
14
14
  `:`
15
- `,t+=go,t}async function $t(e,t,o,n=wt){if(e.length<=n||Nt(e))return e;let r=await Dt(e,t,o);return r?Ft(r):e.slice(0,n)+`
16
- ...[truncated ${e.length-n} chars]`}function To(e){let t=[],o=[];for(let n of e)n.role==="tool"&&typeof n.content=="string"&&n.tool_call_id?Nt(n.content)||o.push({toolCallId:n.tool_call_id,content:n.content,size:n.content.length}):n.role==="assistant"&&o.length>0&&(t.push(o),o=[]);return o.length>0&&t.push(o),t}function Co(e,t){let o=[],n=[],r=[];for(let i of e){let a=t.replacements.get(i.toolCallId);a!==void 0?o.push({...i,replacement:a}):t.seenIds.has(i.toolCallId)?n.push(i):r.push(i)}return{mustReapply:o,frozen:n,fresh:r}}function bo(e,t,o){let n=[...e].sort((a,s)=>s.size-a.size),r=[],i=t+e.reduce((a,s)=>a+s.size,0);for(let a of n){if(i<=o)break;r.push(a),i-=a.size}return r}async function Bt(e,t,o,n=Mt){let r=To(e);if(r.length===0)return{messages:e,newlyReplacedCount:0};let i=new Map,a=[];for(let p of r){let{mustReapply:m,frozen:b,fresh:f}=Co(p,t);for(let y of m)i.set(y.toolCallId,y.replacement);if(f.length===0){for(let y of p)t.seenIds.add(y.toolCallId);continue}let k=b.reduce((y,x)=>y+x.size,0),T=f.reduce((y,x)=>y+x.size,0),h=k+T>n?bo(f,k,n):[],A=new Set(h.map(y=>y.toolCallId));for(let y of p)A.has(y.toolCallId)||t.seenIds.add(y.toolCallId);h.length>0&&a.push(...h)}if(i.size===0&&a.length===0)return{messages:e,newlyReplacedCount:0};let s=await Promise.all(a.map(async p=>{let m=await Dt(p.content,p.toolCallId,o);return{candidate:p,result:m}})),u=0;for(let{candidate:p,result:m}of s){if(t.seenIds.add(p.toolCallId),!m)continue;let b=Ft(m);i.set(p.toolCallId,b),t.replacements.set(p.toolCallId,b),u++}return i.size===0?{messages:e,newlyReplacedCount:0}:{messages:e.map(p=>{if(p.role!=="tool"||!p.tool_call_id)return p;let m=i.get(p.tool_call_id);return m===void 0?p:{...p,content:m}}),newlyReplacedCount:u}}var ko=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),So=new Set(["bash","execute_command","Bash","shell"]),ge=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(t){this.config=t,this.concurrencySafe=t.concurrencySafeTools??ko,this.siblingAbortController=new AbortController,t.signal&&t.signal.addEventListener("abort",()=>{this.siblingAbortController.abort("parent_abort")},{once:!0})}discard(){this.discarded=!0}addTool(t){let o=this.concurrencySafe.has(t.function.name);this.tools.push({id:t.id,toolCall:t,status:"queued",isConcurrencySafe:o,results:[],pendingProgress:[]}),this.processQueue()}canExecuteTool(t){let o=this.tools.filter(r=>r.status==="executing"),n=this.config.maxConcurrentTools;return n&&n>0&&o.length>=n?!1:o.length===0||t&&o.every(r=>r.isConcurrencySafe)}async processQueue(){for(let t of this.tools)if(t.status==="queued"){if(this.canExecuteTool(t.isConcurrencySafe))await this.executeTool(t);else if(!t.isConcurrencySafe)break}}getAbortReason(){return this.discarded?"discarded":this.hasErrored?"sibling_error":this.config.signal?.aborted?"user_interrupted":null}getToolDescription(t){let o;try{o=JSON.parse(t.toolCall.function.arguments)}catch{}let n=o?.command??o?.file_path??o?.pattern??"";if(typeof n=="string"&&n.length>0){let r=n.length>40?n.slice(0,40)+"\u2026":n;return`${t.toolCall.function.name}(${r})`}return t.toolCall.function.name}createSyntheticError(t,o){let n=this.erroredToolDescription,r=o==="user_interrupted"?"User rejected tool use":o==="discarded"?"Streaming fallback - tool execution discarded":n?`Cancelled: parallel tool call ${n} errored`:"Cancelled: parallel tool call errored";return{callId:t.id,toolName:t.toolCall.function.name,ok:!1,error:r,message:Q(t.id,{ok:!1,error:r})}}async executeTool(t){t.status="executing";let n=(async()=>{let r=this.getAbortReason();if(r){t.results.push(this.createSyntheticError(t,r)),t.status="completed";return}let{toolInvoker:i,hooks:a,sessionId:s,turnId:u,log:g}=this.config,p=t.toolCall.function.name,m=!1,b=t.toolCall.function.arguments;if(a)try{let y=await a.invoke("tool.before_invoke",{sessionId:s,turnId:u,callId:t.id,toolName:p,arguments:xo(b)});if(y.action==="abort"){let x=y.reason??"blocked by policy";g.info(`tool ${p} blocked: ${x}`),t.results.push({callId:t.id,toolName:p,ok:!1,error:x,blocked:!0,blockReason:x,message:Q(t.id,{ok:!1,error:x})}),t.status="completed";return}y.action==="continue"&&y.context?.arguments&&(b=JSON.stringify(y.context.arguments))}catch{}let f=await i.invoke(u,p,b,this.siblingAbortController.signal),k=this.getAbortReason();if(k&&!m){t.results.push(this.createSyntheticError(t,k)),t.status="completed";return}let T=!f.error,h=f.result;T&&h&&h.length>5e4&&(h=await $t(h,t.id,s));let A=Q(t.id,{ok:T,payload:h,error:f.error});T||(m=!0,So.has(p)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(t),this.siblingAbortController.abort("sibling_error"))),a?.invoke(T?"tool.after_invoke":"tool.invoke_failed",{sessionId:s,turnId:u,callId:t.id,toolName:p,ok:T,...f.error?{error:f.error}:{}}).catch(()=>{}),t.results.push({callId:t.id,toolName:p,ok:T,error:f.error,message:A}),t.status="completed"})();t.promise=n,n.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded){for(let t of this.tools)if(t.status!=="yielded"){if(t.status==="completed"&&t.results.length>0){t.status="yielded";for(let o of t.results)yield o}else if(t.status==="executing"&&!t.isConcurrencySafe)break}}}async*getRemainingResults(){if(!this.discarded){for(;this.hasUnfinishedTools();){await this.processQueue();for(let t of this.getCompletedResults())yield t;if(this.hasExecutingTools()&&!this.hasCompletedResults()){let t=this.tools.filter(n=>n.status==="executing"&&n.promise).map(n=>n.promise),o=new Promise(n=>{this.progressResolve=n});t.length>0&&await Promise.race([...t,o])}}for(let t of this.getCompletedResults())yield t}}hasCompletedResults(){return this.tools.some(t=>t.status==="completed")}hasExecutingTools(){return this.tools.some(t=>t.status==="executing")}hasUnfinishedTools(){return this.tools.some(t=>t.status!=="yielded")}};function xo(e){try{return JSON.parse(e)}catch{return}}import{readFile as di}from"node:fs/promises";function Ye(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function Ge(e){let t=0;for(let o of e)t+=Ye(o);return t}var We={"deepseek-chat":64e3,"deepseek-reasoner":64e3,"deepseek-v4-flash":64e3,"gpt-4o":128e3,"gpt-4o-mini":128e3,"claude-sonnet-4-20250514":2e5,"claude-3-5-haiku-20241022":2e5,"gemini-2.0-flash":1e6,"gemini-2.5-flash-preview-05-20":1e6};function Ro(e){if(!e)return 128e3;if(e in We)return We[e];let t=e.toLowerCase();for(let[o,n]of Object.entries(We))if(t.startsWith(o.toLowerCase()))return n;return 128e3}var _o=8e3;var vo=new ne(200);var pi=new oe;function Ao(){return ke(new te(_o),new j(20,Ye),new ee(Ye))}var Eo=null;function Ut(e,t){let o=t?.budget??Se({modelContextWindow:Ro(t?.model)}),r=(t?.pipeline??Ao()).compress(e,o);if(r.droppedCount>0){let i=Ge(e),a=Ge(r.messages);vo.record({timestamp:Date.now(),strategy:r.strategy,tokensBefore:i,tokensAfter:a,droppedCount:r.droppedCount,latencyMs:r.metrics?.latencyMs??0,usedLlm:!1,cacheInvalidated:r.metrics?.cacheInvalidated??!1,tier:xe(i,o)})}return r.droppedCount>0&&Eo?.(r.droppedCount,Ge(r.messages)),r}function zt(e,t,o){let n=o-t;return`[Budget] ${Math.round(e)}% used (${t.toLocaleString()} / ${o.toLocaleString()} tokens). ${n.toLocaleString()} tokens remaining. `+(e>=90?"Wrap up your current task \u2014 you are near the token limit.":"Continue working \u2014 do not summarize prematurely.")}function No(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.round(e),100):Ct}function qt(e){let t=e.message.toLowerCase();return e.status===413||t.includes("prompt_too_long")||t.includes("context_length_exceeded")||t.includes("maximum context length")}function Do(e){return e==="length"||e==="max_tokens"}function Gt(e){let t=e.message.toLowerCase();return(t.includes("image")||t.includes("media")||t.includes("file too large")||t.includes("payload too large"))&&(e.status===413||t.includes("too large")||t.includes("size"))}function Fo(e){let t=e.headers;if(!t)return null;let o=t["retry-after"]??t["Retry-After"];if(!o)return null;let n=parseInt(o,10);return!isNaN(n)&&n>0?n*1e3:null}function $o(e){if(e.status!==400)return null;let t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!t?.[1]||!t?.[3])return null;let o=parseInt(t[1],10),n=parseInt(t[3],10);if(isNaN(o)||isNaN(n))return null;let r=n-o-1e3;return r>=3e3?r:null}function Bo(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}async function*Wt(e,t,o,n){let{turnId:r,sessionId:i,messages:a,tools:s,model:u,apiKey:g,temperature:p,hooks:m,signal:b}=e,f={sessionId:i,turnId:r},k=e.maxTurns??0,T=e.querySource,{resolveToolEligibility:h}=await Promise.resolve().then(()=>(Ht(),jt)),A=h(s,e.toolEligibilityContext),y=A.eligibleTools;for(let v of A.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:v.toolName,reason:"blocked-by-policy"};if(!y.length){yield*Uo(r,u,a,g,p,b,t,n);return}let x=No(e.maxRounds),E={contextWindowTokens:e.contextWindowTokens??kt,responseBufferTokens:St,maxOutputTokens:e.maxOutputTokens??xt,abortSignal:b,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},H=!1,fe=null,N=(e.parentDepth??0)+1,Y=new Set,I=0,se=y,ie,c={messages:[...a],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Fe(E),reactiveCompactState:je(),toolLoopState:pe({maxRounds:x,replayMessages:[...a]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{prompt:0,completion:0},collapseStore:_e(),currentModel:u,consecutive529Errors:0,stopHookActive:void 0,snipRemovedIds:new Set,contentReplacementState:Ot()};for(;;){let{messages:v,maxOutputTokensRecoveryCount:K,hasAttemptedReactiveCompact:jo,maxOutputTokensOverride:Ke,turnCount:X,guardState:R,reactiveCompactState:L,collapseStore:ye}=c,{toolLoopState:w}=c;if(ie){try{let l=await ie;l&&(yield{type:"tool_use_summary",turnId:r,summary:l})}catch{}ie=void 0}if(e.refreshTools&&X>1){let l=e.refreshTools();l!==se&&(se=l,n.debug(`tools refreshed: ${l.length} tools`))}if(ze(R,E)){n.info(`turn aborted by guard at turn ${X}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED"};return}let F=$e(R,E);if(F.level==="blocking"){F.reason==="prompt_too_long"&&G(L)&&(L.attemptedThisTurn=!0,R.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${F.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),n.info(`token budget blocking (${F.reason}), ending tool loop`);break}F.level==="warning"&&n.info(`token budget warning: ${F.usagePercent}% used, ${F.remainingTokens} remaining`);let _;{let l=await Bt(v,c.contentReplacementState,i);_=l.messages,l.newlyReplacedCount>0&&(n.info(`tool-result-budget: persisted ${l.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:r,action:"tool_result_budget",detail:`${l.newlyReplacedCount} persisted`})}{let l=Re(_,c.snipRemovedIds);_=l.messages,l.removedCount>0&&(n.info(`snip: removed ${l.removedCount} messages, freed ~${l.tokensFreed} tokens`),yield{type:"recovery",turnId:r,action:"snip",detail:`${l.removedCount} messages`})}{let d=new j().compress(_,0);d.droppedCount>0&&(_=d.messages,n.info(`microcompact: cleared ${d.droppedCount} old tool results`))}if(_=ve(_,ye).messages,R.promptTokens>0){let l=Ut(_,{budget:E.contextWindowTokens*.75,model:c.currentModel});l.droppedCount>0&&(_=l.messages,n.info(`autocompact: ${l.strategy}, dropped ${l.droppedCount}`),yield{type:"recovery",turnId:r,action:"autocompact",detail:`${l.strategy}: ${l.droppedCount} dropped`},c.hasAttemptedReactiveCompact=!1,m?.invoke("context.after_compact",{...f,removedCount:l.droppedCount}).catch(()=>{}))}_=Bo(_);let ae=Ee({tools:se,toolChoice:e.toolChoice??"auto"}),V=pe({maxRounds:x,replayMessages:_,lastStopReason:w.lastStopReason,options:{stopReason:w.lastStopReason}}),Xe=ae.extraSystemPrompt?[{role:"system",content:ae.extraSystemPrompt},...V.state.replayMessages]:V.state.replayMessages;w=V.state,V.recoveryActions.length>0&&n.debug(`tool loop recovery: ${V.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),n.debug(`turn ${X}, messages: ${Xe.length}`),m?.invoke("turn.before_inference",{...f,model:c.currentModel}).catch(()=>{});let le=!1,Ve=[],Je=new Map,Qe="stop",D,C=null,ce=!1;try{for await(let l of t.stream({model:c.currentModel,messages:Xe,tools:ae.tools,toolChoice:ae.normalizedToolChoice??"auto",temperature:p,maxTokens:(Ke??R.currentMaxOutputTokens)||void 0},g,b))switch(l.type){case"delta":Ve.push(l.text),le||(yield{type:"delta",turnId:r,text:l.text});break;case"tool_call_delta":le=!0,Tt(Je,l);break;case"reasoning_delta":break;case"usage":D={prompt:l.promptTokens,completion:l.completionTokens,reasoning:l.reasoningTokens};break;case"done":Qe=l.finishReason;break}if(le||m?.invoke("turn.after_inference",{...f,model:c.currentModel}).catch(()=>{}),e.postSamplingHooks&&e.postSamplingHooks.length>0){let l=c.currentModel;for(let d of e.postSamplingHooks)try{d({messages:[..._],model:l,sessionId:i})}catch{}}}catch(l){if(l instanceof re&&e.fallbackModel){n.info(`model fallback triggered: ${l.originalModel} \u2192 ${l.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`${l.originalModel} \u2192 ${l.fallbackModel}`},c={...c,currentModel:l.fallbackModel,consecutive529Errors:0,transition:void 0};continue}let d=l instanceof Error?l.message:String(l),S=typeof l?.status=="number"?l.status:void 0;if(!S&&d&&(d.includes("ECONNRESET")||d.includes("EPIPE"))){n.info(`stale connection (${d.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:r,action:"stale_connection_retry",detail:d.slice(0,80)},c={...c,transition:void 0};continue}let O=$o({status:S,message:d});if(O!==null){n.info(`max_tokens overflow: adjusting to ${O}`),R.currentMaxOutputTokens=O,c={...c,maxOutputTokensOverride:O,transition:void 0};continue}if(Ne(S)){if(c.consecutive529Errors++,c.consecutive529Errors>=Et&&e.fallbackModel&&c.currentModel!==e.fallbackModel){n.info(`529 \xD7 ${c.consecutive529Errors}: triggering fallback to ${e.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`529 \xD7 ${c.consecutive529Errors}`},c={...c,currentModel:e.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(De()){let $=me(c.consecutive529Errors);n.info(`persistent retry: waiting ${$}ms (attempt ${c.consecutive529Errors})`);let P=$;for(;P>0;){if(b?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED"};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(P/1e3)}s (${S})`};let q=Math.min(P,At);await new Promise(Vt=>setTimeout(Vt,q)),P-=q}c={...c,transition:void 0};continue}if(Pe(T)){let P=Fo({status:S,message:d})??me(c.consecutive529Errors);n.info(`transient ${S}: retry in ${P}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${S} retry in ${P}ms`},await new Promise(q=>setTimeout(q,P)),c={...c,transition:void 0};continue}n.info(`background source ${T}: not retrying ${S}`)}C={status:S,message:d}}if(C&&m?.invoke("turn.after_inference",{...f,model:c.currentModel,response:{error:C.message}}).catch(()=>{}),C)if(qt(C))ce=!0,n.info(`withheld prompt_too_long error (status=${C.status})`);else if(Gt(C))ce=!0,n.info(`withheld media_size error (status=${C.status})`);else{let l=Be({status:C.status??500,message:C.message},R,E);if(l.action==="reactive_compact"&&G(L)&&(L.attemptedThisTurn=!0,R.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${C.status??500}: ${C.message}`}),l.action==="retry"){yield{type:"recovery",turnId:r,action:"retry",detail:l.reason},c={...c,transition:void 0};continue}let d=Z(C.status,C.message);m?.invoke("stop.failure",{sessionId:i,reason:d,error:C.message}).catch(()=>{}),yield{type:"error",turnId:r,error:C.message,code:d};return}D&&(c.totalUsage.prompt+=D.prompt,c.totalUsage.completion+=D.completion,D.reasoning&&(c.totalUsage.reasoning=(c.totalUsage.reasoning??0)+D.reasoning)),D?.prompt&&(R.promptTokens=D.prompt),c.finalText=Ve.join("");let M=[...Je.values()].map(l=>({id:l.id||`tc_${r}_${X}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(fe&&M.length>0){let l=ht(M,fe);l.denied.length>0&&n.info(`sidechain policy denied: ${l.denied.map(d=>`${d.toolCall.function.name} (${d.reason})`).join(", ")}`),M=l.allowed}if(M.length===0&&!le){if(ce&&C&&qt(C)){if(c.transition?.reason!=="collapse_drain_retry"){let l=Ae(_,ye);if(l.committed>0){n.info(`collapse drain: committed ${l.committed} stages`),yield{type:"recovery",turnId:r,action:"collapse_drain",detail:`${l.committed} stages committed`},c={...c,messages:l.messages,transition:{reason:"collapse_drain_retry",committed:l.committed}};continue}}if(G(L)){L.attemptedThisTurn=!0,R.hasAttemptedReactiveCompact=!0,n.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"withheld prompt_too_long"},c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld 413: recovery exhausted, surfacing error"),m?.invoke("stop.failure",{sessionId:i,reason:"prompt_too_long",error:C.message}).catch(()=>{}),yield{type:"error",turnId:r,error:C.message,code:"PROMPT_TOO_LONG"};return}if(ce&&C&&Gt(C)){if(G(L)){L.attemptedThisTurn=!0,R.hasAttemptedReactiveCompact=!0,n.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"media error strip-retry"},c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld media error: recovery exhausted"),m?.invoke("stop.failure",{sessionId:i,reason:"media_error",error:C.message}).catch(()=>{}),yield{type:"error",turnId:r,error:C.message,code:"IMAGE_ERROR"};return}if(Do(Qe)){R.consecutiveTruncations+=1;let l=e.modelMaxOutputTokens??Rt,d=Ue(R,E,l);if(d.shouldEscalate&&Ke===void 0){R.currentMaxOutputTokens=d.newMax,n.info(`max_output_tokens escalate: ${d.newMax} tokens`),yield{type:"recovery",turnId:r,action:"output_escalation",detail:`${d.newMax} tokens`},c={...c,maxOutputTokensOverride:vt,transition:{reason:"max_output_tokens_escalate"}};continue}if(K<_t){let S={role:"user",content:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};n.info(`max_output_tokens recovery #${K+1}`),yield{type:"recovery",turnId:r,action:"max_output_tokens_recovery",detail:`attempt ${K+1}`},c={...c,messages:[..._,S],maxOutputTokensRecoveryCount:K+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:K+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else R.consecutiveTruncations=0;if(w=de(w,{replayMessages:v,lastStopReason:"completed"}),m){let l=await m.invoke("stop",{sessionId:i,reason:"completed"});if(l.action==="prevent"){n.info(`stop hook prevented continuation: ${l.reason??"no reason"}`),yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}if(l.action==="abort"){let d=l.reason??"Stop hook requested continuation";n.info(`stop hook blocking: ${d}`);let S={role:"user",content:d};c={...c,messages:[...v,{role:"assistant",content:c.finalText},S],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(e.tokenBudget&&e.tokenBudget>0){let l=c.totalUsage.prompt+c.totalUsage.completion+(c.totalUsage.reasoning??0),d=l/e.tokenBudget*100;if(d<90){let S={role:"user",content:zt(d,l,e.tokenBudget)};n.info(`token budget continuation: ${Math.round(d)}% used`),yield{type:"recovery",turnId:r,action:"budget_continuation",detail:`${Math.round(d)}% used`},c={...c,messages:[...v,{role:"assistant",content:c.finalText},S],transition:{reason:"token_budget_continuation"}};continue}}if(H&&(yield{type:"sidechain_completed",turnId:r,depth:N,toolCallCount:I}),I>0){let l={ok:!0,toolCallCount:I,distinctToolCount:Y.size,multiStep:I>=2,hasSidechain:H,feedback:null,existingSkillName:null},d=ue(l,{tools:[...Y]});d&&(yield{type:"skill_instruction",turnId:r,instruction:d})}yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}for(let l of M){let d=l.function.arguments,S=se.find(O=>O.function.name===l.function.name);if(S?.backfillObservableInput)try{let O=JSON.parse(l.function.arguments),$={...O};S.backfillObservableInput($),Object.keys($).some(q=>!(q in O))&&(d=JSON.stringify($))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:d}}if(v.push(Te(M)),!H){if(N>W){yield{type:"error",turnId:r,error:`sidechain depth ${N} exceeds max ${W}`,code:"SIDECHAIN_DEPTH_LIMIT"};return}H=!0;let l=N>=W?"leaf":"orchestrator";yield{type:"sidechain_started",turnId:r,depth:N,role:l},fe=yt({type:e.sidechainType??"code-repair",depth:N,maxDepth:W,role:N>=W?"leaf":"orchestrator",toolNames:s.map(d=>d.function.name)})}w=Oe(w,{replayMessages:v,pendingToolCallIds:M.map(l=>l.id),completedToolCallIds:w.completedToolCallIds,lastStopReason:"tool_calls"});let Ze=[];try{let l=new ge({toolInvoker:o,hooks:m,sessionId:i,turnId:r,log:n,signal:b,maxConcurrentTools:e?.maxConcurrentTools});for(let d of M)l.addTool(d);for await(let d of l.getRemainingResults())d.blocked&&(yield{type:"tool_blocked",turnId:r,callId:d.callId,name:d.toolName,reason:d.blockReason??"blocked"}),v.push(d.message),Ze.push(d.callId),Y.add(d.toolName),I++,yield{type:"tool_result",turnId:r,callId:d.callId,name:d.toolName,ok:d.ok,error:d.error}}catch(l){let d=l instanceof Error?l.message:String(l);yield{type:"error",turnId:r,error:d,code:"TOOL_EXECUTION_ERROR"};return}if(w=de(w,{replayMessages:v,completedToolCallIds:[...w.completedToolCallIds,...Ze],lastStopReason:"tool_calls"}),e.generateToolUseSummary&&M.length>0){let l=M.map(d=>({name:d.function.name,arguments:d.function.arguments}));ie=e.generateToolUseSummary(l).catch(()=>null)}let et=v.slice(-M.length),Xt=et.length>0&&et.every(l=>{let d=l?.content;if(typeof d!="string")return!1;try{return JSON.parse(d)?.ok===!1}catch{return!1}}),J=c.consecutiveFailedRounds;if(Xt){if(J+=1,J>=bt&&c.finalText){n.info(`early exit: ${J} consecutive failed rounds, returning partial response`),yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}}else J=0;let he=X+1;if(k>0&&he>k){if(n.info(`max turns reached (${k}), completing`),m){let l=await m.invoke("stop",{sessionId:i,reason:"max_turns"});if(l.action==="abort"){let d=l.reason??"Stop hook requested continuation after max_turns";c={...c,messages:[...v,{role:"assistant",content:c.finalText},{role:"user",content:d}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}if(he>x){if(c.finalText){if(n.info(`tool loop budget exhausted (${x} rounds), returning partial response`),H&&(yield{type:"sidechain_completed",turnId:r,depth:N,toolCallCount:I}),I>0){let l={ok:!0,toolCallCount:I,distinctToolCount:Y.size,multiStep:I>=2,hasSidechain:H,feedback:null,existingSkillName:null},d=ue(l,{tools:[...Y]});d&&(yield{type:"skill_instruction",turnId:r,instruction:d})}yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}yield{type:"error",turnId:r,error:`Tool loop exceeded budget (${x} rounds)`,code:"TOOL_LOOP_LIMIT"};return}c={messages:v,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:he,transition:{reason:"next_turn"},guardState:R,reactiveCompactState:L,toolLoopState:w,consecutiveFailedRounds:J,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:ye,currentModel:c.currentModel,consecutive529Errors:0,stopHookActive:c.stopHookActive,snipRemovedIds:c.snipRemovedIds,contentReplacementState:c.contentReplacementState}}}async function*Uo(e,t,o,n,r,i,a,s){let u=[],g;s.debug(`single LLM round, messages: ${o.length}`);for await(let p of a.stream({model:t,messages:o,temperature:r},n,i))switch(p.type){case"delta":u.push(p.text),yield{type:"delta",turnId:e,text:p.text};break;case"usage":g={prompt:p.promptTokens,completion:p.completionTokens,reasoning:p.reasoningTokens};break;case"done":break}yield{type:"end",turnId:e,content:u.join(""),usage:g??{prompt:0,completion:0},model:t}}var Kt=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;constructor(t){this.transport=t.llmTransport,this.apiKey=t.apiKey,this.toolInvoker=t.toolInvoker,this.log=t.log,this.hooks=t.hooks,this.maxRounds=Math.min(t.maxRounds??25,100)}async*run(t,o){let{turnId:n,messages:r,tools:i,systemPrompt:a,config:s}=t,u={sessionId:t.sessionId,turnId:n};yield{type:"start",turnId:n},this.hooks?.invoke("turn.submitted",{...u,prompt:r[r.length-1]?.content??void 0}).catch(()=>{});let g=Le(r),p=[];if(a&&p.push({role:"system",content:a}),p.push(...g),this.hooks){let f=g.filter(T=>T.role==="user").pop(),k=typeof f?.content=="string"?f.content.slice(0,500):void 0;if(k)try{let T=await this.hooks.invoke("memory.before_recall",{sessionId:t.sessionId,turnId:n,query:k}),h=T?.context?.recalledMemories;if(h&&h.length>0){let A=h.map(y=>`- ${y.text}`).join(`
17
- `);p.splice(a?1:0,0,{role:"system",content:`[Recalled from long-term memory]
18
- ${A}`})}this.hooks.invoke("memory.after_recall",{sessionId:t.sessionId,turnId:n,blockCount:T?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let m=s?.model??"",b=Math.min(s?.maxRounds??this.maxRounds,100);try{let f=s?.summaryModel?async h=>{try{let A=h.map(E=>`${E.name}(${E.arguments.slice(0,200)})`).join(", "),y=this.transport.stream({model:s.summaryModel,messages:[{role:"system",content:"Summarize the tool usage in ~30 chars, git-commit-subject style. Reply with ONLY the summary, nothing else."},{role:"user",content:A}],tools:[],maxTokens:60},s.apiKey??this.apiKey),x="";for await(let E of y)E.type==="delta"&&(x+=E.text);return x.trim()||null}catch{return null}}:void 0,k={turnId:n,sessionId:t.sessionId,messages:p,tools:i,model:m,apiKey:s?.apiKey??this.apiKey,temperature:s?.temperature,maxRounds:b,contextWindowTokens:s?.contextWindowTokens,maxOutputTokens:s?.maxOutputTokens,modelMaxOutputTokens:s?.modelMaxOutputTokens,toolChoice:s?.toolChoice,parentDepth:s?.parentDepth,sidechainType:s?.sidechainType,hooks:this.hooks,fallbackModel:s?.fallbackModel,maxTurns:s?.maxTurns,tokenBudget:s?.tokenBudget,maxConcurrentTools:s?.maxConcurrentTools,generateToolUseSummary:f,signal:o},T;for await(let h of Wt(k,this.transport,this.toolInvoker,this.log))T=h,yield h;T?.type==="end"?this.hooks?.invoke("turn.completed",{...u}).catch(()=>{}):T?.type==="error"&&this.hooks?.invoke("turn.failed",{...u,code:T.code,error:T.error}).catch(()=>{})}catch(f){if(o?.aborted)this.hooks?.invoke("turn.failed",{...u,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED"};else{let k=f instanceof Error?f.message:String(f),T=typeof f?.status=="number"?f.status:void 0,h=Z(T,k),A=be(h);this.log.error(`turn ${n} error [${h}, retryable=${A.retryable}]: ${k}`),this.hooks?.invoke("turn.failed",{...u,code:h,error:k}).catch(()=>{}),yield{type:"error",turnId:n,error:k,code:h}}}}};export{Kt as Agent};
15
+ `,t+=Zo,t}async function It(e,t,n,o=_t){if(e.length<=o||Et(e))return e;let r=await Mt(e,t,n);return r?wt(r):e.slice(0,o)+`
16
+ ...[truncated ${e.length-o} chars]`}function nn(e){let t=[],n=[];for(let o of e)o.role==="tool"&&typeof o.content=="string"&&o.tool_call_id?Et(o.content)||n.push({toolCallId:o.tool_call_id,content:o.content,size:o.content.length}):o.role==="assistant"&&n.length>0&&(t.push(n),n=[]);return n.length>0&&t.push(n),t}function rn(e,t){let n=[],o=[],r=[];for(let i of e){let l=t.replacements.get(i.toolCallId);l!==void 0?n.push({...i,replacement:l}):t.seenIds.has(i.toolCallId)?o.push(i):r.push(i)}return{mustReapply:n,frozen:o,fresh:r}}function sn(e,t,n){let o=[...e].sort((l,s)=>s.size-l.size),r=[],i=t+e.reduce((l,s)=>l+s.size,0);for(let l of o){if(i<=n)break;r.push(l),i-=l.size}return r}async function Lt(e,t,n,o=Rt){let r=nn(e);if(r.length===0)return{messages:e,newlyReplacedCount:0};let i=new Map,l=[];for(let p of r){let{mustReapply:m,frozen:k,fresh:y}=rn(p,t);for(let T of m)i.set(T.toolCallId,T.replacement);if(y.length===0){for(let T of p)t.seenIds.add(T.toolCallId);continue}let _=k.reduce((T,R)=>T+R.size,0),C=y.reduce((T,R)=>T+R.size,0),h=_+C>o?sn(y,_,o):[],A=new Set(h.map(T=>T.toolCallId));for(let T of p)A.has(T.toolCallId)||t.seenIds.add(T.toolCallId);h.length>0&&l.push(...h)}if(i.size===0&&l.length===0)return{messages:e,newlyReplacedCount:0};let s=await Promise.all(l.map(async p=>{let m=await Mt(p.content,p.toolCallId,n);return{candidate:p,result:m}})),d=0;for(let{candidate:p,result:m}of s){if(t.seenIds.add(p.toolCallId),!m)continue;let k=wt(m);i.set(p.toolCallId,k),t.replacements.set(p.toolCallId,k),d++}return i.size===0?{messages:e,newlyReplacedCount:0}:{messages:e.map(p=>{if(p.role!=="tool"||!p.tool_call_id)return p;let m=i.get(p.tool_call_id);return m===void 0?p:{...p,content:m}}),newlyReplacedCount:d}}var an=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),ln=new Set(["bash","execute_command","Bash","shell"]),pe=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(t){this.config=t,this.concurrencySafe=t.concurrencySafeTools??an,this.siblingAbortController=new AbortController,t.signal&&t.signal.addEventListener("abort",()=>{this.siblingAbortController.abort("parent_abort")},{once:!0})}discard(){this.discarded=!0}addTool(t){let n=this.concurrencySafe.has(t.function.name);this.tools.push({id:t.id,toolCall:t,status:"queued",isConcurrencySafe:n,results:[],pendingProgress:[]}),this.processQueue()}canExecuteTool(t){let n=this.tools.filter(r=>r.status==="executing"),o=this.config.maxConcurrentTools;return o&&o>0&&n.length>=o?!1:n.length===0||t&&n.every(r=>r.isConcurrencySafe)}async processQueue(){for(let t of this.tools)if(t.status==="queued"){if(this.canExecuteTool(t.isConcurrencySafe))await this.executeTool(t);else if(!t.isConcurrencySafe)break}}getAbortReason(){return this.discarded?"discarded":this.hasErrored?"sibling_error":this.config.signal?.aborted?"user_interrupted":null}getToolDescription(t){let n;try{n=JSON.parse(t.toolCall.function.arguments)}catch{}let o=n?.command??n?.file_path??n?.pattern??"";if(typeof o=="string"&&o.length>0){let r=o.length>40?o.slice(0,40)+"\u2026":o;return`${t.toolCall.function.name}(${r})`}return t.toolCall.function.name}createSyntheticError(t,n){let o=this.erroredToolDescription,r=n==="user_interrupted"?"User rejected tool use":n==="discarded"?"Streaming fallback - tool execution discarded":o?`Cancelled: parallel tool call ${o} errored`:"Cancelled: parallel tool call errored";return{callId:t.id,toolName:t.toolCall.function.name,ok:!1,error:r,message:J(t.id,{ok:!1,error:r})}}async executeTool(t){t.status="executing";let o=(async()=>{let r=this.getAbortReason();if(r){t.results.push(this.createSyntheticError(t,r)),t.status="completed";return}let{toolInvoker:i,hooks:l,sessionId:s,turnId:d,log:g}=this.config,p=t.toolCall.function.name,m=!1,k=t.toolCall.function.arguments;if(l)try{let T=await l.invoke("tool.before_invoke",{sessionId:s,turnId:d,callId:t.id,toolName:p,arguments:cn(k)});if(T.action==="abort"){let R=T.reason??"blocked by policy";g.info(`tool ${p} blocked: ${R}`),t.results.push({callId:t.id,toolName:p,ok:!1,error:R,blocked:!0,blockReason:R,message:J(t.id,{ok:!1,error:R})}),t.status="completed";return}T.action==="continue"&&T.context?.arguments&&(k=JSON.stringify(T.context.arguments))}catch{}let y=await i.invoke(d,p,k,this.siblingAbortController.signal),_=this.getAbortReason();if(_&&!m){t.results.push(this.createSyntheticError(t,_)),t.status="completed";return}let C=!y.error,h=y.result;C&&h&&h.length>5e4&&(h=await It(h,t.id,s));let A=J(t.id,{ok:C,payload:h,error:y.error});C||(m=!0,ln.has(p)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(t),this.siblingAbortController.abort("sibling_error"))),l?.invoke(C?"tool.after_invoke":"tool.invoke_failed",{sessionId:s,turnId:d,callId:t.id,toolName:p,ok:C,...y.error?{error:y.error}:{}}).catch(()=>{}),t.results.push({callId:t.id,toolName:p,ok:C,error:y.error,message:A}),t.status="completed"})();t.promise=o,o.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded){for(let t of this.tools)if(t.status!=="yielded"){if(t.status==="completed"&&t.results.length>0){t.status="yielded";for(let n of t.results)yield n}else if(t.status==="executing"&&!t.isConcurrencySafe)break}}}async*getRemainingResults(){if(!this.discarded){for(;this.hasUnfinishedTools();){await this.processQueue();for(let t of this.getCompletedResults())yield t;if(this.hasExecutingTools()&&!this.hasCompletedResults()){let t=this.tools.filter(o=>o.status==="executing"&&o.promise).map(o=>o.promise),n=new Promise(o=>{this.progressResolve=o});t.length>0&&await Promise.race([...t,n])}}for(let t of this.getCompletedResults())yield t}}hasCompletedResults(){return this.tools.some(t=>t.status==="completed")}hasExecutingTools(){return this.tools.some(t=>t.status==="executing")}hasUnfinishedTools(){return this.tools.some(t=>t.status!=="yielded")}};function cn(e){try{return JSON.parse(e)}catch{return}}import{readFile as zr}from"node:fs/promises";function Ge(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function je(e){let t=0;for(let n of e)t+=Ge(n);return t}var ze={"deepseek-chat":64e3,"deepseek-reasoner":64e3,"deepseek-v4-flash":64e3,"gpt-4o":128e3,"gpt-4o-mini":128e3,"claude-sonnet-4-20250514":2e5,"claude-3-5-haiku-20241022":2e5,"gemini-2.0-flash":1e6,"gemini-2.5-flash-preview-05-20":1e6};function un(e){if(!e)return 128e3;if(e in ze)return ze[e];let t=e.toLowerCase();for(let[n,o]of Object.entries(ze))if(t.startsWith(n.toLowerCase()))return o;return 128e3}var dn=8e3;var pn=new Z(200);var Gr=new ee;function mn(){return he(new Q(dn),new j(20,Ge),new V(Ge))}var gn=null;function Ot(e,t){let n=t?.budget??Ce({modelContextWindow:un(t?.model)}),r=(t?.pipeline??mn()).compress(e,n);if(r.droppedCount>0){let i=je(e),l=je(r.messages);pn.record({timestamp:Date.now(),strategy:r.strategy,tokensBefore:i,tokensAfter:l,droppedCount:r.droppedCount,latencyMs:r.metrics?.latencyMs??0,usedLlm:!1,cacheInvalidated:r.metrics?.cacheInvalidated??!1,tier:be(i,n)})}return r.droppedCount>0&&gn?.(r.droppedCount,je(r.messages)),r}function Pt(e,t,n){let o=n-t;return`[Budget] ${Math.round(e)}% used (${t.toLocaleString()} / ${n.toLocaleString()} tokens). ${o.toLocaleString()} tokens remaining. `+(e>=90?"Wrap up your current task \u2014 you are near the token limit.":"Continue working \u2014 do not summarize prematurely.")}function kn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.round(e),100):pt}function Dt(e){let t=e.message.toLowerCase();return e.status===413||t.includes("prompt_too_long")||t.includes("context_length_exceeded")||t.includes("maximum context length")}function _n(e){return e==="length"||e==="max_tokens"}function Bt(e){let t=e.message.toLowerCase();return(t.includes("image")||t.includes("media")||t.includes("file too large")||t.includes("payload too large"))&&(e.status===413||t.includes("too large")||t.includes("size"))}function Rn(e){let t=e.headers;if(!t)return null;let n=t["retry-after"]??t["Retry-After"];if(!n)return null;let o=parseInt(n,10);return!isNaN(o)&&o>0?o*1e3:null}function xn(e){if(e.status!==400)return null;let t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!t?.[1]||!t?.[3])return null;let n=parseInt(t[1],10),o=parseInt(t[3],10);if(isNaN(n)||isNaN(o))return null;let r=o-n-1e3;return r>=3e3?r:null}function Sn(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}async function*$t(e,t,n,o){let{turnId:r,sessionId:i,messages:l,tools:s,model:d,apiKey:g,temperature:p,hooks:m,signal:k}=e,y={sessionId:i,turnId:r},_=e.maxTurns??0,C=e.querySource,{resolveToolEligibility:h}=await Promise.resolve().then(()=>(Ft(),Nt)),A=h(s,e.toolEligibilityContext),T=A.eligibleTools;for(let v of A.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:v.toolName,reason:"blocked-by-policy"};if(!T.length){yield*vn(r,d,l,g,p,k,t,o);return}let R=kn(e.maxRounds),E={contextWindowTokens:e.contextWindowTokens??gt,responseBufferTokens:ft,maxOutputTokens:e.maxOutputTokens??yt,abortSignal:k,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},q=new Set,F=0,ne=T,re,c={messages:[...l],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Pe(E),reactiveCompactState:$e(),toolLoopState:ue({maxRounds:R,replayMessages:[...l]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{prompt:0,completion:0},collapseStore:_e(),currentModel:d,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,snipRemovedIds:new Set,contentReplacementState:vt()};for(;;){let{messages:v,maxOutputTokensRecoveryCount:W,hasAttemptedReactiveCompact:En,maxOutputTokensOverride:He,turnCount:K,guardState:x,reactiveCompactState:L,collapseStore:me}=c,{toolLoopState:M}=c;if(re){try{let a=await re;a&&(yield{type:"tool_use_summary",turnId:r,summary:a})}catch{}re=void 0}if(e.refreshTools&&K>1){let a=e.refreshTools();a!==ne&&(ne=a,o.debug(`tools refreshed: ${a.length} tools`))}if(Be(x,E)){o.info(`turn aborted by guard at turn ${K}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED"};return}let D=Ne(x,E);if(D.level==="blocking"){D.reason==="prompt_too_long"&&H(L)&&(L.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${D.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),o.info(`token budget blocking (${D.reason}), ending tool loop`);break}D.level==="warning"&&o.info(`token budget warning: ${D.usagePercent}% used, ${D.remainingTokens} remaining`);let S;{let a=await Lt(v,c.contentReplacementState,i);S=a.messages,a.newlyReplacedCount>0&&(o.info(`tool-result-budget: persisted ${a.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:r,action:"tool_result_budget",detail:`${a.newlyReplacedCount} persisted`})}{let a=ke(S,c.snipRemovedIds);S=a.messages,a.removedCount>0&&(o.info(`snip: removed ${a.removedCount} messages, freed ~${a.tokensFreed} tokens`),yield{type:"recovery",turnId:r,action:"snip",detail:`${a.removedCount} messages`})}{let u=new j().compress(S,0);u.droppedCount>0&&(S=u.messages,o.info(`microcompact: cleared ${u.droppedCount} old tool results`))}if(S=Re(S,me).messages,x.promptTokens>0){let a=Ot(S,{budget:E.contextWindowTokens*.75,model:c.currentModel});a.droppedCount>0&&(S=a.messages,o.info(`autocompact: ${a.strategy}, dropped ${a.droppedCount}`),yield{type:"recovery",turnId:r,action:"autocompact",detail:`${a.strategy}: ${a.droppedCount} dropped`},c.hasAttemptedReactiveCompact=!1,m?.invoke("context.after_compact",{...y,removedCount:a.droppedCount}).catch(()=>{}))}S=Sn(S);let se=Se({tools:ne,toolChoice:e.toolChoice??"auto"}),X=ue({maxRounds:R,replayMessages:S,lastStopReason:M.lastStopReason,options:{stopReason:M.lastStopReason}}),qe=se.extraSystemPrompt?[{role:"system",content:se.extraSystemPrompt},...X.state.replayMessages]:X.state.replayMessages;M=X.state,X.recoveryActions.length>0&&o.debug(`tool loop recovery: ${X.recoveryActions.map(a=>a.detail??a.kind).join("; ")}`),o.debug(`turn ${K}, messages: ${qe.length}`),m?.invoke("turn.before_inference",{...y,model:c.currentModel}).catch(()=>{});let ie=!1,We=[],Ke=new Map,Xe="stop",P,f=null,ae=!1;try{for await(let a of t.stream({model:c.currentModel,messages:qe,tools:se.tools,toolChoice:se.normalizedToolChoice??"auto",temperature:p,maxTokens:(He??x.currentMaxOutputTokens)||void 0},g,k))switch(a.type){case"delta":We.push(a.text),ie||(yield{type:"delta",turnId:r,text:a.text});break;case"tool_call_delta":ie=!0,dt(Ke,a);break;case"reasoning_delta":break;case"usage":P={prompt:a.promptTokens,completion:a.completionTokens,reasoning:a.reasoningTokens};break;case"done":Xe=a.finishReason;break}if(ie||m?.invoke("turn.after_inference",{...y,model:c.currentModel}).catch(()=>{}),e.postSamplingHooks&&e.postSamplingHooks.length>0){let a=c.currentModel;for(let u of e.postSamplingHooks)try{u({messages:[...S],model:a,sessionId:i})}catch{}}}catch(a){if(a instanceof te&&e.fallbackModel){o.info(`model fallback triggered: ${a.originalModel} \u2192 ${a.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`${a.originalModel} \u2192 ${a.fallbackModel}`},c={...c,currentModel:a.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let u=a instanceof Error?a.message:String(a),b=typeof a?.status=="number"?a.status:void 0;if(!b&&u&&(u.includes("ECONNRESET")||u.includes("EPIPE"))){let I=(c.consecutiveApiRetries??0)+1;if(I>oe){o.info(`stale connection retry limit reached (${oe}), aborting`),yield{type:"error",turnId:r,error:u,code:"RETRIES_EXHAUSTED"};return}o.info(`stale connection (${u.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:r,action:"stale_connection_retry",detail:u.slice(0,80)},c={...c,consecutiveApiRetries:I,transition:void 0};continue}let w=xn({status:b,message:u});if(w!==null){o.info(`max_tokens overflow: adjusting to ${w}`),x.currentMaxOutputTokens=w,c={...c,maxOutputTokensOverride:w,transition:void 0};continue}if(Le(b)){if(c.consecutive529Errors++,c.consecutive529Errors>=kt&&e.fallbackModel&&c.currentModel!==e.fallbackModel){o.info(`529 \xD7 ${c.consecutive529Errors}: triggering fallback to ${e.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`529 \xD7 ${c.consecutive529Errors}`},c={...c,currentModel:e.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(Oe()){let I=de(c.consecutive529Errors);o.info(`persistent retry: waiting ${I}ms (attempt ${c.consecutive529Errors})`);let O=I;for(;O>0;){if(k?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED"};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(O/1e3)}s (${b})`};let z=Math.min(O,bt);await new Promise(Gt=>setTimeout(Gt,z)),O-=z}c={...c,transition:void 0};continue}if(Ie(C)){let O=Rn({status:b,message:u})??de(c.consecutive529Errors);o.info(`transient ${b}: retry in ${O}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${b} retry in ${O}ms`},await new Promise(z=>setTimeout(z,O)),c={...c,transition:void 0};continue}o.info(`background source ${C}: not retrying ${b}`)}f={status:b,message:u}}if(f&&m?.invoke("turn.after_inference",{...y,model:c.currentModel,response:{error:f.message}}).catch(()=>{}),f)if(Dt(f))ae=!0,o.info(`withheld prompt_too_long error (status=${f.status})`);else if(Bt(f))ae=!0,o.info(`withheld media_size error (status=${f.status})`);else{let a=Fe({status:f.status??500,message:f.message},x,E);if(a.action==="reactive_compact"&&H(L)&&(L.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${f.status??500}: ${f.message}`}),a.action==="retry"){let b=(c.consecutiveApiRetries??0)+1;if(b>oe){o.info(`API retry limit reached (${oe}), aborting`);let w=G(f.status,f.message);yield{type:"error",turnId:r,error:f.message,code:w};return}yield{type:"recovery",turnId:r,action:"retry",detail:a.reason},c={...c,consecutiveApiRetries:b,transition:void 0};continue}let u=G(f.status,f.message);m?.invoke("stop.failure",{sessionId:i,reason:u,error:f.message}).catch(()=>{}),yield{type:"error",turnId:r,error:f.message,code:u};return}P&&(c.totalUsage.prompt+=P.prompt,c.totalUsage.completion+=P.completion,P.reasoning&&(c.totalUsage.reasoning=(c.totalUsage.reasoning??0)+P.reasoning)),P?.prompt&&(x.promptTokens=P.prompt),c.finalText=We.join("");let N=[...Ke.values()].map(a=>({id:a.id||`tc_${r}_${K}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:a.name,arguments:a.arguments}}));if(N.length===0&&!ie){if(ae&&f&&Dt(f)){if(c.transition?.reason!=="collapse_drain_retry"){let a=xe(S,me);if(a.committed>0){o.info(`collapse drain: committed ${a.committed} stages`),yield{type:"recovery",turnId:r,action:"collapse_drain",detail:`${a.committed} stages committed`},c={...c,messages:a.messages,transition:{reason:"collapse_drain_retry",committed:a.committed}};continue}}if(H(L)){L.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"withheld prompt_too_long"},c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),m?.invoke("stop.failure",{sessionId:i,reason:"prompt_too_long",error:f.message}).catch(()=>{}),yield{type:"error",turnId:r,error:f.message,code:"PROMPT_TOO_LONG"};return}if(ae&&f&&Bt(f)){if(H(L)){L.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"media error strip-retry"},c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),m?.invoke("stop.failure",{sessionId:i,reason:"media_error",error:f.message}).catch(()=>{}),yield{type:"error",turnId:r,error:f.message,code:"IMAGE_ERROR"};return}if(_n(Xe)){x.consecutiveTruncations+=1;let a=e.modelMaxOutputTokens??Tt,u=De(x,E,a);if(u.shouldEscalate&&He===void 0){x.currentMaxOutputTokens=u.newMax,o.info(`max_output_tokens escalate: ${u.newMax} tokens`),yield{type:"recovery",turnId:r,action:"output_escalation",detail:`${u.newMax} tokens`},c={...c,maxOutputTokensOverride:Ct,transition:{reason:"max_output_tokens_escalate"}};continue}if(W<ht){let b={role:"user",content:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};o.info(`max_output_tokens recovery #${W+1}`),yield{type:"recovery",turnId:r,action:"max_output_tokens_recovery",detail:`attempt ${W+1}`},c={...c,messages:[...S,b],maxOutputTokensRecoveryCount:W+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:W+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else x.consecutiveTruncations=0;if(M=ce(M,{replayMessages:v,lastStopReason:"completed"}),m){let a=await m.invoke("stop",{sessionId:i,reason:"completed"});if(a.action==="prevent"){o.info(`stop hook prevented continuation: ${a.reason??"no reason"}`),yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}if(a.action==="abort"){let u=a.reason??"Stop hook requested continuation";o.info(`stop hook blocking: ${u}`);let b={role:"user",content:u};c={...c,messages:[...v,{role:"assistant",content:c.finalText},b],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(e.tokenBudget&&e.tokenBudget>0){let a=c.totalUsage.prompt+c.totalUsage.completion+(c.totalUsage.reasoning??0),u=a/e.tokenBudget*100;if(u<90){let b={role:"user",content:Pt(u,a,e.tokenBudget)};o.info(`token budget continuation: ${Math.round(u)}% used`),yield{type:"recovery",turnId:r,action:"budget_continuation",detail:`${Math.round(u)}% used`},c={...c,messages:[...v,{role:"assistant",content:c.finalText},b],transition:{reason:"token_budget_continuation"}};continue}}if(F>0){let a={ok:!0,toolCallCount:F,distinctToolCount:q.size,multiStep:F>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},u=le(a,{tools:[...q]});u&&(yield{type:"skill_instruction",turnId:r,instruction:u})}yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}for(let a of N){let u=a.function.arguments,b=ne.find(w=>w.function.name===a.function.name);if(b?.backfillObservableInput)try{let w=JSON.parse(a.function.arguments),I={...w};b.backfillObservableInput(I),Object.keys(I).some(z=>!(z in w))&&(u=JSON.stringify(I))}catch{}yield{type:"tool_call",turnId:r,callId:a.id,name:a.function.name,arguments:u}}v.push(fe(N)),M=we(M,{replayMessages:v,pendingToolCallIds:N.map(a=>a.id),completedToolCallIds:M.completedToolCallIds,lastStopReason:"tool_calls"});let Ye=[];try{let a=new pe({toolInvoker:n,hooks:m,sessionId:i,turnId:r,log:o,signal:k,maxConcurrentTools:e?.maxConcurrentTools});for(let u of N)a.addTool(u);for await(let u of a.getRemainingResults())u.blocked&&(yield{type:"tool_blocked",turnId:r,callId:u.callId,name:u.toolName,reason:u.blockReason??"blocked"}),v.push(u.message),Ye.push(u.callId),q.add(u.toolName),F++,yield{type:"tool_result",turnId:r,callId:u.callId,name:u.toolName,ok:u.ok,error:u.error}}catch(a){let u=a instanceof Error?a.message:String(a);yield{type:"error",turnId:r,error:u,code:"TOOL_EXECUTION_ERROR"};return}if(M=ce(M,{replayMessages:v,completedToolCallIds:[...M.completedToolCallIds,...Ye],lastStopReason:"tool_calls"}),e.generateToolUseSummary&&N.length>0){let a=N.map(u=>({name:u.function.name,arguments:u.function.arguments}));re=e.generateToolUseSummary(a).catch(()=>null)}let Je=v.slice(-N.length),zt=Je.length>0&&Je.every(a=>{let u=a?.content;if(typeof u!="string")return!1;try{return JSON.parse(u)?.ok===!1}catch{return!1}}),Y=c.consecutiveFailedRounds;if(zt){if(Y+=1,Y>=mt&&c.finalText){o.info(`early exit: ${Y} consecutive failed rounds, returning partial response`),yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}}else Y=0;let ge=K+1;if(_>0&&ge>_){if(o.info(`max turns reached (${_}), completing`),m){let a=await m.invoke("stop",{sessionId:i,reason:"max_turns"});if(a.action==="abort"){let u=a.reason??"Stop hook requested continuation after max_turns";c={...c,messages:[...v,{role:"assistant",content:c.finalText},{role:"user",content:u}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}if(ge>R){if(c.finalText){if(o.info(`tool loop budget exhausted (${R} rounds), returning partial response`),F>0){let a={ok:!0,toolCallCount:F,distinctToolCount:q.size,multiStep:F>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},u=le(a,{tools:[...q]});u&&(yield{type:"skill_instruction",turnId:r,instruction:u})}yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}yield{type:"error",turnId:r,error:`Tool loop exceeded budget (${R} rounds)`,code:"TOOL_LOOP_LIMIT"};return}c={messages:v,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:ge,transition:{reason:"next_turn"},guardState:x,reactiveCompactState:L,toolLoopState:M,consecutiveFailedRounds:Y,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:me,currentModel:c.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:c.stopHookActive,snipRemovedIds:c.snipRemovedIds,contentReplacementState:c.contentReplacementState}}}async function*vn(e,t,n,o,r,i,l,s){let d=[],g;s.debug(`single LLM round, messages: ${n.length}`);for await(let p of l.stream({model:t,messages:n,temperature:r},o,i))switch(p.type){case"delta":d.push(p.text),yield{type:"delta",turnId:e,text:p.text};break;case"usage":g={prompt:p.promptTokens,completion:p.completionTokens,reasoning:p.reasoningTokens};break;case"done":break}yield{type:"end",turnId:e,content:d.join(""),usage:g??{prompt:0,completion:0},model:t}}var jt=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;constructor(t){this.transport=t.llmTransport,this.apiKey=t.apiKey,this.toolInvoker=t.toolInvoker,this.log=t.log,this.hooks=t.hooks,this.maxRounds=Math.min(t.maxRounds??25,100)}async*run(t,n){let{turnId:o,messages:r,tools:i,systemPrompt:l,config:s}=t,d={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},this.hooks?.invoke("turn.submitted",{...d,prompt:r[r.length-1]?.content??void 0}).catch(()=>{});let g=Me(r),p=[];if(l&&p.push({role:"system",content:l}),p.push(...g),this.hooks){let y=g.filter(C=>C.role==="user").pop(),_=typeof y?.content=="string"?y.content.slice(0,500):void 0;if(_)try{let C=await this.hooks.invoke("memory.before_recall",{sessionId:t.sessionId,turnId:o,query:_}),h=C?.context?.recalledMemories;if(h&&h.length>0){let A=h.map(T=>`- ${T.text}`).join(`
17
+ `);p.splice(l?1:0,0,{role:"system",content:`[Recalled from long-term memory]
18
+ ${A}`})}this.hooks.invoke("memory.after_recall",{sessionId:t.sessionId,turnId:o,blockCount:C?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let m=s?.model??"",k=Math.min(s?.maxRounds??this.maxRounds,100);try{let y=s?.summaryModel?async h=>{try{let A=h.map(E=>`${E.name}(${E.arguments.slice(0,200)})`).join(", "),T=this.transport.stream({model:s.summaryModel,messages:[{role:"system",content:"Summarize the tool usage in ~30 chars, git-commit-subject style. Reply with ONLY the summary, nothing else."},{role:"user",content:A}],tools:[],maxTokens:60},s.apiKey??this.apiKey),R="";for await(let E of T)E.type==="delta"&&(R+=E.text);return R.trim()||null}catch{return null}}:void 0,_={turnId:o,sessionId:t.sessionId,messages:p,tools:i,model:m,apiKey:s?.apiKey??this.apiKey,temperature:s?.temperature,maxRounds:k,contextWindowTokens:s?.contextWindowTokens,maxOutputTokens:s?.maxOutputTokens,modelMaxOutputTokens:s?.modelMaxOutputTokens,toolChoice:s?.toolChoice,parentDepth:s?.parentDepth,hooks:this.hooks,fallbackModel:s?.fallbackModel,maxTurns:s?.maxTurns,tokenBudget:s?.tokenBudget,maxConcurrentTools:s?.maxConcurrentTools,generateToolUseSummary:y,signal:n},C;for await(let h of $t(_,this.transport,this.toolInvoker,this.log))C=h,yield h;C?.type==="end"?this.hooks?.invoke("turn.completed",{...d}).catch(()=>{}):C?.type==="error"&&this.hooks?.invoke("turn.failed",{...d,code:C.code,error:C.error}).catch(()=>{})}catch(y){if(n?.aborted)this.hooks?.invoke("turn.failed",{...d,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let _=y instanceof Error?y.message:String(y),C=typeof y?.status=="number"?y.status:void 0,h=G(C,_),A=Te(h);this.log.error(`turn ${o} error [${h}, retryable=${A.retryable}]: ${_}`),this.hooks?.invoke("turn.failed",{...d,code:h,error:_}).catch(()=>{}),yield{type:"error",turnId:o,error:_,code:h}}}}};export{jt as Agent};