qlogicagent 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/README.md +403 -402
  2. package/dist/agent.js +18 -0
  3. package/dist/cli.js +384 -0
  4. package/dist/contracts.js +1 -0
  5. package/dist/index.js +383 -0
  6. package/dist/orchestration.js +34 -0
  7. package/dist/types/agent/agent.d.ts +43 -0
  8. package/dist/types/agent/constants.d.ts +47 -0
  9. package/dist/types/agent/tool-access.d.ts +30 -0
  10. package/dist/types/agent/tool-loop.d.ts +94 -0
  11. package/dist/types/agent/types.d.ts +238 -0
  12. package/dist/types/cli/main.d.ts +11 -0
  13. package/dist/types/cli/stdio-server.d.ts +78 -0
  14. package/dist/types/cli/tool-bootstrap.d.ts +40 -0
  15. package/dist/types/cli/transport.d.ts +40 -0
  16. package/dist/types/config/config.d.ts +17 -0
  17. package/dist/types/contracts/hooks.d.ts +175 -0
  18. package/dist/types/contracts/index.d.ts +9 -0
  19. package/dist/types/contracts/planner.d.ts +35 -0
  20. package/dist/types/contracts/todo.d.ts +23 -0
  21. package/dist/types/index.d.ts +16 -0
  22. package/dist/types/llm/builtin-providers.d.ts +10 -0
  23. package/dist/types/llm/debug-transport.d.ts +12 -0
  24. package/dist/types/llm/index.d.ts +16 -0
  25. package/dist/types/llm/llm-client.d.ts +43 -0
  26. package/dist/types/llm/model-catalog.d.ts +53 -0
  27. package/dist/types/llm/provider-def.d.ts +59 -0
  28. package/dist/types/llm/provider-registry.d.ts +54 -0
  29. package/dist/types/llm/transport.d.ts +62 -0
  30. package/dist/types/llm/transports/anthropic-messages.d.ts +31 -0
  31. package/dist/types/llm/transports/openai-chat.d.ts +36 -0
  32. package/dist/types/orchestration/context/context-collapse.d.ts +58 -0
  33. package/dist/types/orchestration/context/context-compression.d.ts +301 -0
  34. package/dist/types/orchestration/context/reactive-compact.d.ts +73 -0
  35. package/dist/types/orchestration/context/turn-loop-guard.d.ts +86 -0
  36. package/dist/types/orchestration/error-handling/error-classification.d.ts +12 -0
  37. package/dist/types/orchestration/error-handling/failover-classification.d.ts +8 -0
  38. package/dist/types/orchestration/error-handling/failover-error.d.ts +33 -0
  39. package/dist/types/orchestration/error-handling/retry-loop.d.ts +69 -0
  40. package/dist/types/orchestration/index.d.ts +15 -0
  41. package/dist/types/orchestration/skill-improvement.d.ts +59 -0
  42. package/dist/types/orchestration/subagent/agent-registry.d.ts +46 -0
  43. package/dist/types/orchestration/subagent/fork-subagent.d.ts +98 -0
  44. package/dist/types/orchestration/subagent/task-types.d.ts +142 -0
  45. package/dist/types/orchestration/tool-loop/conversation-repair.d.ts +61 -0
  46. package/dist/types/orchestration/tool-loop/tool-choice-policy.d.ts +54 -0
  47. package/dist/types/orchestration/tool-loop/tool-loop-state.d.ts +50 -0
  48. package/dist/types/orchestration/tool-loop/tool-schema.d.ts +39 -0
  49. package/dist/types/runtime/execution/dream-agent.d.ts +199 -0
  50. package/dist/types/runtime/execution/forked-agent.d.ts +109 -0
  51. package/dist/types/runtime/execution/index.d.ts +6 -0
  52. package/dist/types/runtime/execution/progress-tracker.d.ts +78 -0
  53. package/dist/types/runtime/execution/remote-agent.d.ts +63 -0
  54. package/dist/types/runtime/execution/streaming-tool-executor.d.ts +100 -0
  55. package/dist/types/runtime/execution/tool-eligibility.d.ts +59 -0
  56. package/dist/types/runtime/execution/tool-result-storage.d.ts +87 -0
  57. package/dist/types/runtime/hooks/context-compression.d.ts +61 -0
  58. package/dist/types/runtime/hooks/hook-registry.d.ts +12 -0
  59. package/dist/types/runtime/hooks/index.d.ts +3 -0
  60. package/dist/types/runtime/hooks/memory-hooks.d.ts +49 -0
  61. package/dist/types/runtime/index.d.ts +5 -0
  62. package/dist/types/runtime/infra/agent-paths.d.ts +57 -0
  63. package/dist/types/runtime/infra/checkpoint-backend.d.ts +8 -0
  64. package/dist/types/runtime/infra/cleanup-registry.d.ts +23 -0
  65. package/dist/types/runtime/infra/disk-storage.d.ts +36 -0
  66. package/dist/types/runtime/infra/file-watcher.d.ts +72 -0
  67. package/dist/types/runtime/infra/index.d.ts +8 -0
  68. package/dist/types/runtime/infra/secure-storage.d.ts +81 -0
  69. package/dist/types/runtime/infra/task-runtime.d.ts +108 -0
  70. package/dist/types/runtime/infra/token-budget.d.ts +92 -0
  71. package/dist/types/runtime/infra/worktree-backend.d.ts +85 -0
  72. package/dist/types/runtime/prompt/environment-context.d.ts +23 -0
  73. package/dist/types/runtime/prompt/index.d.ts +3 -0
  74. package/dist/types/runtime/prompt/instruction-loader.d.ts +64 -0
  75. package/dist/types/runtime/prompt/system-prompt-sections.d.ts +63 -0
  76. package/dist/types/runtime/session/index.d.ts +2 -0
  77. package/dist/types/runtime/session/session-memory.d.ts +90 -0
  78. package/dist/types/runtime/session/session-persistence.d.ts +94 -0
  79. package/dist/types/runtime/session/session-state.d.ts +117 -0
  80. package/dist/types/skills/index.d.ts +119 -0
  81. package/dist/types/skills/mcp/index.d.ts +3 -0
  82. package/dist/types/skills/mcp/mcp-http-client.d.ts +66 -0
  83. package/dist/types/skills/mcp/mcp-manager.d.ts +83 -0
  84. package/dist/types/skills/mcp/mcp-stdio-client.d.ts +84 -0
  85. package/dist/types/skills/memory/memory-extractor.d.ts +64 -0
  86. package/dist/types/skills/memory/memory-store.d.ts +86 -0
  87. package/dist/types/skills/memory/memory-tool.d.ts +87 -0
  88. package/dist/types/skills/memory/qmemory-adapter.d.ts +42 -0
  89. package/dist/types/skills/permissions/bash-classifier.d.ts +30 -0
  90. package/dist/types/skills/permissions/classifier-cache.d.ts +51 -0
  91. package/dist/types/skills/permissions/denial-tracking.d.ts +42 -0
  92. package/dist/types/skills/permissions/hook-runner.d.ts +85 -0
  93. package/dist/types/skills/permissions/index.d.ts +12 -0
  94. package/dist/types/skills/permissions/permission-classifier.d.ts +41 -0
  95. package/dist/types/skills/permissions/rule-engine.d.ts +41 -0
  96. package/dist/types/skills/permissions/settings-watcher.d.ts +46 -0
  97. package/dist/types/skills/permissions/types.d.ts +113 -0
  98. package/dist/types/skills/plugins/index.d.ts +2 -0
  99. package/dist/types/skills/plugins/plugin-api.d.ts +38 -0
  100. package/dist/types/skills/plugins/plugin-loader.d.ts +42 -0
  101. package/dist/types/skills/plugins/plugin-marketplace.d.ts +61 -0
  102. package/dist/types/skills/portable-tool.d.ts +104 -0
  103. package/dist/types/skills/skill-system/skill-frontmatter.d.ts +19 -0
  104. package/dist/types/skills/skill-system/skill-guard.d.ts +23 -0
  105. package/dist/types/skills/skill-system/skill-loader.d.ts +16 -0
  106. package/dist/types/skills/skill-system/skill-source.d.ts +119 -0
  107. package/dist/types/skills/skill-system/skill-types.d.ts +199 -0
  108. package/dist/types/skills/think-tool.d.ts +16 -0
  109. package/dist/types/skills/todo-tool.d.ts +72 -0
  110. package/dist/types/skills/tools/agent-tool.d.ts +91 -0
  111. package/dist/types/skills/tools/apply-patch-tool.d.ts +29 -0
  112. package/dist/types/skills/tools/ask-user-tool.d.ts +80 -0
  113. package/dist/types/skills/tools/brief-tool.d.ts +74 -0
  114. package/dist/types/skills/tools/browser-tool.d.ts +114 -0
  115. package/dist/types/skills/tools/checkpoint-tool.d.ts +66 -0
  116. package/dist/types/skills/tools/config-tool.d.ts +63 -0
  117. package/dist/types/skills/tools/cron-tool.d.ts +116 -0
  118. package/dist/types/skills/tools/edit-tool.d.ts +43 -0
  119. package/dist/types/skills/tools/exec-tool.d.ts +97 -0
  120. package/dist/types/skills/tools/image-generate-tool.d.ts +62 -0
  121. package/dist/types/skills/tools/instructions-tool.d.ts +65 -0
  122. package/dist/types/skills/tools/lsp-tool.d.ts +153 -0
  123. package/dist/types/skills/tools/mcp-client-types.d.ts +269 -0
  124. package/dist/types/skills/tools/mcp-resource-tools.d.ts +14 -0
  125. package/dist/types/skills/tools/mcp-tool.d.ts +249 -0
  126. package/dist/types/skills/tools/monitor-tool.d.ts +113 -0
  127. package/dist/types/skills/tools/music-generate-tool.d.ts +55 -0
  128. package/dist/types/skills/tools/notebook-edit-tool.d.ts +15 -0
  129. package/dist/types/skills/tools/notify-tool.d.ts +53 -0
  130. package/dist/types/skills/tools/patch-tool.d.ts +45 -0
  131. package/dist/types/skills/tools/plan-mode-tool.d.ts +98 -0
  132. package/dist/types/skills/tools/read-tool.d.ts +51 -0
  133. package/dist/types/skills/tools/repl-tool.d.ts +70 -0
  134. package/dist/types/skills/tools/search-tool.d.ts +112 -0
  135. package/dist/types/skills/tools/send-message-tool.d.ts +51 -0
  136. package/dist/types/skills/tools/shell/bash-provider.d.ts +26 -0
  137. package/dist/types/skills/tools/shell/command-classification.d.ts +44 -0
  138. package/dist/types/skills/tools/shell/command-semantics.d.ts +14 -0
  139. package/dist/types/skills/tools/shell/destructive-command-warning.d.ts +10 -0
  140. package/dist/types/skills/tools/shell/exec-permissions.d.ts +52 -0
  141. package/dist/types/skills/tools/shell/index.d.ts +17 -0
  142. package/dist/types/skills/tools/shell/powershell-provider.d.ts +15 -0
  143. package/dist/types/skills/tools/shell/shell-command.d.ts +54 -0
  144. package/dist/types/skills/tools/shell/shell-exec.d.ts +33 -0
  145. package/dist/types/skills/tools/shell/shell-provider.d.ts +85 -0
  146. package/dist/types/skills/tools/shell/task-output.d.ts +45 -0
  147. package/dist/types/skills/tools/skill-invoke-tool.d.ts +46 -0
  148. package/dist/types/skills/tools/skill-list-tool.d.ts +33 -0
  149. package/dist/types/skills/tools/skill-manage-tool.d.ts +73 -0
  150. package/dist/types/skills/tools/skill-view-tool.d.ts +37 -0
  151. package/dist/types/skills/tools/sleep-tool.d.ts +49 -0
  152. package/dist/types/skills/tools/structured-output-tool.d.ts +116 -0
  153. package/dist/types/skills/tools/task-tool.d.ts +104 -0
  154. package/dist/types/skills/tools/team-tool.d.ts +89 -0
  155. package/dist/types/skills/tools/tool-search-tool.d.ts +51 -0
  156. package/dist/types/skills/tools/tts-tool.d.ts +38 -0
  157. package/dist/types/skills/tools/video-edit-tool.d.ts +69 -0
  158. package/dist/types/skills/tools/video-generate-tool.d.ts +62 -0
  159. package/dist/types/skills/tools/video-merge-tool.d.ts +105 -0
  160. package/dist/types/skills/tools/video-upscale-tool.d.ts +45 -0
  161. package/dist/types/skills/tools/web-fetch-tool.d.ts +78 -0
  162. package/dist/types/skills/tools/web-search-tool.d.ts +57 -0
  163. package/dist/types/skills/tools/workflow-tool.d.ts +44 -0
  164. package/dist/types/skills/tools/worktree-tool.d.ts +69 -0
  165. package/dist/types/skills/tools/write-tool.d.ts +45 -0
  166. package/dist/types/skills/tools.d.ts +65 -0
  167. package/package.json +4 -3
