qlogicagent 0.5.3 → 1.0.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.
- package/README.md +24 -23
- package/dist/agent.js +13 -13
- package/dist/cli.js +218 -184
- package/dist/contracts.js +1 -1
- package/dist/index.js +391 -20
- package/dist/orchestration.js +14 -105
- package/dist/types/agent/agent.d.ts +1 -1
- package/dist/types/agent/constants.d.ts +2 -2
- package/dist/types/agent/tool-access.d.ts +30 -0
- package/dist/types/agent/tool-loop.d.ts +2 -4
- package/dist/types/agent/types.d.ts +51 -13
- package/dist/types/cli/main.d.ts +3 -3
- package/dist/types/cli/stdio-server.d.ts +89 -7
- package/dist/types/cli/tool-bootstrap.d.ts +16 -5
- package/dist/types/cli/transport.d.ts +40 -0
- package/dist/types/contracts/index.d.ts +0 -1
- package/dist/types/contracts/todo.d.ts +9 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/types/llm/index.d.ts +7 -1
- package/dist/types/llm/media-client.d.ts +43 -0
- package/dist/types/llm/media-transport.d.ts +80 -0
- package/dist/types/llm/model-catalog.d.ts +5 -5
- package/dist/types/llm/provider-def.d.ts +7 -0
- package/dist/types/llm/provider-registry.d.ts +1 -1
- package/dist/types/llm/transport.d.ts +2 -0
- package/dist/types/llm/transports/anthropic-messages.d.ts +34 -11
- package/dist/types/llm/transports/gemini-media.d.ts +21 -0
- package/dist/types/llm/transports/minimax-media.d.ts +21 -0
- package/dist/types/llm/transports/openai-chat.d.ts +1 -1
- package/dist/types/llm/transports/openai-media.d.ts +24 -0
- package/dist/types/llm/transports/qwen-media.d.ts +25 -0
- package/dist/types/llm/transports/volcengine-media.d.ts +34 -0
- package/dist/types/orchestration/index.d.ts +14 -112
- package/dist/types/orchestration/skill-improvement.d.ts +2 -2
- package/dist/types/orchestration/{fork-subagent.d.ts → subagent/fork-subagent.d.ts} +2 -4
- package/dist/types/orchestration/{tool-schema.d.ts → tool-loop/tool-schema.d.ts} +1 -2
- package/dist/types/protocol/index.d.ts +7 -0
- package/dist/types/protocol/methods.d.ts +380 -0
- package/dist/types/protocol/notifications.d.ts +296 -0
- package/dist/types/runtime/execution/dream-agent.d.ts +1 -1
- package/dist/types/runtime/execution/forked-agent.d.ts +1 -3
- package/dist/types/runtime/hooks/context-compression.d.ts +1 -1
- package/dist/types/runtime/infra/agent-paths.d.ts +57 -0
- package/dist/types/runtime/infra/checkpoint-backend.d.ts +8 -0
- package/dist/types/runtime/infra/disk-storage.d.ts +36 -0
- package/dist/types/runtime/infra/file-watcher.d.ts +2 -2
- package/dist/types/runtime/infra/index.d.ts +2 -0
- package/dist/types/runtime/infra/secure-storage.d.ts +1 -1
- package/dist/types/runtime/infra/task-runtime.d.ts +1 -1
- package/dist/types/runtime/prompt/environment-context.d.ts +1 -1
- package/dist/types/runtime/prompt/instruction-loader.d.ts +6 -6
- package/dist/types/runtime/session/index.d.ts +1 -1
- package/dist/types/runtime/session/session-memory.d.ts +0 -1
- package/dist/types/runtime/session/session-persistence.d.ts +1 -1
- package/dist/types/runtime/session/session-state.d.ts +18 -9
- package/dist/types/skills/index.d.ts +20 -26
- package/dist/types/skills/mcp/mcp-manager.d.ts +3 -4
- package/dist/types/skills/mcp/mcp-stdio-client.d.ts +1 -1
- package/dist/types/skills/{memory-store.d.ts → memory/memory-store.d.ts} +20 -0
- package/dist/types/skills/{memory-tool.d.ts → memory/memory-tool.d.ts} +20 -0
- package/dist/types/skills/{qmemory-adapter.d.ts → memory/qmemory-adapter.d.ts} +1 -0
- package/dist/types/skills/permissions/hook-runner.d.ts +1 -1
- package/dist/types/skills/permissions/settings-watcher.d.ts +2 -2
- package/dist/types/skills/plugins/plugin-api.d.ts +1 -1
- package/dist/types/skills/plugins/plugin-loader.d.ts +1 -4
- package/dist/types/skills/plugins/plugin-marketplace.d.ts +1 -1
- package/dist/types/skills/portable-tool.d.ts +34 -1
- package/dist/types/skills/todo-tool.d.ts +51 -42
- package/dist/types/skills/tools/instructions-tool.d.ts +20 -58
- package/dist/types/skills/tools/shell/shell-exec.d.ts +2 -0
- package/dist/types/skills/tools/skill-invoke-tool.d.ts +2 -2
- package/dist/types/skills/tools.d.ts +65 -0
- package/package.json +2 -2
- package/dist/types/contracts/skill-candidate.d.ts +0 -63
- package/dist/types/orchestration/curator-scheduler.d.ts +0 -119
- package/dist/types/orchestration/memory-provider.d.ts +0 -14
- package/dist/types/orchestration/skill-candidate.d.ts +0 -52
- package/dist/types/orchestration/skill-consolidation.d.ts +0 -123
- package/dist/types/orchestration/skill-similarity.d.ts +0 -98
- package/dist/types/orchestration/team-orchestration.d.ts +0 -195
- package/dist/types/orchestration/team-tool-loop-wiring.d.ts +0 -92
- package/dist/types/skills/memory-query-tool.d.ts +0 -43
- package/dist/types/skills/tool-registry.d.ts +0 -29
- package/dist/types/skills/tools/memory-tool.d.ts +0 -74
- package/dist/types/skills/tools/pdf-tool.d.ts +0 -66
- /package/dist/types/orchestration/{context-collapse.d.ts → context/context-collapse.d.ts} +0 -0
- /package/dist/types/orchestration/{context-compression.d.ts → context/context-compression.d.ts} +0 -0
- /package/dist/types/orchestration/{reactive-compact.d.ts → context/reactive-compact.d.ts} +0 -0
- /package/dist/types/orchestration/{turn-loop-guard.d.ts → context/turn-loop-guard.d.ts} +0 -0
- /package/dist/types/orchestration/{error-classification.d.ts → error-handling/error-classification.d.ts} +0 -0
- /package/dist/types/orchestration/{failover-classification.d.ts → error-handling/failover-classification.d.ts} +0 -0
- /package/dist/types/orchestration/{failover-error.d.ts → error-handling/failover-error.d.ts} +0 -0
- /package/dist/types/orchestration/{retry-loop.d.ts → error-handling/retry-loop.d.ts} +0 -0
- /package/dist/types/orchestration/{agent-registry.d.ts → subagent/agent-registry.d.ts} +0 -0
- /package/dist/types/orchestration/{task-types.d.ts → subagent/task-types.d.ts} +0 -0
- /package/dist/types/orchestration/{conversation-repair.d.ts → tool-loop/conversation-repair.d.ts} +0 -0
- /package/dist/types/orchestration/{tool-choice-policy.d.ts → tool-loop/tool-choice-policy.d.ts} +0 -0
- /package/dist/types/orchestration/{tool-loop-state.d.ts → tool-loop/tool-loop-state.d.ts} +0 -0
- /package/dist/types/skills/{memory-extractor.d.ts → memory/memory-extractor.d.ts} +0 -0
- /package/dist/types/skills/{skill-frontmatter.d.ts → skill-system/skill-frontmatter.d.ts} +0 -0
- /package/dist/types/skills/{skill-guard.d.ts → skill-system/skill-guard.d.ts} +0 -0
- /package/dist/types/skills/{skill-loader.d.ts → skill-system/skill-loader.d.ts} +0 -0
- /package/dist/types/skills/{skill-source.d.ts → skill-system/skill-source.d.ts} +0 -0
- /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
|
|
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
|
-
| `
|
|
95
|
+
| `initialize` | 协议握手 | `{ protocolVersion, host: { name, version } }` |
|
|
96
96
|
| `agent.ping` | 心跳检测 | — |
|
|
97
|
-
| `
|
|
97
|
+
| `thread.turn` | 执行一轮对话 | 见下方详细说明 |
|
|
98
98
|
| `agent.abort` | 中止当前 turn | `{ turnId }` |
|
|
99
|
-
| `
|
|
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
|
-
###
|
|
105
|
+
### thread.turn 参数
|
|
105
106
|
|
|
106
107
|
```json
|
|
107
108
|
{
|
|
108
109
|
"jsonrpc": "2.0",
|
|
109
110
|
"id": 1,
|
|
110
|
-
"method": "
|
|
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
|
-
│ ├──
|
|
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) | `~/.
|
|
246
|
+
| **MD 记忆** | Agent 主动管理的笔记 (add/replace/remove) | `~/.qlogicagent/session-memory.md` |
|
|
246
247
|
| **QMemory** | 语义向量记忆,自动提取 + 语义召回 | QMemory 服务 (SQLite + embedding) |
|
|
247
|
-
| **会话转录** | JSONL 对话记录,用于会话恢复 | `~/.
|
|
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
|
-
### 用户级配置(`~/.
|
|
282
|
+
### 用户级配置(`~/.qlogicagent/`)
|
|
282
283
|
|
|
283
284
|
| 路径 | 说明 |
|
|
284
285
|
|------|------|
|
|
285
|
-
| `~/.
|
|
286
|
-
| `~/.
|
|
287
|
-
| `~/.
|
|
288
|
-
| `~/.
|
|
289
|
-
| `~/.
|
|
290
|
-
| `~/.
|
|
291
|
-
| `~/.
|
|
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
|
-
| `.
|
|
298
|
-
| `.
|
|
299
|
-
| `.
|
|
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(`~/.
|
|
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
|
-
### `~/.
|
|
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
|
|
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
|
-
`),
|
|
3
|
-
`));if(
|
|
4
|
-
[...truncated: ${e.length-
|
|
5
|
-
`);return r>t*.7?
|
|
6
|
-
[...truncated: ${e.length-r} chars omitted]`:
|
|
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=
|
|
1
|
+
var qt=Object.defineProperty;var Ht=(e,t)=>()=>(e&&(t=e(e=0)),t);var Wt=(e,t)=>{for(var n in t)qt(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 hn(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 Tn(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=[],a=[];for(let l of e){let s=l.function.name,{level:p,reasons:g}=hn(l,t),d=Tn(p),m={toolName:s,status:d,permissionLevel:p,approvalRequired:p===4,reasonCodes:g};n.set(s,m),p===5?r.push(m):(o.push(l),p===4&&a.push(m))}return{eligibleTools:o,blockedTools:r,approvalRequiredTools:a,eligibilityByName:n}}var fn,Ft=Ht(()=>{"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,t){return{role:"assistant",content:t||null,tool_calls:e}}function J(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n}}var Kt=/\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]},Yt=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Xt=/["']?(?: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 j(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 j(e,U.format)}function Ve(e){return j(e,U.rateLimit)}function co(e){return j(e,U.timeout)}function uo(e){return Kt.test(e)}function ye(e){let t=e.toLowerCase();return t?e.length>Jt?Xt.test(t):j(t,U.billing)?!0:Yt.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Qe(e){return j(e,U.authPermanent)}function po(e){return j(e,U.auth)}function Ze(e){return j(e,U.overloaded)}function $(e,t){return t.some(n=>e.includes(n))}function mo(e){return $(e,Zt)||$(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=$(e,to),n=e.includes("spend limit")||e.includes("spending limit"),o=$(e,ro);return $(e,oo)&&$(e,no)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||$(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 ho(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function To(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":To(e)?tt(e.trim())?.code===529?"overloaded":"timeout":ho(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"},Ro={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 he(e){return Ro[e]}var rt=4,V=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let d of t)d.role==="system"?o.push(d):r.push(d);let a=n;for(let d of o)a-=this.estimateTokens(d);let l;for(let d of r)if(d.role==="user"){l=d;break}if(l&&(a-=this.estimateTokens(l)),a<=0)return{messages:l?[...o,l]:o,droppedCount:r.length-(l?1:0),strategy:"sliding-window"};let s=[],p=0;for(let d=r.length-1;d>=0;d--){let m=r[d];if(m===l)continue;let R=this.estimateTokens(m);if(a-R<0&&p>=rt)break;if(a-R<0&&p<rt){s.unshift(m),p++;continue}a-=R,s.unshift(m),p++}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(a=>a.role!=="tool"||typeof a.content!="string"||a.content.length<=this.maxToolResultChars?a:(o++,{...a,content:_o(a.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function _o(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let a=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
|
|
2
|
+
`),n.lastIndexOf(`]
|
|
3
|
+
`));if(a>t*.5)return n.slice(0,a+1)+`
|
|
4
|
+
[...truncated: ${e.length-a-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 Te(...e){return{compress(t,n){let o=t,r=0,a=[];for(let l of e){let s=l.compress(o,n);o=s.messages,r+=s.droppedCount,s.droppedCount>0&&a.push(s.strategy)}return{messages:o,droppedCount:r,strategy:a.length>0?a.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,a=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&&a++,s.cacheInvalidated&&l++;return{totalCompressions:t,totalLlmCalls:a,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"]),z=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,a=0;return{messages:t.map((s,p)=>{if(p>=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 a+=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,a=[];for(let s of e){let p=s.tool_call_id??"";if(p&&t.has(p)){o+=n(s),r++,t.delete(p);continue}a.push(s)}let l=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:a,tokensFreed:o,removedCount:r,boundaryMessage:l}}function Re(){return{stages:[]}}function _e(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let a=at(e,t),l=vo(a,t,o);if(l.length===0)return{messages:a,stagedCount:0};for(let s of l)t.stages.push(s);return a=at(e,t),{messages:a,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,a)=>a.range[0]-r.range[0]),o=[...e];for(let r of n){let[a,l]=r.range;if(a>=o.length)continue;let s=Math.min(l,o.length),p={role:"system",content:r.summary};o.splice(a,s-a,p)}return o}function vo(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],a=new Set(t.stages.map(p=>`${p.range[0]}-${p.range[1]}`)),l=-1,s=0;for(let p=0;p<o;p++){let g=e[p];if(g.role==="tool"||g.role==="assistant"&&typeof g.content=="string"&&g.content==="")l<0&&(l=p),s++;else{if(s>=3){let m=`${l}-${l+s}`;a.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 p=`${l}-${l+s}`;a.has(p)||r.push({id:`collapse_${l}_${l+s}`,range:[l,l+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}function So(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"}:So(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 ve(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 a=n.function??void 0,l=typeof a?.name=="string"?a.name.trim():"";if(!l)throw new Error("tool_choice.function.name is required");let s=r.filter(p=>ct(p)===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 Se(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 p=s.tool_calls.filter(g=>No(g));return{...s,...p.length>0?{tool_calls:p}:{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 p of s.tool_calls)typeof p.id=="string"&&p.id&&n.add(p.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 a=[];for(let s of o){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let p=s.tool_calls.filter(g=>typeof g.id=="string"&&r.has(g.id));if(p.length===0){let{tool_calls:g,...d}=s;d.content!=null&&d.content!==""&&a.push(d);continue}if(p.length<s.tool_calls.length){a.push({...s,tool_calls:p});continue}}a.push(s)}let l=[];for(let s of a){let p=l.length>0?l[l.length-1]:void 0;if(s.role==="user"&&p?.role==="user"){l[l.length-1]=Po(p,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??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let a of e)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&o.add(a.tool_call_id);let r=[];for(let a of e)if(r.push({...a}),!(a.role!=="assistant"||!Array.isArray(a.tool_calls)||a.tool_calls.length===0))for(let l of a.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=Se(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=Se(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((a,l)=>a!==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 Hn={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 q(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 Xo,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,ht=65536,Tt=3,Ct=65536,bt=3e4,kt=3,oe=5,Rt=5e4,_t=2e5,Ue=2e3;var Qo="tool-results",vt="<persisted-output>",Zo="</persisted-output>";function St(){return{seenIds:new Set,replacements:new Map}}function At(e){return xt(Vo(),"qlogicagent-sessions",e,Qo)}async function en(e){try{await Xo(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(vt)}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:a}=on(e,Ue);return{filepath:o,originalSize:e.length,preview:r,hasMore:a}}function wt(e){let t=`${vt}
|
|
9
9
|
`;return t+=`Output too large (${e.originalSize} chars). Full output saved to: ${e.filepath}
|
|
10
10
|
|
|
11
|
-
`,t+=`Preview (first ${
|
|
11
|
+
`,t+=`Preview (first ${Ue} bytes):
|
|
12
12
|
`,t+=e.preview,t+=e.hasMore?`
|
|
13
13
|
...
|
|
14
14
|
`:`
|
|
15
|
-
`,t+=
|
|
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
|
-
`);
|
|
18
|
-
${
|
|
15
|
+
`,t+=Zo,t}async function It(e,t,n,o=Rt){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 a of e){let l=t.replacements.get(a.toolCallId);l!==void 0?n.push({...a,replacement:l}):t.seenIds.has(a.toolCallId)?o.push(a):r.push(a)}return{mustReapply:n,frozen:o,fresh:r}}function sn(e,t,n){let o=[...e].sort((l,s)=>s.size-l.size),r=[],a=t+e.reduce((l,s)=>l+s.size,0);for(let l of o){if(a<=n)break;r.push(l),a-=l.size}return r}async function Lt(e,t,n,o=_t){let r=nn(e);if(r.length===0)return{messages:e,newlyReplacedCount:0};let a=new Map,l=[];for(let d of r){let{mustReapply:m,frozen:R,fresh:y}=rn(d,t);for(let h of m)a.set(h.toolCallId,h.replacement);if(y.length===0){for(let h of d)t.seenIds.add(h.toolCallId);continue}let _=R.reduce((h,x)=>h+x.size,0),C=y.reduce((h,x)=>h+x.size,0),T=_+C>o?sn(y,_,o):[],I=new Set(T.map(h=>h.toolCallId));for(let h of d)I.has(h.toolCallId)||t.seenIds.add(h.toolCallId);T.length>0&&l.push(...T)}if(a.size===0&&l.length===0)return{messages:e,newlyReplacedCount:0};let s=await Promise.all(l.map(async d=>{let m=await Mt(d.content,d.toolCallId,n);return{candidate:d,result:m}})),p=0;for(let{candidate:d,result:m}of s){if(t.seenIds.add(d.toolCallId),!m)continue;let R=wt(m);a.set(d.toolCallId,R),t.replacements.set(d.toolCallId,R),p++}return a.size===0?{messages:e,newlyReplacedCount:0}:{messages:e.map(d=>{if(d.role!=="tool"||!d.tool_call_id)return d;let m=a.get(d.tool_call_id);return m===void 0?d:{...d,content:m}}),newlyReplacedCount:p}}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:a,hooks:l,sessionId:s,turnId:p,log:g}=this.config,d=t.toolCall.function.name,m=!1,R=t.toolCall.function.arguments;if(l)try{let h=await l.invoke("tool.before_invoke",{sessionId:s,turnId:p,callId:t.id,toolName:d,arguments:cn(R)});if(h.action==="abort"){let x=h.reason??"blocked by policy";g.info(`tool ${d} blocked: ${x}`),t.results.push({callId:t.id,toolName:d,ok:!1,error:x,blocked:!0,blockReason:x,message:J(t.id,{ok:!1,error:x})}),t.status="completed";return}h.action==="continue"&&h.context?.arguments&&(R=JSON.stringify(h.context.arguments))}catch{}let y=await a.invoke(p,d,R,this.siblingAbortController.signal),_=this.getAbortReason();if(_&&!m){t.results.push(this.createSyntheticError(t,_)),t.status="completed";return}let C=!y.error,T=y.result;C&&T&&T.length>5e4&&(T=await It(T,t.id,s));let I=J(t.id,{ok:C,payload:T,error:y.error});C||(m=!0,ln.has(d)&&(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:p,callId:t.id,toolName:d,ok:C,...y.error?{error:y.error}:{}}).catch(()=>{}),t.results.push({callId:t.id,toolName:d,ok:C,error:y.error,message:I}),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 Hr}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 Wr=new ee;function mn(){return Te(new Q(dn),new z(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 a=je(e),l=je(r.messages);pn.record({timestamp:Date.now(),strategy:r.strategy,tokensBefore:a,tokensAfter:l,droppedCount:r.droppedCount,latencyMs:r.metrics?.latencyMs??0,usedLlm:!1,cacheInvalidated:r.metrics?.cacheInvalidated??!1,tier:be(a,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.")}var kn=new Set(["write","edit","patch","apply_patch"]);function Rn(e){let t=e.split(".").pop()?.toLowerCase()??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(t)?"image":["md","txt","pdf","doc","docx","rtf","html"].includes(t)?"document":["mermaid","mmd","dot","puml","plantuml"].includes(t)?"diagram":["csv","tsv","xlsx","xls"].includes(t)?"table":["ts","tsx","js","jsx","py","rs","go","java","c","cpp","h","cs","rb","sh","sql","json","yaml","yml","toml","xml","css","scss","vue","svelte"].includes(t)?"code":"file"}function _n(e){let t=e.split(".").pop()?.toLowerCase()??"";return{ts:"typescript",tsx:"typescriptreact",js:"javascript",jsx:"javascriptreact",py:"python",rs:"rust",go:"go",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",rb:"ruby",sh:"shellscript",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",vue:"vue",svelte:"svelte",md:"markdown"}[t]}function xn(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 vn(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 Sn(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 An(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 En(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:a,messages:l,tools:s,model:p,apiKey:g,temperature:d,hooks:m,signal:R}=e,y={sessionId:a,turnId:r},_=e.maxTurns??0,C=e.querySource,{resolveToolEligibility:T}=await Promise.resolve().then(()=>(Ft(),Nt)),I=T(s,e.toolEligibilityContext),h=I.eligibleTools;for(let E of I.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:E.toolName,reason:"blocked-by-policy"};if(!h.length){yield*Mn(r,p,l,g,d,R,t,o);return}let x=xn(e.maxRounds),L={contextWindowTokens:e.contextWindowTokens??gt,responseBufferTokens:ft,maxOutputTokens:e.maxOutputTokens??yt,abortSignal:R,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},H=new Set,D=0,ne=h,re,c={messages:[...l],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Pe(L),reactiveCompactState:$e(),toolLoopState:ue({maxRounds:x,replayMessages:[...l]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{prompt:0,completion:0},collapseStore:Re(),currentModel:p,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,snipRemovedIds:new Set,contentReplacementState:St()};for(;;){let{messages:E,maxOutputTokensRecoveryCount:W,hasAttemptedReactiveCompact:In,maxOutputTokensOverride:qe,turnCount:K,guardState:v,reactiveCompactState:N,collapseStore:me}=c,{toolLoopState:O}=c;if(re){try{let i=await re;i&&(yield{type:"tool_use_summary",turnId:r,summary:i})}catch{}re=void 0}if(e.refreshTools&&K>1){let i=e.refreshTools();i!==ne&&(ne=i,o.debug(`tools refreshed: ${i.length} tools`))}if(Be(v,L)){o.info(`turn aborted by guard at turn ${K}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED"};return}let B=Ne(v,L);if(B.level==="blocking"){B.reason==="prompt_too_long"&&q(N)&&(N.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${B.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),o.info(`token budget blocking (${B.reason}), ending tool loop`);break}B.level==="warning"&&o.info(`token budget warning: ${B.usagePercent}% used, ${B.remainingTokens} remaining`);let S;{let i=await Lt(E,c.contentReplacementState,a);S=i.messages,i.newlyReplacedCount>0&&(o.info(`tool-result-budget: persisted ${i.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:r,action:"tool_result_budget",detail:`${i.newlyReplacedCount} persisted`})}{let i=ke(S,c.snipRemovedIds);S=i.messages,i.removedCount>0&&(o.info(`snip: removed ${i.removedCount} messages, freed ~${i.tokensFreed} tokens`),yield{type:"recovery",turnId:r,action:"snip",detail:`${i.removedCount} messages`})}{let u=new z().compress(S,0);u.droppedCount>0&&(S=u.messages,o.info(`microcompact: cleared ${u.droppedCount} old tool results`))}if(S=_e(S,me).messages,v.promptTokens>0){let i=Ot(S,{budget:L.contextWindowTokens*.75,model:c.currentModel});i.droppedCount>0&&(S=i.messages,o.info(`autocompact: ${i.strategy}, dropped ${i.droppedCount}`),yield{type:"recovery",turnId:r,action:"autocompact",detail:`${i.strategy}: ${i.droppedCount} dropped`},c.hasAttemptedReactiveCompact=!1,m?.invoke("context.after_compact",{...y,removedCount:i.droppedCount}).catch(()=>{}))}S=En(S);let se=ve({tools:ne,toolChoice:e.toolChoice??"auto"}),Y=ue({maxRounds:x,replayMessages:S,lastStopReason:O.lastStopReason,options:{stopReason:O.lastStopReason}}),He=se.extraSystemPrompt?[{role:"system",content:se.extraSystemPrompt},...Y.state.replayMessages]:Y.state.replayMessages;O=Y.state,Y.recoveryActions.length>0&&o.debug(`tool loop recovery: ${Y.recoveryActions.map(i=>i.detail??i.kind).join("; ")}`),o.debug(`turn ${K}, messages: ${He.length}`),m?.invoke("turn.before_inference",{...y,model:c.currentModel}).catch(()=>{});let ie=!1,We=[],Ke=new Map,Ye="stop",P,f=null,ae=!1;try{for await(let i of t.stream({model:c.currentModel,messages:He,tools:se.tools,toolChoice:se.normalizedToolChoice??"auto",temperature:d,maxTokens:(qe??v.currentMaxOutputTokens)||void 0},g,R))switch(i.type){case"delta":We.push(i.text),ie||(yield{type:"delta",turnId:r,text:i.text});break;case"tool_call_delta":ie=!0,dt(Ke,i);break;case"reasoning_delta":break;case"usage":P={prompt:i.promptTokens,completion:i.completionTokens,reasoning:i.reasoningTokens,cacheRead:i.cacheReadTokens,cacheCreation:i.cacheCreationTokens};break;case"done":Ye=i.finishReason;break}if(ie||m?.invoke("turn.after_inference",{...y,model:c.currentModel}).catch(()=>{}),e.postSamplingHooks&&e.postSamplingHooks.length>0){let i=c.currentModel;for(let u of e.postSamplingHooks)try{u({messages:[...S],model:i,sessionId:a})}catch{}}}catch(i){if(i instanceof te&&e.fallbackModel){o.info(`model fallback triggered: ${i.originalModel} \u2192 ${i.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`${i.originalModel} \u2192 ${i.fallbackModel}`},c={...c,currentModel:i.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let u=i instanceof Error?i.message:String(i),b=typeof i?.status=="number"?i.status:void 0;if(!b&&u&&(u.includes("ECONNRESET")||u.includes("EPIPE"))){let A=(c.consecutiveApiRetries??0)+1;if(A>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:A,transition:void 0};continue}let M=An({status:b,message:u});if(M!==null){o.info(`max_tokens overflow: adjusting to ${M}`),v.currentMaxOutputTokens=M,c={...c,maxOutputTokensOverride:M,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 A=de(c.consecutive529Errors);o.info(`persistent retry: waiting ${A}ms (attempt ${c.consecutive529Errors})`);let k=A;for(;k>0;){if(R?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED"};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(k/1e3)}s (${b})`};let w=Math.min(k,bt);await new Promise(Gt=>setTimeout(Gt,w)),k-=w}c={...c,transition:void 0};continue}if(Ie(C)){let k=Sn({status:b,message:u})??de(c.consecutive529Errors);o.info(`transient ${b}: retry in ${k}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${b} retry in ${k}ms`},await new Promise(w=>setTimeout(w,k)),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 i=Fe({status:f.status??500,message:f.message},v,L);if(i.action==="reactive_compact"&&q(N)&&(N.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${f.status??500}: ${f.message}`}),i.action==="retry"){let b=(c.consecutiveApiRetries??0)+1;if(b>oe){o.info(`API retry limit reached (${oe}), aborting`);let M=G(f.status,f.message);yield{type:"error",turnId:r,error:f.message,code:M};return}yield{type:"recovery",turnId:r,action:"retry",detail:i.reason},c={...c,consecutiveApiRetries:b,transition:void 0};continue}let u=G(f.status,f.message);m?.invoke("stop.failure",{sessionId:a,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.cacheRead&&(c.totalUsage.cacheRead=(c.totalUsage.cacheRead??0)+P.cacheRead),P.cacheCreation&&(c.totalUsage.cacheCreation=(c.totalUsage.cacheCreation??0)+P.cacheCreation)),P?.prompt&&(v.promptTokens=P.prompt),c.finalText=We.join("");let F=[...Ke.values()].map(i=>({id:i.id||`tc_${r}_${K}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:i.name,arguments:i.arguments}}));if(F.length===0&&!ie){if(ae&&f&&Dt(f)){if(c.transition?.reason!=="collapse_drain_retry"){let i=xe(S,me);if(i.committed>0){o.info(`collapse drain: committed ${i.committed} stages`),yield{type:"recovery",turnId:r,action:"collapse_drain",detail:`${i.committed} stages committed`},c={...c,messages:i.messages,transition:{reason:"collapse_drain_retry",committed:i.committed}};continue}}if(q(N)){N.attemptedThisTurn=!0,v.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:a,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(q(N)){N.attemptedThisTurn=!0,v.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:a,reason:"media_error",error:f.message}).catch(()=>{}),yield{type:"error",turnId:r,error:f.message,code:"IMAGE_ERROR"};return}if(vn(Ye)){v.consecutiveTruncations+=1;let i=e.modelMaxOutputTokens??ht,u=De(v,L,i);if(u.shouldEscalate&&qe===void 0){v.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<Tt){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 v.consecutiveTruncations=0;if(O=ce(O,{replayMessages:E,lastStopReason:"completed"}),m){let i=await m.invoke("stop",{sessionId:a,reason:"completed"});if(i.action==="prevent"){o.info(`stop hook prevented continuation: ${i.reason??"no reason"}`),yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}if(i.action==="abort"){let u=i.reason??"Stop hook requested continuation";o.info(`stop hook blocking: ${u}`);let b={role:"user",content:u};c={...c,messages:[...E,{role:"assistant",content:c.finalText},b],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(e.tokenBudget&&e.tokenBudget>0){let i=c.totalUsage.prompt+c.totalUsage.completion+(c.totalUsage.reasoning??0),u=i/e.tokenBudget*100;if(u<90){let b={role:"user",content:Pt(u,i,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:[...E,{role:"assistant",content:c.finalText},b],transition:{reason:"token_budget_continuation"}};continue}}if(D>0){let i={ok:!0,toolCallCount:D,distinctToolCount:H.size,multiStep:D>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},u=le(i,{tools:[...H]});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 i of F){let u=i.function.arguments,b=ne.find(M=>M.function.name===i.function.name);if(b?.backfillObservableInput)try{let M=JSON.parse(i.function.arguments),A={...M};b.backfillObservableInput(A),Object.keys(A).some(w=>!(w in M))&&(u=JSON.stringify(A))}catch{}yield{type:"tool_call",turnId:r,callId:i.id,name:i.function.name,arguments:u}}E.push(fe(F,c.finalText||void 0)),O=we(O,{replayMessages:E,pendingToolCallIds:F.map(i=>i.id),completedToolCallIds:O.completedToolCallIds,lastStopReason:"tool_calls"});let Xe=[];try{let i=new pe({toolInvoker:n,hooks:m,sessionId:a,turnId:r,log:o,signal:R,maxConcurrentTools:e?.maxConcurrentTools});for(let u of F)i.addTool(u);for await(let u of i.getRemainingResults()){u.blocked&&(yield{type:"tool_blocked",turnId:r,callId:u.callId,name:u.toolName,reason:u.blockReason??"blocked"}),E.push(u.message),Xe.push(u.callId),H.add(u.toolName),D++;let b=typeof u.message?.content=="string"?u.message.content:"",M=u.ok&&b?b.slice(0,2e3):void 0;if(yield{type:"tool_result",turnId:r,callId:u.callId,name:u.toolName,ok:u.ok,error:u.error,outputPreview:M},u.ok){let A=F.find(k=>k.id===u.callId);if(A){if(u.toolName==="plan_mode")try{let k=JSON.parse(A.function.arguments);k.action==="exit"&&typeof k.plan=="string"&&k.plan.length>0&&(yield{type:"plan_update",turnId:r,slug:"approved-plan",content:k.plan})}catch{}if(kn.has(u.toolName))try{let k=JSON.parse(A.function.arguments),w=typeof k.file_path=="string"?k.file_path:typeof k.filePath=="string"?k.filePath:typeof k.path=="string"?k.path:void 0;w&&(yield{type:"artifact",turnId:r,artifactId:`artifact-${u.callId}`,artifactType:Rn(w),title:w.split(/[\\/]/).pop()||w,filePath:w,language:_n(w)})}catch{}}}}}catch(i){let u=i instanceof Error?i.message:String(i);yield{type:"error",turnId:r,error:u,code:"TOOL_EXECUTION_ERROR"};return}if(O=ce(O,{replayMessages:E,completedToolCallIds:[...O.completedToolCallIds,...Xe],lastStopReason:"tool_calls"}),e.generateToolUseSummary&&F.length>0){let i=F.map(u=>({name:u.function.name,arguments:u.function.arguments}));re=e.generateToolUseSummary(i).catch(()=>null)}let Je=E.slice(-F.length),zt=Je.length>0&&Je.every(i=>{let u=i?.content;return typeof u!="string"?!1:u.startsWith("Error: ")}),X=c.consecutiveFailedRounds;if(zt){if(X+=1,X>=mt&&c.finalText){o.info(`early exit: ${X} consecutive failed rounds, returning partial response`),yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}}else X=0;let ge=K+1;if(_>0&&ge>_){if(o.info(`max turns reached (${_}), completing`),m){let i=await m.invoke("stop",{sessionId:a,reason:"max_turns"});if(i.action==="abort"){let u=i.reason??"Stop hook requested continuation after max_turns";c={...c,messages:[...E,{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>x){if(o.info(`tool loop budget exhausted (${x} rounds), returning`),D>0){let i={ok:!0,toolCallCount:D,distinctToolCount:H.size,multiStep:D>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},u=le(i,{tools:[...H]});u&&(yield{type:"skill_instruction",turnId:r,instruction:u})}yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}c={messages:E,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:ge,transition:{reason:"next_turn"},guardState:v,reactiveCompactState:N,toolLoopState:O,consecutiveFailedRounds:X,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*Mn(e,t,n,o,r,a,l,s){let p=[],g;s.debug(`single LLM round, messages: ${n.length}`);for await(let d of l.stream({model:t,messages:n,temperature:r},o,a))switch(d.type){case"delta":p.push(d.text),yield{type:"delta",turnId:e,text:d.text};break;case"usage":g={prompt:d.promptTokens,completion:d.completionTokens,reasoning:d.reasoningTokens,cacheRead:d.cacheReadTokens,cacheCreation:d.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:e,content:p.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:a,systemPrompt:l,config:s}=t,p={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},this.hooks?.invoke("turn.submitted",{...p,prompt:r[r.length-1]?.content??void 0}).catch(()=>{});let g=Me(r),d=[];if(l&&d.push({role:"system",content:l}),d.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:_}),T=C?.context?.recalledMemories;if(T&&T.length>0){let I=T.map(h=>`- ${h.text}`).join(`
|
|
17
|
+
`);d.splice(l?1:0,0,{role:"system",content:`[Recalled from long-term memory]
|
|
18
|
+
${I}`})}this.hooks.invoke("memory.after_recall",{sessionId:t.sessionId,turnId:o,blockCount:C?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let m=s?.model??"",R=Math.min(s?.maxRounds??this.maxRounds,100);try{let y=s?.summaryModel?async T=>{try{let I=T.map(L=>`${L.name}(${L.arguments.slice(0,200)})`).join(", "),h=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:I}],tools:[],maxTokens:60},s.apiKey??this.apiKey),x="";for await(let L of h)L.type==="delta"&&(x+=L.text);return x.trim()||null}catch{return null}}:void 0,_={turnId:o,sessionId:t.sessionId,messages:d,tools:a,model:m,apiKey:s?.apiKey??this.apiKey,temperature:s?.temperature,maxRounds:R,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 T of $t(_,this.transport,this.toolInvoker,this.log))C=T,yield T;C?.type==="end"?this.hooks?.invoke("turn.completed",{...p}).catch(()=>{}):C?.type==="error"&&this.hooks?.invoke("turn.failed",{...p,code:C.code,error:C.error}).catch(()=>{})}catch(y){if(n?.aborted)this.hooks?.invoke("turn.failed",{...p,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,T=G(C,_),I=he(T);this.log.error(`turn ${o} error [${T}, retryable=${I.retryable}]: ${_}`),this.hooks?.invoke("turn.failed",{...p,code:T,error:_}).catch(()=>{}),yield{type:"error",turnId:o,error:_,code:T}}}}};export{jt as Agent};
|