@@ -0,0 +1,34 @@
1
+ function ce(e){return{role:"assistant",content:"",tool_calls:e}}function ue(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 pe=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,h={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},de=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,me=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,fe=512,ge=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var ye=new Set([500,502,503,504,521,522,523,524,529]),he=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ce=["upgrade your plan","upgrade plan","current plan","subscription"],Te=["daily","weekly","monthly"],be=["try again","retry","temporary","cooldown"],ke=["usage limit","rate limit","organization usage"],_e=["organization","workspace"],Re=["billing period","exceeded","reached","exhausted"],xe=/["']?(?: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,Ae=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function C(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Se(e){return C(e,h.format)}function H(e){return C(e,h.rateLimit)}function ve(e){return C(e,h.timeout)}function Me(e){return pe.test(e)}function v(e){let t=e.toLowerCase();return t?e.length>fe?me.test(t):C(t,h.billing)?!0:de.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Y(e){return C(e,h.authPermanent)}function we(e){return C(e,h.auth)}function W(e){return C(e,h.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function Ee(e){return y(e,he)||y(e,Ce)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ie(e){let t=y(e,Te),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,_e);return y(e,be)&&y(e,ke)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,Re))}function Le(e){return e.trim().toLowerCase().replace(Ae,"").trim()}function K(e){let t=Le(e);return!t||Ee(t)?"billing":H(t)||Ie(t)?"rate_limit":"billing"}function Oe(e){return xe.test(e)?K(e):null}function X(e){let t=e.match(ge);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Pe(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Fe(e){let t=e.trim();if(!t)return!1;let n=X(t);return n?ye.has(n.code):!1}function J(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?K(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Y(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&W(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&v(t)?"billing":"format":null}function Ne(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 De(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 V(e){if(De(e))return"session_expired";if(Ne(e))return"model_not_found";let t=Oe(e);return t||(Me(e)?v(e)?"billing":"rate_limit":H(e)?"rate_limit":W(e)?"overloaded":Fe(e)?X(e.trim())?.code===529?"overloaded":"timeout":Pe(e)?"timeout":Se(e)?"format":v(e)?"billing":ve(e)?"timeout":Y(e)?"auth_permanent":we(e)?"auth":null)}var Be={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"},je={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 $e(e,t){let n=J(e,t)??(t?V(t):null);return n?Be[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function qe(e){return je[e]}function D(e){return typeof e.compressAsync=="function"}var Q=4,M=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let c of t)c.role==="system"?o.push(c):r.push(c);let a=n;for(let c of o)a-=this.estimateTokens(c);let i;for(let c of r)if(c.role==="user"){i=c;break}if(i&&(a-=this.estimateTokens(i)),a<=0)return{messages:i?[...o,i]:o,droppedCount:r.length-(i?1:0),strategy:"sliding-window"};let s=[],l=0;for(let c=r.length-1;c>=0;c--){let d=r[c];if(d===i)continue;let p=this.estimateTokens(d);if(a-p<0&&l>=Q)break;if(a-p<0&&l<Q){s.unshift(d),l++;continue}a-=p,s.unshift(d),l++}let u=[...o];return i&&!s.includes(i)&&u.push(i),u.push(...s),{messages:u,droppedCount:r.length-(s.length+(i&&!s.includes(i)?1:0)),strategy:"sliding-window"}}},w=class{constructor(t,n){this.recentCount=t;this.summarize=n}recentCount;summarize;compress(t,n){let o=t.filter(l=>l.role==="system"),r=t.filter(l=>l.role!=="system");if(r.length<=this.recentCount)return{messages:t,droppedCount:0,strategy:"summarize-old"};let a=r.slice(0,r.length-this.recentCount),i=r.slice(r.length-this.recentCount),s=this.summarize(a);return{messages:[...o,{role:"system",content:`[Conversation summary]
2
+ ${s}`},...i],droppedCount:a.length,strategy:"summarize-old"}}},E=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:Ge(a.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function Ge(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(`}
3
+ `),n.lastIndexOf(`]
4
+ `));if(a>t*.5)return n.slice(0,a+1)+`
5
+ [...truncated: ${e.length-a-1} chars omitted]`}let r=n.lastIndexOf(`
6
+ `);return r>t*.7?n.slice(0,r)+`
7
+ [...truncated: ${e.length-r} chars omitted]`:n+`
8
+ [...truncated: ${e.length-t} chars omitted]`}function ze(...e){return{compress(t,n){let o=t,r=0,a=[];for(let i of e){let s=i.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"}}}}function Ue(...e){return{compress(t,n){let o=t,r=0,a=[];for(let i of e){let s=i.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"}},async compressAsync(t,n){let o=t,r=0,a=[],i=0,s=!1,l=!1;for(let u of e){let c=D(u)?await u.compressAsync(o,n):u.compress(o,n);o=c.messages,r+=c.droppedCount,c.droppedCount>0&&a.push(c.strategy),c.metrics&&(i+=c.metrics.latencyMs,s=s||c.metrics.usedLlm,l=l||!!c.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:a.length>0?a.join("+"):"none",metrics:i>0||s?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:i,usedLlm:s,cacheInvalidated:l}:void 0}}}}function B(e,t){let n=e.filter(i=>i.role==="user"),o=e.filter(i=>i.tool_calls!=null),r=e.filter(i=>i.role==="tool"),a=["You are a conversation summarizer. Produce a structured summary of the conversation history below.","","## Instructions","Analyze the conversation and produce a summary with these sections:","","### 1. Primary Objective","What is the user's main goal or task? State it in one sentence.","","### 2. Key Decisions Made","List the important decisions, choices, or conclusions reached during the conversation.","","### 3. Current Progress",`Describe the current state. ${o.length>0?`${o.length} tool calls and ${r.length} tool results were exchanged.`:"No tools were used."}`,"","### 4. Pending Tasks","List any tasks that are in-progress or planned but not yet completed.","","### 5. Important Context","Note any critical facts, constraints, or preferences the user mentioned that must be preserved.","","### 6. Error & Recovery History","Summarize any errors encountered and how they were resolved.","","### 7. User Preferences Expressed",`The user sent ${n.length} messages. Note any stated preferences about style, approach, or constraints.`,"","### 8. Technical State","Note file paths, variable names, API endpoints, or configuration values that were discussed.","","### 9. Conversation Flow","Briefly describe the overall flow: what happened first, what changed, where we are now."];return t?.taskContext&&a.push("","## Additional Context",t.taskContext),a.push("","## Conversation to Summarize","",...e.map(i=>{let s=typeof i.content=="string"?i.content:JSON.stringify(i.content??""),l=i.role==="user"?s:s.length>2e3?s.slice(0,2e3)+"...":s;return`[${i.role}]: ${l}`}),"","## Output Format","Respond with a concise summary covering all 9 sections above. Use markdown headers.","Keep the total summary under 800 words. Focus on actionable information."),a.join(`
9
+ `)}var I=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??x,taskContext:t.taskContext}}compress(t,n){return{messages:t,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:a}=ee(t),i=t.reduce((f,g)=>f+this.config.estimateTokens(g),0);if(i<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let s=0,l=0;for(let f=0;f<a.length&&(a[f].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));f++)s=f+1;let u=Math.max(s,a.length-this.config.protectedTailMessages);if(u<=s)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let c=a.slice(0,s),d=a.slice(s,u),p=a.slice(u),m=B(d,{taskContext:this.config.taskContext}),T=await this.config.summarize(d,m),A={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
10
+
11
+ ${T}`},b=[...r,...c,A,...p],k=Date.now()-o,_=b.reduce((f,g)=>f+this.config.estimateTokens(g),0);return{messages:b,droppedCount:d.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:_,compressionRatio:i>0?_/i:1,latencyMs:k,usedLlm:!0,cacheInvalidated:!0}}}},L=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??x}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:a}=ee(t),i=r.findIndex(g=>typeof g.content=="string"&&g.content.startsWith("[Conversation summary")),s=i>=0?r[i]:void 0,l=i>=0?[...r.slice(0,i),...r.slice(i+1)]:r,u=Math.max(0,a.length-this.config.preserveRecentCount);if(u<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let c=t.reduce((g,S)=>g+this.config.estimateTokens(S),0);if(c<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=a.slice(0,u),p=a.slice(u),m=s&&typeof s.content=="string"?`Previous summary:
12
+ ${s.content}
13
+
14
+ New messages to integrate:`:void 0,T=B(d,{taskContext:m}),A=await this.config.summarize(d,T),b={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
15
+
16
+ ${A}`},k=[...l,b,...p],_=Date.now()-o,f=k.reduce((g,S)=>g+this.config.estimateTokens(S),0);return{messages:k,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:c,tokensAfter:f,compressionRatio:c>0?f/c:1,latencyMs:_,usedLlm:!0,cacheInvalidated:!0}}}},O=class{config;constructor(t){this.config=t}compress(t,n){let o=R(t),r=this.config.inner.compress(t,n),a=R(r.messages),i=o!==a&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}async compressAsync(t,n){let o=R(t),r=D(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),a=R(r.messages),i=o!==a&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}},Z={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function He(e={}){let t={...Z,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function Ye(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var P=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,i=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&&i++;return{totalCompressions:t,totalLlmCalls:a,totalCacheInvalidations:i,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},F=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 ee(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function x(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function R(e){let t=Math.min(e.length,5),n=[];for(let o=0;o<t;o++){let r=e[o],a=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${a}`)}return n.join("|")}var We=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"]),N=class{constructor(t=20,n=x){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,l)=>{if(l>=o||s.role!=="tool"||typeof s.content!="string"||!s.name||!We.has(s.name)||s.content.length<=200)return s;let u=this.estimateTokens(s);return a+=u,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){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let a=r.function?.name??"";if(/read|edit|write|file/i.test(a)&&r.function?.arguments)try{let i=JSON.parse(r.function.arguments),s=i.path??i.filePath??i.file_path??i.file;s&&typeof s=="string"&&t.set(s,n)}catch{}}o.role==="tool"&&o.name&&/read|edit|write|file/i.test(o.name)}return[...t.entries()].sort((n,o)=>o[1]-n[1]).map(([n])=>n)}async function Xe(e,t,n){let o=n.estimateTokens??(p=>Math.ceil(p.length/4)),r=Ke(t);if(r.length===0)return e;let a=e.map(p=>typeof p.content=="string"?p.content:"").join(`
17
+ `),i=r.filter(p=>!a.includes(p));if(i.length===0)return e;let s=n.maxTokenBudget,l=[],u=0;for(let p of i){if(u>=n.maxFiles||s<=0)break;let m=await n.readFile(p);if(!m)continue;let T=o(m);T>s||(s-=T,u++,l.push({role:"system",content:`[Post-compact file recovery: ${p}]
18
+
19
+ ${m}`}))}if(l.length===0)return e;let c=[...e],d=-1;for(let p=0;p<c.length;p++)c[p].role==="system"&&(d=p);return c.splice(d+1,0,...l),c}function Je(e,t,n=x){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,a=[];for(let s of e){let l=s.tool_call_id??"";if(l&&t.has(l)){o+=n(s),r++,t.delete(l);continue}a.push(s)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:a,tokensFreed:o,removedCount:r,boundaryMessage:i}}function Ve(){return{stages:[]}}function Qe(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let a=te(e,t),i=et(a,t,o);if(i.length===0)return{messages:a,stagedCount:0};for(let s of i)t.stages.push(s);return a=te(e,t),{messages:a,stagedCount:i.length}}function Ze(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:ne(e,t),committed:n}}function te(e,t){return t.stages.filter(o=>o.committed).length===0?e:ne(e,t)}function ne(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,i]=r.range;if(a>=o.length)continue;let s=Math.min(i,o.length),l={role:"system",content:r.summary};o.splice(a,s-a,l)}return o}function et(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],a=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,s=0;for(let l=0;l<o;l++){let u=e[l];if(u.role==="tool"||u.role==="assistant"&&typeof u.content=="string"&&u.content==="")i<0&&(i=l),s++;else{if(s>=3){let d=`${i}-${i+s}`;a.has(d)||r.push({id:`collapse_${i}_${i+s}`,range:[i,i+s],summary:`[${s} tool results collapsed]`,committed:!1})}i=-1,s=0}}if(s>=3){let l=`${i}-${i+s}`;a.has(l)||r.push({id:`collapse_${i}_${i+s}`,range:[i,i+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}function tt(e){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<3||e.distinctToolCount<2)}function nt(e){return e.existingSkillName?e.feedback==="negative":!1}function ot(e,t){return nt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:tt(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 oe(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 rt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function st(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function it(e){if(!e.eligibility?.length)return[...e.tools];let t=st(e.eligibility);return e.tools.filter(n=>{let o=oe(n);if(!o)return!1;let r=t.get(o);return!r||rt(r.status)})}function at(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 lt(e){let t=at({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=it({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,i=typeof a?.name=="string"?a.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let s=r.filter(l=>oe(l)===i);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var ct=["stop","aborted","timeout","cancelled","interrupted","error"],ut=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function re(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function pt(e,t){return{...e,content:[...re(e.content),...re(t.content)]}}function dt(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 mt(e){return new Set((e??ct).map(t=>t.trim().toLowerCase()))}function se(e,t){return e?mt(t).has(e.trim().toLowerCase()):!1}function ft(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function j(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 l=s.tool_calls.filter(u=>dt(u));return{...s,...l.length>0?{tool_calls:l}:{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 l of s.tool_calls)typeof l.id=="string"&&l.id&&n.add(l.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 l=s.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(l.length===0){let{tool_calls:u,...c}=s;c.content!=null&&c.content!==""&&a.push(c);continue}if(l.length<s.tool_calls.length){a.push({...s,tool_calls:l});continue}}a.push(s)}let i=[];for(let s of a){let l=i.length>0?i[i.length-1]:void 0;if(s.role==="user"&&l?.role==="user"){i[i.length-1]=pt(l,s);continue}i.push(s)}return i}function $(e,t){return se(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of ut)delete o[r];return o}):[...e]}function q(e,t){let n=t?.placeholderToolResult??JSON.stringify({ok:!1,error:"Tool loop interrupted before the tool result was replayed."}),o=new Set;for(let 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 i of a.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function gt(e,t){let n=j(e),o=$(n,t);return q(o,t)}function ie(e,t){let n=t?.placeholderFunctionCallOutput??JSON.stringify({ok:!1,error:"Tool loop interrupted before function_call_output was provided."}),o=se(t?.stopReason,t?.forcedStopReasons),r=[];for(let u=0;u<e.length;u+=1){let c=e[u];if(!c||typeof c!="object"){r.push(c);continue}if(c.type==="reasoning"&&typeof c.id=="string"&&c.id.startsWith("rs_")&&!e.slice(u+1).some(m=>m&&typeof m=="object"&&m.type!=="reasoning"))continue;if(c.type!=="function_call"){r.push({...c});continue}let d={...c};if(typeof d.id=="string"){let p=ft(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let a=new Set,i=new Map;for(let u of r){if(u.type!=="function_call")continue;let c=typeof u.call_id=="string"&&u.call_id?u.call_id:typeof u.id=="string"?u.id:void 0;c&&(a.add(c),i.set(c,u))}let s=new Set,l=[];for(let u of r)if(!(o&&u.type==="function_call")){if(u.type==="function_call_output"){let c=typeof u.call_id=="string"?u.call_id:"";if(!c||!a.has(c))continue;s.add(c)}l.push(u)}for(let[u]of i)s.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function yt(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 ht(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 Ct(e){let t=new Set,n=new Set;for(let o of e){if(o.type==="function_call"){let r=typeof o.call_id=="string"&&o.call_id?o.call_id:typeof o.id=="string"?o.id:"";r&&t.add(r)}o.type==="function_call_output"&&typeof o.call_id=="string"&&o.call_id&&n.add(o.call_id)}return[...t].filter(o=>!n.has(o))}function Tt(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function ae(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function bt(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 kt(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 _t(e){let t=[],n=j(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=$(n,e.options);o.some((a,i)=>a!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=q(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:ae({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:yt(r),completedToolCallIds:ht(r)}),recoveryActions:t}}function Rt(e){let t=ie(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:ae({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:Ct(t),completedToolCallIds:Tt(t)}),recoveryActions:n}}var xt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function At(e){return e?xt.has(e):!0}function St(e){return e===429||e===529}function vt(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 yn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Mt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var G=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var z="<fork-child-context>",le="Fork started \u2014 processing in background",wt=4;function Et(e){return JSON.stringify(e).includes(z)}function It(e){return e<4}function Lt(e,t){let n=[...e.parentMessages],o={role:"user",content:[{type:"text",text:`${z}
20
+
21
+ You are the "${t.agent.name}" agent.
22
+
23
+ ${t.taskPrompt}`}]};return n.push(o),n}function Ot(e){return e.map(t=>({role:"tool",tool_call_id:t,content:le}))}function Pt(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolAccessMode==="none")return[];if(t.toolAccessMode==="read-only"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent")}function Ft(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var Nt={name:"general",label:"General Purpose",description:"A general-purpose sub-agent that can perform any task with full tool access.",maxTurns:200,toolAccessMode:"full",canFork:!1},Dt={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","tool_search"],canFork:!1},Bt={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","todo","tool_search"],canFork:!1},jt={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},$t={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolAccessMode:"read-only",allowedTools:["web_search","web_fetch","read_file","search","think","memory"],canFork:!1},qt={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolAccessMode:"full",allowedTools:["exec","read_file","search","think"],canFork:!1},U=[Nt,Dt,Bt,jt,$t,qt];function Gt(){return[...U]}function zt(e){return U.find(t=>t.name===e)}function Ut(e){return U.some(t=>t.name===e)}function Ht(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolAccessMode==="none")return[];if(e.toolAccessMode==="read-only"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(o=>!n.has(o))}return e.canFork?[...t]:t.filter(n=>n!=="agent_tool"&&n!=="team_create")}var Yt=new Set(["agent_tool","team_create","fork_agent","send_message"]);function Wt(e,t){switch(e){case"worker":return t.filter(n=>!Yt.has(n));case"coordinator":return[...t];default:return[...t]}}function Kt(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function Xt(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Jt(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 Vt(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 Qt(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 Zt(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var en={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function tn(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
24
+ ${n.join(`
25
+ `)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
26
+ Step ${e.activeSkillContext.step}:
27
+ ${e.activeSkillContext.instructions}`),e.toolDelta&&(e.toolDelta.added.length>0||e.toolDelta.removed.length>0)){let n=[];e.toolDelta.added.length>0&&n.push(`New tools available: ${e.toolDelta.added.join(", ")}`),e.toolDelta.removed.length>0&&n.push(`Tools no longer available: ${e.toolDelta.removed.join(", ")}`),t.push(`## Tool Changes
28
+ ${n.join(`
29
+ `)}`)}if(e.customBlocks)for(let n of e.customBlocks)t.push(`## ${n.label}
30
+ ${n.content}`);return t.length===0?null:`[Context was compressed. The following state has been restored:]
31
+
32
+ ${t.join(`
33
+
34
+ `)}`}function nn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function on(e,t=en){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{O as CacheAwareCompressionStrategy,P as CompressionMetricsCollector,F as ContextEngineRegistry,Z as DEFAULT_ADAPTIVE_BUDGET_CONFIG,le as FORK_PLACEHOLDER_RESULT,z as FORK_SENTINEL_TAG,G as FallbackTriggeredError,I as HeadTailProtectedStrategy,L as IncrementalCompactStrategy,wt as MAX_FORK_DEPTH,N as MicroCompactStrategy,M as SlidingWindowStrategy,w as SummarizeOldStrategy,E as ToolResultTrimStrategy,bt as advanceToolLoopState,Qe as applyContextCollapsesIfNeeded,lt as applyToolChoicePolicy,ce as buildAssistantToolCallMessage,Ot as buildForkPlaceholderResults,Lt as buildForkedMessages,tn as buildPostCompactRestorationMessage,ot as buildSkillInstruction,B as buildStructuredSummaryPrompt,ue as buildToolResultMessage,Jt as calculateTokenWarningState,It as canForkAtDepth,$e as classifyError,Ue as composeAsyncStrategies,ze as composeStrategies,He as computeAdaptiveBudget,vt as computeRetryBackoff,Ve as createCollapseStore,nn as createReactiveCompactState,Kt as createTaskState,Xt as createTurnLoopGuardState,Wt as filterToolsByRole,Ft as generateForkChildAgentId,zt as getBuiltInAgent,Gt as getBuiltInAgents,qe as getRetryStrategy,D as isAsyncCompressionStrategy,Ut as isBuiltInAgent,At as isForegroundSource,Et as isInForkChild,Mt as isPersistentRetryEnabled,St as isTransientCapacityError,Xe as postCompactFileRecovery,Ze as recoverContextCollapseFromOverflow,_t as recoverToolLoopStateFromChatConversation,Rt as recoverToolLoopStateFromResponsesItems,gt as repairOpenAiChatConversation,Ht as resolveAgentToolSet,Vt as resolveApiErrorRecovery,Pt as resolveForkChildTools,Qt as resolveOutputTokenEscalation,Ye as selectCompressionTier,kt as settleToolLoopState,Zt as shouldAbortTurn,on as shouldAttemptReactiveCompact,Je as snipCompactIfNeeded};
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Agent — clean agent execution loop for CLI subprocess mode.
3
+ *
4
+ * Thin wrapper around tool-loop.ts. Handles:
5
+ * - DI injection (LLMTransport, ToolInvoker, AgentLogger)
6
+ * - Turn lifecycle (start event + message repair + delegate to tool loop)
7
+ * - Top-level error handling
8
+ *
9
+ * The actual tool loop state machine (turn-loop-guard, tool-loop-state,
10
+ * parallel scheduling, tool filtering, etc.) lives in tool-loop.ts,
11
+ * ported faithfully from Hub's semantic-turn-tools.ts.
12
+ *
13
+ * Zero imports from express/pg/ioredis/ws.
14
+ */
15
+ import type { AgentLogger, ToolInvoker, TurnEvent, TurnRequest, HookRegistry } from "./types.js";
16
+ import type { LLMTransport } from "../llm/transport.js";
17
+ export interface AgentConfig {
18
+ llmTransport: LLMTransport;
19
+ apiKey: string;
20
+ toolInvoker: ToolInvoker;
21
+ log: AgentLogger;
22
+ hooks?: HookRegistry;
23
+ maxRounds?: number;
24
+ verbose?: boolean;
25
+ }
26
+ export declare class Agent {
27
+ private transport;
28
+ private apiKey;
29
+ private toolInvoker;
30
+ private log;
31
+ private hooks?;
32
+ private maxRounds;
33
+ constructor(config: AgentConfig);
34
+ /**
35
+ * Execute an agent turn. Yields TurnEvent stream.
36
+ *
37
+ * 1. Emit start
38
+ * 2. Repair conversation history
39
+ * 3. Delegate to executeToolLoop() (full Hub-ported tool loop state machine)
40
+ * 4. Catch unhandled errors
41
+ */
42
+ run(request: TurnRequest, signal?: AbortSignal): AsyncGenerator<TurnEvent>;
43
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Centralized agent configuration constants.
3
+ *
4
+ * All default parameters for agent loop, tool loop, and
5
+ * CC-aligned recovery live here. Consumers import from this module
6
+ * instead of hardcoding magic numbers.
7
+ *
8
+ * CC reference: Various — CC scatters these across query.ts,
9
+ * withRetry.ts, tokenBudget.ts. We centralize for maintainability.
10
+ */
11
+ /** Absolute max rounds any agent can run (hard cap). */
12
+ export declare const MAX_ROUNDS_LIMIT = 100;
13
+ /** Default rounds for a top-level agent turn. */
14
+ export declare const DEFAULT_MAX_ROUNDS = 25;
15
+ /** Hard cap on tool calls per round (prevents runaway). */
16
+ export declare const MAX_TOOL_BUDGET_CAP = 100;
17
+ /** Default tool budget per round. Overridable via TOOL_LOOP_DEFAULT_BUDGET env. */
18
+ export declare const DEFAULT_TOOL_BUDGET: number;
19
+ /** Max consecutive tool call failures before early exit. */
20
+ export declare const MAX_CONSECUTIVE_FAILURES = 3;
21
+ /** Default context window size (tokens). Used when model-specific size unknown. */
22
+ export declare const DEFAULT_CONTEXT_WINDOW_TOKENS = 128000;
23
+ /** Reserved tokens for model response output in turn-loop-guard budget check. */
24
+ export declare const RESPONSE_BUFFER_TOKENS = 13000;
25
+ /** Default max output tokens per LLM API call. */
26
+ export declare const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
27
+ /** Model's absolute max output tokens (escalation ceiling). */
28
+ export declare const DEFAULT_MODEL_MAX_OUTPUT_TOKENS = 65536;
29
+ /** Max max_output_tokens recovery attempts before surfacing the error (CC: 3). */
30
+ export declare const MAX_OUTPUT_TOKENS_RECOVERY_LIMIT = 3;
31
+ /** Escalated max output tokens — retry at this ceiling before multi-turn recovery (CC: 64k). */
32
+ export declare const ESCALATED_MAX_OUTPUT_TOKENS = 65536;
33
+ /** Heartbeat interval during persistent retry waits (CC: 30 seconds). */
34
+ export declare const HEARTBEAT_INTERVAL_MS = 30000;
35
+ /** Max consecutive 529 errors before fallback model switch (CC: 3). */
36
+ export declare const MAX_529_RETRIES = 3;
37
+ /** Max consecutive API error retries before aborting (prevents infinite retry loops). */
38
+ export declare const MAX_API_RETRIES = 5;
39
+ /** Per-tool result size threshold (chars). Results exceeding this are persisted to disk
40
+ * and replaced with a preview reference (CC: DEFAULT_MAX_RESULT_SIZE_CHARS = 50_000). */
41
+ export declare const DEFAULT_MAX_RESULT_SIZE_CHARS = 50000;
42
+ /** Per-message aggregate budget (chars). When a group of tool results in one response
43
+ * batch exceeds this, the largest fresh results are persisted until under budget
44
+ * (CC: MAX_TOOL_RESULTS_PER_MESSAGE_CHARS = 200_000). */
45
+ export declare const MAX_TOOL_RESULTS_PER_MESSAGE_CHARS = 200000;
46
+ /** Preview size for persisted tool result reference messages (CC: PREVIEW_SIZE_BYTES = 2000). */
47
+ export declare const TOOL_RESULT_PREVIEW_BYTES = 2000;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Tool access constants for sub-agent tool filtering.
3
+ *
4
+ * CC-aligned: constants/tools.ts pattern.
5
+ * Tool filtering happens at agent SPAWN time (not per-iteration in tool loop).
6
+ *
7
+ * CC reference: claude-code-haha/src/constants/tools.ts
8
+ * CC reference: claude-code-haha/src/tools/AgentTool/agentToolUtils.ts
9
+ */
10
+ import type { ToolDefinition } from "./types.js";
11
+ /**
12
+ * Tools that ALL sub-agents are forbidden from using.
13
+ * CC: ALL_AGENT_DISALLOWED_TOOLS
14
+ */
15
+ export declare const AGENT_DISALLOWED_TOOLS: Set<string>;
16
+ /**
17
+ * Additional tools denied for custom (user-defined) agents.
18
+ * CC: CUSTOM_AGENT_DISALLOWED_TOOLS
19
+ */
20
+ export declare const CUSTOM_AGENT_DISALLOWED_TOOLS: Set<string>;
21
+ /**
22
+ * Filter tools available to a sub-agent.
23
+ *
24
+ * CC pattern: tool filtering happens at agent SPAWN time,
25
+ * not per-iteration inside the tool loop.
26
+ *
27
+ * @param tools - Parent's full tool pool
28
+ * @param isBuiltIn - Whether the agent is a built-in agent type (vs custom)
29
+ */
30
+ export declare function filterToolsForAgent(tools: ToolDefinition[], isBuiltIn: boolean): ToolDefinition[];
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Tool loop state machine — CC query.ts aligned.
3
+ *
4
+ * Architecture:
5
+ * - Infinite while(true) loop with centralized State object (CC parity)
6
+ * - 7 labeled continue sites matching CC's query loop transitions
7
+ * - Error Withholding: 413 / max_output_tokens / media errors are
8
+ * withheld from callers during recovery attempts
9
+ * - Context Collapse drain: staged collapses committed on 413
10
+ * BEFORE falling through to reactive compact
11
+ * - Media error recovery: image/media errors → reactive compact retry
12
+ * - Hermes delta suppression preserved
13
+ * - StreamingToolExecutor preserved
14
+ * - Sub-agent fork depth preserved
15
+ * - Skill learning evaluation preserved
16
+ *
17
+ * CC reference: src/query.ts queryLoop()
18
+ *
19
+ * Zero imports from express/pg/ioredis/ws.
20
+ */
21
+ import type { AgentLogger, ChatMessage, ToolDefinition, ToolInvoker, TurnEvent, HookRegistry } from "./types.js";
22
+ import type { LLMTransport } from "../llm/transport.js";
23
+ export interface ToolLoopParams {
24
+ turnId: string;
25
+ sessionId: string;
26
+ messages: ChatMessage[];
27
+ tools: ToolDefinition[];
28
+ model: string;
29
+ apiKey: string;
30
+ temperature?: number;
31
+ maxRounds?: number;
32
+ /** Context window size in tokens (for turn-loop-guard budget checks) */
33
+ contextWindowTokens?: number;
34
+ /** Max output tokens for current model */
35
+ maxOutputTokens?: number;
36
+ /** Model's absolute max output tokens (escalation ceiling) */
37
+ modelMaxOutputTokens?: number;
38
+ /** Tool choice strategy (default "auto") */
39
+ toolChoice?: "auto" | "none" | "required";
40
+ /** Parent fork depth (0 = top-level) */
41
+ parentDepth?: number;
42
+ /** Tool eligibility context for policy-based filtering */
43
+ toolEligibilityContext?: import("../runtime/execution/tool-eligibility.js").ToolEligibilityContext;
44
+ /** Hook registry for lifecycle events (optional, fire-and-forget) */
45
+ hooks?: HookRegistry;
46
+ /** Max turns (loop iterations). 0 = use maxRounds. */
47
+ maxTurns?: number;
48
+ /** Fallback model to switch to after repeated 529 errors (CC parity). */
49
+ fallbackModel?: string;
50
+ /** Query source for foreground/background retry distinction (CC parity). */
51
+ querySource?: string;
52
+ /** Token budget for this turn (>0 enables budget continuation). */
53
+ tokenBudget?: number;
54
+ /**
55
+ * Refresh tools callback — called between turns (CC refreshTools parity).
56
+ * Returns updated tool definitions if tools have changed (e.g. MCP reconnect),
57
+ * or the same array reference if unchanged.
58
+ */
59
+ refreshTools?: () => ToolDefinition[];
60
+ /**
61
+ * Generate a human-readable summary label for a tool batch (CC generateToolUseSummary parity).
62
+ * Fire-and-forget: called after tool execution, result yielded as tool_use_summary event
63
+ * when the next LLM round starts streaming. ~30 chars, git-commit-subject style.
64
+ */
65
+ generateToolUseSummary?: (toolCalls: Array<{
66
+ name: string;
67
+ arguments: string;
68
+ result?: string;
69
+ }>) => Promise<string | null>;
70
+ /**
71
+ * Post-sampling hooks — fire-and-forget after LLM response completes (CC executePostSamplingHooks parity).
72
+ * Cannot modify messages. Used for background tasks (memory extraction, skill learning, etc.).
73
+ */
74
+ postSamplingHooks?: Array<(context: {
75
+ messages: unknown[];
76
+ model: string;
77
+ sessionId: string;
78
+ }) => Promise<void> | void>;
79
+ /** Max concurrent tool executions (0 = unlimited, CC parity: semantic concurrency control). */
80
+ maxConcurrentTools?: number;
81
+ signal?: AbortSignal;
82
+ }
83
+ /**
84
+ * Execute the tool loop — CC query.ts queryLoop() aligned.
85
+ *
86
+ * Yields TurnEvent stream. The caller (Agent class) wraps this with
87
+ * start/end lifecycle and error handling.
88
+ *
89
+ * Architecture: infinite while(true) with centralized State + 7 continue
90
+ * labels. Error withholding gates recoverable errors through collapse
91
+ * drain → reactive compact → escalation → recovery message pipeline
92
+ * before surfacing to callers.
93
+ */
94
+ export declare function executeToolLoop(params: ToolLoopParams, transport: LLMTransport, toolInvoker: ToolInvoker, log: AgentLogger): AsyncGenerator<TurnEvent>;
@@ -0,0 +1,238 @@
1
+ /**
2
+ * Pure agent types — zero I/O framework dependencies.
3
+ *
4
+ * These types define the contract between:
5
+ * - CLI stdio layer ↔ Agent class
6
+ * - Agent class ↔ LLM Provider
7
+ * - Agent class ↔ Tool loop
8
+ *
9
+ * Ported from Hub semantic-turn-shared.ts / semantic-turn-tools.ts,
10
+ * with Hub infrastructure (WS/PG/Redis) replaced by DI interfaces.
11
+ *
12
+ * No imports from express/pg/ioredis/ws.
13
+ */
14
+ import type { SkillInstruction } from "../orchestration/index.js";
15
+ import type { HookRegistry } from "../contracts/hooks.js";
16
+ export type ChatMessageRole = "system" | "user" | "assistant" | "tool";
17
+ export interface ChatMessage {
18
+ role: ChatMessageRole;
19
+ content: string | null;
20
+ /** For assistant messages with tool calls */
21
+ tool_calls?: ToolCallMessage[];
22
+ /** For tool result messages */
23
+ tool_call_id?: string;
24
+ /** For tool result messages — tool name */
25
+ name?: string;
26
+ }
27
+ export interface ToolCallMessage {
28
+ id: string;
29
+ type: "function";
30
+ function: {
31
+ name: string;
32
+ arguments: string;
33
+ };
34
+ }
35
+ export interface ToolDefinition {
36
+ type: "function";
37
+ function: {
38
+ name: string;
39
+ description: string;
40
+ parameters?: Record<string, unknown>;
41
+ };
42
+ /** Tool scheduling metadata from host manifest (optional) */
43
+ meta?: {
44
+ serialOnly?: boolean;
45
+ parallelSafe?: boolean;
46
+ /** If true, host should request user approval before execution (CC PreToolUse parity) */
47
+ requiresApproval?: boolean;
48
+ /** Tool is read-only / safe — skip approval even in strict mode */
49
+ isReadOnly?: boolean;
50
+ /** Tool can cause irreversible side-effects — force approval in default mode */
51
+ isDangerous?: boolean;
52
+ };
53
+ /**
54
+ * Backfill derived/legacy fields onto a shallow copy of the tool input
55
+ * before hooks and observers see it (CC backfillObservableInput parity).
56
+ * The original API-bound input is never modified.
57
+ */
58
+ backfillObservableInput?: (input: Record<string, unknown>) => void;
59
+ }
60
+ export interface TokenUsage {
61
+ prompt: number;
62
+ completion: number;
63
+ /** Reasoning tokens (for models like o1/DeepSeek-R1) */
64
+ reasoning?: number;
65
+ /** Prompt cache read tokens (CC cache_read_input_tokens parity) */
66
+ cacheRead?: number;
67
+ /** Prompt cache creation tokens (CC cache_creation_input_tokens parity) */
68
+ cacheCreation?: number;
69
+ }
70
+ /**
71
+ * Why the previous iteration continued — each variant corresponds to one of
72
+ * the 7 `continue` sites in the main while(true) loop.
73
+ * Tests can assert recovery paths fired without inspecting message contents.
74
+ */
75
+ export type ToolLoopTransition = {
76
+ reason: "collapse_drain_retry";
77
+ committed: number;
78
+ } | {
79
+ reason: "reactive_compact_retry";
80
+ } | {
81
+ reason: "max_output_tokens_escalate";
82
+ } | {
83
+ reason: "max_output_tokens_recovery";
84
+ attempt: number;
85
+ } | {
86
+ reason: "stop_hook_blocking";
87
+ } | {
88
+ reason: "token_budget_continuation";
89
+ } | {
90
+ reason: "next_turn";
91
+ };
92
+ /** Terminal exit reasons from the tool loop. */
93
+ export type ToolLoopTerminal = {
94
+ reason: "completed";
95
+ } | {
96
+ reason: "aborted";
97
+ } | {
98
+ reason: "prompt_too_long";
99
+ } | {
100
+ reason: "image_error";
101
+ } | {
102
+ reason: "model_error";
103
+ error?: unknown;
104
+ } | {
105
+ reason: "max_turns";
106
+ } | {
107
+ reason: "budget_exhausted";
108
+ } | {
109
+ reason: "tool_loop_limit";
110
+ } | {
111
+ reason: "stop_hook_prevented";
112
+ } | {
113
+ reason: "hook_stopped";
114
+ };
115
+ export interface TurnRequest {
116
+ turnId: string;
117
+ sessionId: string;
118
+ messages: ChatMessage[];
119
+ tools: ToolDefinition[];
120
+ systemPrompt?: string;
121
+ config?: TurnConfig;
122
+ }
123
+ export interface TurnConfig {
124
+ /** LLM provider id, e.g. "deepseek" */
125
+ provider?: string;
126
+ /** Model id, e.g. "deepseek-chat" */
127
+ model?: string;
128
+ /** User API key */
129
+ apiKey?: string;
130
+ /** Optional base URL override */
131
+ baseUrl?: string;
132
+ /** Max tool-call rounds per turn (default 25, max 100) */
133
+ maxRounds?: number;
134
+ /** Temperature override */
135
+ temperature?: number;
136
+ /** Context window size in tokens (for turn-loop-guard budget checks) */
137
+ contextWindowTokens?: number;
138
+ /** Max output tokens for current model */
139
+ maxOutputTokens?: number;
140
+ /** Model's absolute max output tokens (for escalation ceiling) */
141
+ modelMaxOutputTokens?: number;
142
+ /** Tool choice strategy: "auto" (default), "none", "required" */
143
+ toolChoice?: "auto" | "none" | "required";
144
+ /** Parent fork depth (0 = top-level, default 0). CC: depth tracking for fork recursion limit. */
145
+ parentDepth?: number;
146
+ /** Per-turn token budget (prompt + completion). 0 or undefined = unlimited. */
147
+ tokenBudget?: number;
148
+ /** Fallback model to switch to after repeated 529 errors (CC parity). */
149
+ fallbackModel?: string;
150
+ /** Max turns (tool loop iterations). 0 or undefined = use maxRounds. */
151
+ maxTurns?: number;
152
+ /** Model for generating tool use summaries (CC parity: Haiku). If set, enables summary generation. */
153
+ summaryModel?: string;
154
+ /** Max concurrent tool executions (0 = unlimited). */
155
+ maxConcurrentTools?: number;
156
+ }
157
+ export type TurnEvent = {
158
+ type: "start";
159
+ turnId: string;
160
+ } | {
161
+ type: "delta";
162
+ turnId: string;
163
+ text: string;
164
+ } | {
165
+ type: "tool_call";
166
+ turnId: string;
167
+ callId: string;
168
+ name: string;
169
+ arguments: string;
170
+ } | {
171
+ type: "end";
172
+ turnId: string;
173
+ content: string;
174
+ usage?: TokenUsage;
175
+ model?: string;
176
+ provider?: string;
177
+ } | {
178
+ type: "error";
179
+ turnId: string;
180
+ error: string;
181
+ code?: string;
182
+ } | {
183
+ type: "skill_instruction";
184
+ turnId: string;
185
+ instruction: SkillInstruction;
186
+ } | {
187
+ type: "tool_result";
188
+ turnId: string;
189
+ callId: string;
190
+ name: string;
191
+ ok: boolean;
192
+ error?: string;
193
+ } | {
194
+ type: "tool_blocked";
195
+ turnId: string;
196
+ callId: string;
197
+ name: string;
198
+ reason: string;
199
+ } | {
200
+ type: "recovery";
201
+ turnId: string;
202
+ action: string;
203
+ detail?: string;
204
+ } | {
205
+ type: "plan_update";
206
+ turnId: string;
207
+ slug: string;
208
+ content: string;
209
+ } | {
210
+ type: "heartbeat";
211
+ turnId: string;
212
+ message: string;
213
+ } | {
214
+ type: "tool_use_summary";
215
+ turnId: string;
216
+ summary: string;
217
+ };
218
+ /**
219
+ * ToolInvoker: request tool execution from the host process (Gateway).
220
+ * In CLI mode this sends a JSON-RPC notification over stdio and waits for result.
221
+ */
222
+ export interface ToolInvoker {
223
+ invoke(turnId: string, name: string, args: string, signal?: AbortSignal): Promise<{
224
+ result: string;
225
+ error?: string;
226
+ }>;
227
+ }
228
+ /**
229
+ * AgentLogger: structured logging interface.
230
+ * In CLI mode this writes to stderr; in Hub mode this uses pino.
231
+ */
232
+ export interface AgentLogger {
233
+ info(message: string): void;
234
+ warn(message: string): void;
235
+ error(message: string): void;
236
+ debug(message: string): void;
237
+ }
238
+ export type { HookRegistry };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * qlogicagent CLI — Agent subprocess entry point.
3
+ *
4
+ * Communicates with host applications via JSON-RPC over pluggable transports.
5
+ * Default transport: line-delimited JSON over stdin/stdout.
6
+ * All log/debug output goes to stderr (never pollutes the protocol).
7
+ *
8
+ * Usage:
9
+ * qlogicagent [--verbose]
10
+ */
11
+ export {};