qlogicagent 2.12.7 → 2.12.9

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 (106) hide show
  1. package/README.md +91 -157
  2. package/dist/agent.js +6 -6
  3. package/dist/cli.js +411 -426
  4. package/dist/index.js +410 -425
  5. package/dist/orchestration.js +6 -6
  6. package/dist/protocol.js +1 -1
  7. package/dist/types/agent/memory-recall-injection.d.ts +34 -0
  8. package/dist/types/agent/tool-loop/budget-continuation-policy.d.ts +22 -0
  9. package/dist/types/agent/tool-loop/completion-action-policy.d.ts +19 -0
  10. package/dist/types/agent/tool-loop/completion-stop-policy.d.ts +19 -0
  11. package/dist/types/agent/tool-loop/compression-pipeline.d.ts +44 -0
  12. package/dist/types/agent/tool-loop/skill-instruction-policy.d.ts +7 -0
  13. package/dist/types/agent/tool-loop/stream-error-recovery.d.ts +59 -0
  14. package/dist/types/agent/tool-loop/tool-failure-policy.d.ts +22 -0
  15. package/dist/types/agent/types.d.ts +2 -2
  16. package/dist/types/cli/acp-message-router.d.ts +8 -0
  17. package/dist/types/cli/acp-session-host.d.ts +20 -4
  18. package/dist/types/cli/cli-agent-builder.d.ts +1 -1
  19. package/dist/types/cli/core-tool-coordinator.d.ts +1 -0
  20. package/dist/types/cli/core-tools/config-tool-bootstrap.d.ts +1 -5
  21. package/dist/types/cli/core-tools/config-tool-service.d.ts +9 -5
  22. package/dist/types/cli/core-tools/registry.d.ts +1 -2
  23. package/dist/types/cli/core-tools/session-tool-manifest.d.ts +11 -0
  24. package/dist/types/cli/core-tools/team-registry.d.ts +8 -8
  25. package/dist/types/cli/core-tools/team-tool-service.d.ts +6 -3
  26. package/dist/types/cli/dev-tools/dev-tool-registry.d.ts +1 -2
  27. package/dist/types/cli/gateway-rpc-connection.d.ts +50 -0
  28. package/dist/types/cli/handlers/session-handler.d.ts +2 -1
  29. package/dist/types/cli/handlers/workflow-handler.d.ts +10 -0
  30. package/dist/types/cli/model-client-resolver.d.ts +12 -3
  31. package/dist/types/cli/resolved-agent-cache.d.ts +47 -0
  32. package/dist/types/cli/rpc-registry.d.ts +59 -5
  33. package/dist/types/cli/session-context.d.ts +32 -0
  34. package/dist/types/cli/skill-meta-tool-bootstrap.d.ts +7 -0
  35. package/dist/types/cli/stdio-acp-protocol-coordinator.d.ts +18 -0
  36. package/dist/types/cli/stdio-acp-request-host.d.ts +3 -0
  37. package/dist/types/cli/stdio-rpc-handler-hosts.d.ts +50 -0
  38. package/dist/types/cli/stdio-server.d.ts +103 -178
  39. package/dist/types/cli/stdio-session-runtime-coordinator.d.ts +19 -0
  40. package/dist/types/cli/tool-bootstrap-core-registration.d.ts +30 -0
  41. package/dist/types/cli/tool-bootstrap-media-registration.d.ts +8 -0
  42. package/dist/types/cli/tool-bootstrap-paths.d.ts +7 -0
  43. package/dist/types/cli/tool-bootstrap-web-registration.d.ts +13 -0
  44. package/dist/types/cli/tool-bootstrap-workflow-registration.d.ts +7 -0
  45. package/dist/types/cli/tool-bootstrap.d.ts +5 -22
  46. package/dist/types/cli/tunable-store.d.ts +26 -0
  47. package/dist/types/cli/workflow-host-adapter.d.ts +29 -0
  48. package/dist/types/contracts/hooks.d.ts +6 -0
  49. package/dist/types/orchestration/workflow/run-history-store.d.ts +58 -0
  50. package/dist/types/orchestration/workflow/workflow-controller.d.ts +23 -1
  51. package/dist/types/orchestration/workflow/workflow-store.d.ts +24 -0
  52. package/dist/types/protocol/wire/acp-protocol.d.ts +1 -2
  53. package/dist/types/protocol/wire/gateway-rpc.d.ts +0 -112
  54. package/dist/types/runtime/config/tunable-defaults.d.ts +6 -0
  55. package/dist/types/runtime/infra/agent-paths.d.ts +0 -2
  56. package/dist/types/runtime/infra/agent-process.d.ts +12 -9
  57. package/dist/types/runtime/infra/default-path-service.d.ts +0 -1
  58. package/dist/types/runtime/infra/index.d.ts +1 -1
  59. package/dist/types/runtime/infra/key-pool.d.ts +1 -0
  60. package/dist/types/runtime/infra/llmrouter-catalog.d.ts +8 -0
  61. package/dist/types/runtime/ports/path-service.d.ts +0 -1
  62. package/dist/types/runtime/ports/tool-contracts.d.ts +1 -1
  63. package/dist/types/runtime/prompt/environment-context.d.ts +13 -0
  64. package/dist/types/runtime/prompt/index.d.ts +1 -0
  65. package/dist/types/runtime/prompt/prompt-policy.d.ts +2 -0
  66. package/dist/types/runtime/prompt/system-prompt-sections.d.ts +2 -0
  67. package/dist/types/runtime/session/session-catalog.d.ts +4 -0
  68. package/dist/types/runtime/session/session-metadata-store.d.ts +8 -0
  69. package/dist/types/runtime/session/session-paths.d.ts +9 -0
  70. package/dist/types/runtime/session/session-persistence.d.ts +14 -159
  71. package/dist/types/runtime/session/session-resume.d.ts +4 -0
  72. package/dist/types/runtime/session/session-schema.d.ts +10 -0
  73. package/dist/types/runtime/session/session-summary.d.ts +5 -0
  74. package/dist/types/runtime/session/session-transcript-store.d.ts +13 -0
  75. package/dist/types/runtime/session/session-types.d.ts +77 -0
  76. package/dist/types/runtime/session/session-write-queue.d.ts +2 -0
  77. package/dist/types/runtime/tasks/task-types.d.ts +1 -1
  78. package/dist/types/skills/mcp/index.d.ts +1 -3
  79. package/dist/types/skills/mcp/mcp-manager.d.ts +14 -38
  80. package/dist/types/skills/permissions/rule-engine.d.ts +1 -0
  81. package/dist/types/skills/plugins/plugin-api.d.ts +0 -1
  82. package/dist/types/skills/plugins/plugin-loader.d.ts +0 -4
  83. package/dist/types/skills/portable-tool.d.ts +2 -2
  84. package/dist/types/skills/tools/config-tool.d.ts +1 -3
  85. package/dist/types/skills/tools/skill-tool.d.ts +2 -2
  86. package/dist/types/skills/tools/team-tool.d.ts +44 -4
  87. package/dist/types/skills/tools/tool-search-tool.d.ts +11 -0
  88. package/package.json +3 -2
  89. package/dist/types/assistants/assistant-registry.d.ts +0 -4
  90. package/dist/types/assistants/assistant-store.d.ts +0 -23
  91. package/dist/types/assistants/assistant-turn-context.d.ts +0 -20
  92. package/dist/types/assistants/assistant-types.d.ts +0 -38
  93. package/dist/types/assistants/plugin-assistant-registry.d.ts +0 -16
  94. package/dist/types/cli/core-tools/utility-tool-bootstrap.d.ts +0 -12
  95. package/dist/types/cli/dev-tools/repl-tool-service.d.ts +0 -5
  96. package/dist/types/cli/handlers/assistants-handler.d.ts +0 -13
  97. package/dist/types/skills/mcp/mcp-http-client.d.ts +0 -68
  98. package/dist/types/skills/mcp/mcp-stdio-client.d.ts +0 -86
  99. package/dist/types/skills/think-tool.d.ts +0 -16
  100. package/dist/types/skills/tools/apply-patch-tool.d.ts +0 -29
  101. package/dist/types/skills/tools/mcp-client-types.d.ts +0 -269
  102. package/dist/types/skills/tools/mcp-resource-tools.d.ts +0 -14
  103. package/dist/types/skills/tools/mcp-tool.d.ts +0 -249
  104. package/dist/types/skills/tools/project-switch-tool.d.ts +0 -24
  105. package/dist/types/skills/tools/repl-tool.d.ts +0 -70
  106. package/dist/types/skills/tools/send-message-tool.d.ts +0 -57
@@ -1,4 +1,4 @@
1
- function Ae(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Me(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var Ee=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,y={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]},Ie=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,ve=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Le=512,we=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Oe=new Set([500,502,503,504,521,522,523,524,529]),Pe=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ne=["upgrade your plan","upgrade plan","current plan","subscription"],De=["daily","weekly","monthly"],Fe=["try again","retry","temporary","cooldown"],Be=["usage limit","rate limit","organization usage"],Ue=["organization","workspace"],je=["billing period","exceeded","reached","exhausted"],Ge=/["']?(?: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,He=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function h(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function $e(e){return h(e,y.format)}function W(e){return h(e,y.rateLimit)}function ze(e){return h(e,y.timeout)}function qe(e){return Ee.test(e)}function E(e){let t=e.toLowerCase();return t?e.length>Le?ve.test(t):h(t,y.billing)?!0:Ie.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function V(e){return h(e,y.authPermanent)}function Xe(e){return h(e,y.auth)}function J(e){return h(e,y.overloaded)}function T(e,t){return t.some(n=>e.includes(n))}function Ke(e){return T(e,Pe)||T(e,Ne)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ye(e){let t=T(e,De),n=e.includes("spend limit")||e.includes("spending limit"),o=T(e,Ue);return T(e,Fe)&&T(e,Be)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||T(e,je))}function We(e){return e.trim().toLowerCase().replace(He,"").trim()}function Z(e){let t=We(e);return!t||Ke(t)?"billing":W(t)||Ye(t)?"rate_limit":"billing"}function Ve(e){return Ge.test(e)?Z(e):null}function Q(e){let t=e.match(we);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Je(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Ze(e){let t=e.trim();if(!t)return!1;let n=Q(t);return n?Oe.has(n.code):!1}function ee(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?Z(t):"billing":e===429?"rate_limit":e===401||e===403?t&&V(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&J(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&E(t)?"billing":"format":null}function Qe(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 et(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 te(e){if(et(e))return"session_expired";if(Qe(e))return"model_not_found";let t=Ve(e);return t||(qe(e)?E(e)?"billing":"rate_limit":W(e)?"rate_limit":J(e)?"overloaded":Ze(e)?Q(e.trim())?.code===529?"overloaded":"timeout":Je(e)?"timeout":$e(e)?"format":E(e)?"billing":ze(e)?"timeout":V(e)?"auth_permanent":Xe(e)?"auth":null)}var tt={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"},nt=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ot(e,t){let n=ee(e,t)??(t?te(t):null);return n?tt[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function rt(e){return nt.has(e)}function B(e){return typeof e.compressAsync=="function"}var ne=4,I=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 i=n;for(let c of o)i-=this.estimateTokens(c);let a;for(let c of r)if(c.role==="user"){a=c;break}if(a&&(i-=this.estimateTokens(a)),i<=0)return{messages:a?[...o,a]:o,droppedCount:r.length-(a?1:0),strategy:"sliding-window"};let s=[],l=0;for(let c=r.length-1;c>=0;c--){let d=r[c];if(d===a)continue;let p=this.estimateTokens(d);if(i-p<0&&l>=ne)break;if(i-p<0&&l<ne){s.unshift(d),l++;continue}i-=p,s.unshift(d),l++}let u=[...o];return a&&!s.includes(a)&&u.push(a),u.push(...s),{messages:u,droppedCount:r.length-(s.length+(a&&!s.includes(a)?1:0)),strategy:"sliding-window"}}},v=class{constructor(t,n){this.recentCount=t;this.summarize=n}recentCount;summarize;compress(t,n){let o=t.filter(l=>l.role==="system"),r=t.filter(l=>l.role!=="system");if(r.length<=this.recentCount)return{messages:t,droppedCount:0,strategy:"summarize-old"};let i=r.slice(0,r.length-this.recentCount),a=r.slice(r.length-this.recentCount),s=this.summarize(i);return{messages:[...o,{role:"system",content:`[Conversation summary]
1
+ function Ae(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Me(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var Ee=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,T={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Ie=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,ve=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Le=512,we=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Oe=new Set([500,502,503,504,521,522,523,524,529]),Pe=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ne=["upgrade your plan","upgrade plan","current plan","subscription"],De=["daily","weekly","monthly"],Fe=["try again","retry","temporary","cooldown"],Be=["usage limit","rate limit","organization usage"],Ue=["organization","workspace"],je=["billing period","exceeded","reached","exhausted"],Ge=/["']?(?: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,He=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function h(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function $e(e){return h(e,T.format)}function W(e){return h(e,T.rateLimit)}function ze(e){return h(e,T.timeout)}function qe(e){return Ee.test(e)}function E(e){let t=e.toLowerCase();return t?e.length>Le?ve.test(t):h(t,T.billing)?!0:Ie.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function V(e){return h(e,T.authPermanent)}function Ke(e){return h(e,T.auth)}function J(e){return h(e,T.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function Xe(e){return y(e,Pe)||y(e,Ne)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ye(e){let t=y(e,De),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,Ue);return y(e,Fe)&&y(e,Be)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,je))}function We(e){return e.trim().toLowerCase().replace(He,"").trim()}function Z(e){let t=We(e);return!t||Xe(t)?"billing":W(t)||Ye(t)?"rate_limit":"billing"}function Ve(e){return Ge.test(e)?Z(e):null}function Q(e){let t=e.match(we);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Je(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Ze(e){let t=e.trim();if(!t)return!1;let n=Q(t);return n?Oe.has(n.code):!1}function ee(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?Z(t):"billing":e===429?"rate_limit":e===401||e===403?t&&V(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&J(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&E(t)?"billing":"format":null}function Qe(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 et(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 te(e){if(et(e))return"session_expired";if(Qe(e))return"model_not_found";let t=Ve(e);return t||(qe(e)?E(e)?"billing":"rate_limit":W(e)?"rate_limit":J(e)?"overloaded":Ze(e)?Q(e.trim())?.code===529?"overloaded":"timeout":Je(e)?"timeout":$e(e)?"format":E(e)?"billing":ze(e)?"timeout":V(e)?"auth_permanent":Ke(e)?"auth":null)}var tt={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"},nt=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ot(e,t){let n=ee(e,t)??(t?te(t):null);return n?tt[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function rt(e){return nt.has(e)}function B(e){return typeof e.compressAsync=="function"}var ne=4,I=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 i=n;for(let c of o)i-=this.estimateTokens(c);let a;for(let c of r)if(c.role==="user"){a=c;break}if(a&&(i-=this.estimateTokens(a)),i<=0)return{messages:a?[...o,a]:o,droppedCount:r.length-(a?1:0),strategy:"sliding-window"};let s=[],l=0;for(let c=r.length-1;c>=0;c--){let d=r[c];if(d===a)continue;let p=this.estimateTokens(d);if(i-p<0&&l>=ne)break;if(i-p<0&&l<ne){s.unshift(d),l++;continue}i-=p,s.unshift(d),l++}let u=[...o];return a&&!s.includes(a)&&u.push(a),u.push(...s),{messages:u,droppedCount:r.length-(s.length+(a&&!s.includes(a)?1:0)),strategy:"sliding-window"}}},v=class{constructor(t,n){this.recentCount=t;this.summarize=n}recentCount;summarize;compress(t,n){let o=t.filter(l=>l.role==="system"),r=t.filter(l=>l.role!=="system");if(r.length<=this.recentCount)return{messages:t,droppedCount:0,strategy:"summarize-old"};let i=r.slice(0,r.length-this.recentCount),a=r.slice(r.length-this.recentCount),s=this.summarize(i);return{messages:[...o,{role:"system",content:`[Conversation summary]
2
2
  ${s}`},...a],droppedCount:i.length,strategy:"summarize-old"}}},L=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(i=>i.role!=="tool"||typeof i.content!="string"||i.content.length<=this.maxToolResultChars?i:(o++,{...i,content:st(i.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function st(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let i=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
3
3
  `),n.lastIndexOf(`]
4
4
  `));if(i>t*.5)return n.slice(0,i+1)+`
@@ -16,15 +16,15 @@ New messages to integrate:`:void 0,C=U(d,{taskContext:f}),k=await this.config.su
16
16
  ${k}`},_=[...l,A,...p],M=Date.now()-o,b=_.reduce((m,g)=>m+this.config.estimateTokens(g),0);return{messages:_,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:c,tokensAfter:b,compressionRatio:c>0?b/c:1,latencyMs:M,usedLlm:!0,cacheInvalidated:!0}}}},P=class{config;constructor(t){this.config=t}compress(t,n){let o=R(t),r=this.config.inner.compress(t,n),i=R(r.messages),a=o!==i&&r.droppedCount>0;return a&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:a}}}async compressAsync(t,n){let o=R(t),r=B(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),i=R(r.messages),a=o!==i&&r.droppedCount>0;return a&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:a}}}},oe={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function lt(e={}){let t={...oe,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function ct(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var N=class{events=[];maxEvents;constructor(t=100){this.maxEvents=t}record(t){this.events.push(t),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let t=this.events.length;if(t===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let n=0,o=0,r=0,i=0,a=0;for(let s of this.events)n+=s.tokensBefore>0?s.tokensAfter/s.tokensBefore:1,o+=s.latencyMs,r+=Math.max(0,s.tokensBefore-s.tokensAfter),s.usedLlm&&i++,s.cacheInvalidated&&a++;return{totalCompressions:t,totalLlmCalls:i,totalCacheInvalidations:a,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},D=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 re(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function S(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],i=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${i}`)}return n.join("|")}var ut=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"]),F=class{constructor(t=20,n=S){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=t.length-this.preserveRecentCount,r=0,i=0;return{messages:t.map((s,l)=>{if(l>=o||s.role!=="tool"||typeof s.content!="string"||!s.name||!ut.has(s.name)||s.content.length<=200)return s;let u=this.estimateTokens(s);return i+=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 pt(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let i=r.function?.name??"";if(/read|edit|write|file/i.test(i)&&r.function?.arguments)try{let a=JSON.parse(r.function.arguments),s=a.path??a.filePath??a.file_path??a.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 dt(e,t,n){let o=n.estimateTokens??(p=>Math.ceil(p.length/4)),r=pt(t);if(r.length===0)return e;let i=e.map(p=>typeof p.content=="string"?p.content:"").join(`
17
17
  `),a=r.filter(p=>!i.includes(p));if(a.length===0)return e;let s=n.maxTokenBudget,l=[],u=0;for(let p of a){if(u>=n.maxFiles||s<=0)break;let f=await n.readFile(p);if(!f)continue;let C=o(f);C>s||(s-=C,u++,l.push({role:"system",content:`[Post-compact file recovery: ${p}]
18
18
 
19
- ${f}`}))}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 mt(e,t,n=S){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let s of e){let l=s.tool_call_id??"";if(l&&t.has(l)){o+=n(s),r++,t.delete(l);continue}i.push(s)}let a=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:a}}function ft(){return{stages:[]}}function gt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=se(e,t),a=yt(i,t,o);if(a.length===0)return{messages:i,stagedCount:0};for(let s of a)t.stages.push(s);return i=se(e,t),{messages:i,stagedCount:a.length}}function Tt(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:ie(e,t),committed:n}}function se(e,t){return t.stages.filter(o=>o.committed).length===0?e:ie(e,t)}function ie(e,t){let n=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),o=[...e];for(let r of n){let[i,a]=r.range;if(i>=o.length)continue;let s=Math.min(a,o.length),l={role:"system",content:r.summary};o.splice(i,s-i,l)}return o}function yt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),a=-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==="")a<0&&(a=l),s++;else{if(s>=3){let d=`${a}-${a+s}`;i.has(d)||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 l=`${a}-${a+s}`;i.has(l)||r.push({id:`collapse_${a}_${a+s}`,range:[a,a+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}import{existsSync as G,readFileSync as fe,writeFileSync as ht,readdirSync as ge,mkdirSync as Ct}from"node:fs";import{join as H,dirname as _t}from"node:path";var Nn=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100);var ae=20;var le=3,ce=2,ue=300*1e3,pe=3,de=720*60*60*1e3;var Dn=300*1e3,j=4;var Fn=3600*1e3;var Bn=50*1024,Un=500*1024,jn=500*1024*1024,Gn=50*1024*1024;var Hn=60*1024;var Te=0;var bt="skill-patterns.json";function ye(e){return H(e,".qlogicagent",bt)}function he(e){let t=ye(e);try{return JSON.parse(fe(t,"utf8"))}catch{return{version:1,patterns:{}}}}function me(e,t){let n=ye(e);Ct(_t(n),{recursive:!0}),ht(n,JSON.stringify(t,null,2),"utf8")}function Rt(e){let t=Date.now()-de;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function Ce(e,t){if(t.length===0)return!1;let n=x(t),o=he(e);Rt(o);let r=new Date().toISOString(),i=o.patterns[n];if(i||(i={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=i),i.promoted)return me(e,o),!1;i.count++,i.lastSeen=r;let a=i.count>=pe;return a&&(i.promoted=!0),me(e,o),a}function St(e){let t=he(e);return Object.values(t.patterns)}function x(e){return[...e].sort().join("+")}function xt(e,t){if(!G(t))return null;let n=x(e);try{let o=ge(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let i=H(t,r.name,"SKILL.md");try{let s=fe(i,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(s){let l=s[1].split(`
20
- `).map(u=>u.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(x(l)===n)return r.name}}catch{}}}catch{}return null}function kt(e){if(!G(e))return 0;try{return ge(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&G(H(e,t.name,"SKILL.md"))).length}catch{return 0}}function At(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<le||e.distinctToolCount<ce||Date.now()-Te<ue||t?.projectSkillsDir&&(kt(t.projectSkillsDir)>=ae||t.tools.length>0&&xt(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Ce(t.projectRoot,t.tools))}function Mt(e){return e.existingSkillName?e.feedback==="negative":!1}function Et(e,t){return Mt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:At(e,t)?(Te=Date.now(),{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 _e(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 It(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function vt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Lt(e){if(!e.eligibility?.length)return[...e.tools];let t=vt(e.eligibility);return e.tools.filter(n=>{let o=_e(n);if(!o)return!1;let r=t.get(o);return!r||It(r.status)})}function wt(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 Ot(e){let t=wt({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Lt({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,a=typeof i?.name=="string"?i.name.trim():"";if(!a)throw new Error("tool_choice.function.name is required");let s=r.filter(l=>_e(l)===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:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Pt=["stop","aborted","timeout","cancelled","interrupted","error"],Nt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function be(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Dt(e,t){return{...e,content:[...be(e.content),...be(t.content)]}}function Ft(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 Bt(e){return new Set((e??Pt).map(t=>t.trim().toLowerCase()))}function Re(e,t){return e?Bt(t).has(e.trim().toLowerCase()):!1}function Ut(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 $(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=>Ft(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 i=[];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!==""&&i.push(c);continue}if(l.length<s.tool_calls.length){i.push({...s,tool_calls:l});continue}}i.push(s)}let a=[];for(let s of i){let l=a.length>0?a[a.length-1]:void 0;if(s.role==="user"&&l?.role==="user"){a[a.length-1]=Dt(l,s);continue}a.push(s)}return a}function z(e,t){return Re(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Nt)delete o[r];return o}):[...e]}function q(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&o.add(i.tool_call_id);let r=[];for(let i of e)if(r.push({...i}),!(i.role!=="assistant"||!Array.isArray(i.tool_calls)||i.tool_calls.length===0))for(let a of i.tool_calls)typeof a.id!="string"||!a.id||o.has(a.id)||(o.add(a.id),r.push({role:"tool",tool_call_id:a.id,content:n}));return r}function jt(e,t){let n=$(e),o=z(n,t);return q(o,t)}function Se(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=Re(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(f=>f&&typeof f=="object"&&f.type!=="reasoning"))continue;if(c.type!=="function_call"){r.push({...c});continue}let d={...c};if(typeof d.id=="string"){let p=Ut(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let i=new Set,a=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&&(i.add(c),a.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||!i.has(c))continue;s.add(c)}l.push(u)}for(let[u]of a)s.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function Gt(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 $t(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 zt(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 xe(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function qt(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 Xt(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 Kt(e){let t=[],n=$(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=z(n,e.options);o.some((i,a)=>i!==n[a])&&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:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Gt(r),completedToolCallIds:Ht(r)}),recoveryActions:t}}function Yt(e){let t=Se(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:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:$t(t),completedToolCallIds:zt(t)}),recoveryActions:n}}var Wt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Vt(e){return e?Wt.has(e):!0}function Jt(e){return e===429||e===529}function Zt(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 Qn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Qt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var X=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var K="<fork-child-context>",ke="Fork started \u2014 processing in background";function en(e){return JSON.stringify(e).includes(K)}function tn(e){return e<j}function nn(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
19
+ ${f}`}))}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 mt(e,t,n=S){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let s of e){let l=s.tool_call_id??"";if(l&&t.has(l)){o+=n(s),r++,t.delete(l);continue}i.push(s)}let a=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:a}}function ft(){return{stages:[]}}function gt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=se(e,t),a=Tt(i,t,o);if(a.length===0)return{messages:i,stagedCount:0};for(let s of a)t.stages.push(s);return i=se(e,t),{messages:i,stagedCount:a.length}}function yt(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:ie(e,t),committed:n}}function se(e,t){return t.stages.filter(o=>o.committed).length===0?e:ie(e,t)}function ie(e,t){let n=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),o=[...e];for(let r of n){let[i,a]=r.range;if(i>=o.length)continue;let s=Math.min(a,o.length),l={role:"system",content:r.summary};o.splice(i,s-i,l)}return o}function Tt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),a=-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==="")a<0&&(a=l),s++;else{if(s>=3){let d=`${a}-${a+s}`;i.has(d)||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 l=`${a}-${a+s}`;i.has(l)||r.push({id:`collapse_${a}_${a+s}`,range:[a,a+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}import{existsSync as G,readFileSync as fe,writeFileSync as ht,readdirSync as ge,mkdirSync as Ct}from"node:fs";import{join as H,dirname as _t}from"node:path";var Nn=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100);var ae=20;var le=3,ce=2,ue=300*1e3,pe=3,de=720*60*60*1e3;var Dn=300*1e3,j=4;var Fn=3600*1e3;var Bn=50*1024,Un=500*1024,jn=500*1024*1024,Gn=50*1024*1024;var Hn=60*1024;var ye=0;var bt="skill-patterns.json";function Te(e){return H(e,".qlogicagent",bt)}function he(e){let t=Te(e);try{return JSON.parse(fe(t,"utf8"))}catch{return{version:1,patterns:{}}}}function me(e,t){let n=Te(e);Ct(_t(n),{recursive:!0}),ht(n,JSON.stringify(t,null,2),"utf8")}function Rt(e){let t=Date.now()-de;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function Ce(e,t){if(t.length===0)return!1;let n=x(t),o=he(e);Rt(o);let r=new Date().toISOString(),i=o.patterns[n];if(i||(i={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=i),i.promoted)return me(e,o),!1;i.count++,i.lastSeen=r;let a=i.count>=pe;return a&&(i.promoted=!0),me(e,o),a}function St(e){let t=he(e);return Object.values(t.patterns)}function x(e){return[...e].sort().join("+")}function xt(e,t){if(!G(t))return null;let n=x(e);try{let o=ge(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let i=H(t,r.name,"SKILL.md");try{let s=fe(i,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(s){let l=s[1].split(`
20
+ `).map(u=>u.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(x(l)===n)return r.name}}catch{}}}catch{}return null}function kt(e){if(!G(e))return 0;try{return ge(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&G(H(e,t.name,"SKILL.md"))).length}catch{return 0}}function At(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<le||e.distinctToolCount<ce||Date.now()-ye<ue||t?.projectSkillsDir&&(kt(t.projectSkillsDir)>=ae||t.tools.length>0&&xt(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Ce(t.projectRoot,t.tools))}function Mt(e){return e.existingSkillName?e.feedback==="negative":!1}function Et(e,t){return Mt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:At(e,t)?(ye=Date.now(),{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 _e(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 It(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function vt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Lt(e){if(!e.eligibility?.length)return[...e.tools];let t=vt(e.eligibility);return e.tools.filter(n=>{let o=_e(n);if(!o)return!1;let r=t.get(o);return!r||It(r.status)})}function wt(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 Ot(e){let t=wt({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Lt({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,a=typeof i?.name=="string"?i.name.trim():"";if(!a)throw new Error("tool_choice.function.name is required");let s=r.filter(l=>_e(l)===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:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Pt=["stop","aborted","timeout","cancelled","interrupted","error"],Nt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function be(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Dt(e,t){return{...e,content:[...be(e.content),...be(t.content)]}}function Ft(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 Bt(e){return new Set((e??Pt).map(t=>t.trim().toLowerCase()))}function Re(e,t){return e?Bt(t).has(e.trim().toLowerCase()):!1}function Ut(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 $(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=>Ft(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 i=[];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!==""&&i.push(c);continue}if(l.length<s.tool_calls.length){i.push({...s,tool_calls:l});continue}}i.push(s)}let a=[];for(let s of i){let l=a.length>0?a[a.length-1]:void 0;if(s.role==="user"&&l?.role==="user"){a[a.length-1]=Dt(l,s);continue}a.push(s)}return a}function z(e,t){return Re(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Nt)delete o[r];return o}):[...e]}function q(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&o.add(i.tool_call_id);let r=[];for(let i of e)if(r.push({...i}),!(i.role!=="assistant"||!Array.isArray(i.tool_calls)||i.tool_calls.length===0))for(let a of i.tool_calls)typeof a.id!="string"||!a.id||o.has(a.id)||(o.add(a.id),r.push({role:"tool",tool_call_id:a.id,content:n}));return r}function jt(e,t){let n=$(e),o=z(n,t);return q(o,t)}function Se(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=Re(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(f=>f&&typeof f=="object"&&f.type!=="reasoning"))continue;if(c.type!=="function_call"){r.push({...c});continue}let d={...c};if(typeof d.id=="string"){let p=Ut(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let i=new Set,a=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&&(i.add(c),a.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||!i.has(c))continue;s.add(c)}l.push(u)}for(let[u]of a)s.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function Gt(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 $t(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 zt(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 xe(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function qt(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 Xt(e){let t=[],n=$(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=z(n,e.options);o.some((i,a)=>i!==n[a])&&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:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Gt(r),completedToolCallIds:Ht(r)}),recoveryActions:t}}function Yt(e){let t=Se(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:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:$t(t),completedToolCallIds:zt(t)}),recoveryActions:n}}var Wt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Vt(e){return e?Wt.has(e):!0}function Jt(e){return e===429||e===529}function Zt(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 Qn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Qt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var K=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var X="<fork-child-context>",ke="Fork started \u2014 processing in background";function en(e){return JSON.stringify(e).includes(X)}function tn(e){return e<j}function nn(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
21
21
 
22
22
  Your working directory is: ${e.worktreePath}
23
- All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${K}
23
+ All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${X}
24
24
 
25
25
  You are the "${t.agent.name}" agent.${o}
26
26
 
27
- ${t.taskPrompt}`}]};return n.push(r),n}function on(e){return e.map(t=>({role:"tool",tool_call_id:t,content:ke}))}function rn(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolCapabilityProfile==="no_tools")return[];if(t.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent"&&n!=="team")}function sn(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var an={name:"general",label:"General Purpose",description:"A general-purpose sub-agent that can perform any task with full tool access.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!1},ln={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolCapabilityProfile:"read_tools",allowedTools:["read_file","search","web_search","web_fetch","think","memory","tool_search"],canFork:!1,systemPromptSuffix:"You are READ-ONLY: never attempt to modify files or run mutating commands. Locate and understand code, then report concrete findings with file:line references. Read excerpts rather than whole files; surface conclusions, not raw dumps."},cn={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolCapabilityProfile:"read_tools",allowedTools:["read_file","search","web_search","web_fetch","think","memory","task","tool_search"],canFork:!1,systemPromptSuffix:"You PLAN but do not execute: never write files or run commands. Investigate enough to ground the plan in the real code, then return a concrete, step-by-step implementation plan naming the specific files and changes involved."},un={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!0,systemPromptSuffix:"Implement the task directly by editing files. Read existing code before changing it, match the surrounding conventions, and verify your change compiles/passes where possible."},pn={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolCapabilityProfile:"read_tools",allowedTools:["web_search","web_fetch","read_file","search","think","memory"],canFork:!1,systemPromptSuffix:"Gather information from multiple sources before concluding. Distinguish facts from inferences, cite where each claim comes from, and synthesize \u2014 do not just dump search results."},dn={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolCapabilityProfile:"all_tools",allowedTools:["exec","read_file","search","think"],canFork:!1,systemPromptSuffix:"Verify by RUNNING things (tests, builds, type-checks) and reading the actual output \u2014 do not assume. Report a clear verdict (pass/fail) with the evidence that supports it."},Y=[an,ln,cn,un,pn,dn];function mn(){return[...Y]}function fn(e){return Y.find(t=>t.name===e)}function gn(e){return Y.some(t=>t.name===e)}function Tn(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolCapabilityProfile==="no_tools")return[];if(e.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(o=>!n.has(o))}return e.canFork?[...t]:t.filter(n=>n!=="agent"&&n!=="team")}var yn=new Set(["agent_tool","team_create","fork_agent","send_message"]);function hn(e,t){switch(e){case"worker":return t.filter(n=>!yn.has(n));case"coordinator":return[...t];default:return[...t]}}function Cn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function _n(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function bn(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 Rn(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function Sn(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 xn(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var kn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function An(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
27
+ ${t.taskPrompt}`}]};return n.push(r),n}function on(e){return e.map(t=>({role:"tool",tool_call_id:t,content:ke}))}function rn(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolCapabilityProfile==="no_tools")return[];if(t.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent"&&n!=="team")}function sn(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var an={name:"general",label:"General Purpose",description:"A general-purpose sub-agent that can perform any task with full tool access.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!1},ln={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolCapabilityProfile:"read_tools",allowedTools:["read_file","search","web_search","web_fetch","memory","tool_search"],canFork:!1,systemPromptSuffix:"You are READ-ONLY: never attempt to modify files or run mutating commands. Locate and understand code, then report concrete findings with file:line references. Read excerpts rather than whole files; surface conclusions, not raw dumps."},cn={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolCapabilityProfile:"read_tools",allowedTools:["read_file","search","web_search","web_fetch","memory","task","tool_search"],canFork:!1,systemPromptSuffix:"You PLAN but do not execute: never write files or run commands. Investigate enough to ground the plan in the real code, then return a concrete, step-by-step implementation plan naming the specific files and changes involved."},un={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!0,systemPromptSuffix:"Implement the task directly by editing files. Read existing code before changing it, match the surrounding conventions, and verify your change compiles/passes where possible."},pn={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolCapabilityProfile:"read_tools",allowedTools:["web_search","web_fetch","read_file","search","memory"],canFork:!1,systemPromptSuffix:"Gather information from multiple sources before concluding. Distinguish facts from inferences, cite where each claim comes from, and synthesize \u2014 do not just dump search results."},dn={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolCapabilityProfile:"all_tools",allowedTools:["exec","read_file","search"],canFork:!1,systemPromptSuffix:"Verify by RUNNING things (tests, builds, type-checks) and reading the actual output \u2014 do not assume. Report a clear verdict (pass/fail) with the evidence that supports it."},Y=[an,ln,cn,un,pn,dn];function mn(){return[...Y]}function fn(e){return Y.find(t=>t.name===e)}function gn(e){return Y.some(t=>t.name===e)}function yn(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolCapabilityProfile==="no_tools")return[];if(e.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(o=>!n.has(o))}return e.canFork?[...t]:t.filter(n=>n!=="agent"&&n!=="team")}var Tn=new Set(["agent_tool","team","fork_agent"]);function hn(e,t){switch(e){case"worker":return t.filter(n=>!Tn.has(n));case"coordinator":return[...t];default:return[...t]}}function Cn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function _n(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function bn(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 Rn(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function Sn(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 xn(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var kn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function An(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
28
28
  ${n.join(`
29
29
  `)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
30
30
  Step ${e.activeSkillContext.step}:
@@ -35,4 +35,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
35
35
 
36
36
  ${t.join(`
37
37
 
38
- `)}`}function Mn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function En(e,t=kn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{P as CacheAwareCompressionStrategy,N as CompressionMetricsCollector,D as ContextEngineRegistry,oe as DEFAULT_ADAPTIVE_BUDGET_CONFIG,ke as FORK_PLACEHOLDER_RESULT,K as FORK_SENTINEL_TAG,X as FallbackTriggeredError,w as HeadTailProtectedStrategy,O as IncrementalCompactStrategy,j as MAX_FORK_DEPTH,F as MicroCompactStrategy,I as SlidingWindowStrategy,v as SummarizeOldStrategy,L as ToolResultTrimStrategy,qt as advanceToolLoopState,gt as applyContextCollapsesIfNeeded,Ot as applyToolChoicePolicy,Ae as buildAssistantToolCallMessage,on as buildForkPlaceholderResults,nn as buildForkedMessages,An as buildPostCompactRestorationMessage,Et as buildSkillInstruction,U as buildStructuredSummaryPrompt,Me as buildToolResultMessage,x as buildToolSignature,bn as calculateTokenWarningState,tn as canForkAtDepth,ot as classifyError,at as composeAsyncStrategies,it as composeStrategies,lt as computeAdaptiveBudget,Zt as computeRetryBackoff,ft as createCollapseStore,Mn as createReactiveCompactState,Cn as createTaskState,_n as createTurnLoopGuardState,hn as filterToolsByRole,sn as generateForkChildAgentId,fn as getBuiltInAgent,mn as getBuiltInAgents,St as getPatternStats,B as isAsyncCompressionStrategy,gn as isBuiltInAgent,Vt as isForegroundSource,en as isInForkChild,Qt as isPersistentRetryEnabled,rt as isRetryableCategory,Jt as isTransientCapacityError,dt as postCompactFileRecovery,Ce as recordPatternAndCheckThreshold,Tt as recoverContextCollapseFromOverflow,Kt as recoverToolLoopStateFromChatConversation,Yt as recoverToolLoopStateFromResponsesItems,jt as repairOpenAiChatConversation,Tn as resolveAgentToolSet,Rn as resolveApiErrorRecovery,rn as resolveForkChildTools,Sn as resolveOutputTokenEscalation,ct as selectCompressionTier,Xt as settleToolLoopState,xn as shouldAbortTurn,En as shouldAttemptReactiveCompact,mt as snipCompactIfNeeded};
38
+ `)}`}function Mn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function En(e,t=kn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{P as CacheAwareCompressionStrategy,N as CompressionMetricsCollector,D as ContextEngineRegistry,oe as DEFAULT_ADAPTIVE_BUDGET_CONFIG,ke as FORK_PLACEHOLDER_RESULT,X as FORK_SENTINEL_TAG,K as FallbackTriggeredError,w as HeadTailProtectedStrategy,O as IncrementalCompactStrategy,j as MAX_FORK_DEPTH,F as MicroCompactStrategy,I as SlidingWindowStrategy,v as SummarizeOldStrategy,L as ToolResultTrimStrategy,qt as advanceToolLoopState,gt as applyContextCollapsesIfNeeded,Ot as applyToolChoicePolicy,Ae as buildAssistantToolCallMessage,on as buildForkPlaceholderResults,nn as buildForkedMessages,An as buildPostCompactRestorationMessage,Et as buildSkillInstruction,U as buildStructuredSummaryPrompt,Me as buildToolResultMessage,x as buildToolSignature,bn as calculateTokenWarningState,tn as canForkAtDepth,ot as classifyError,at as composeAsyncStrategies,it as composeStrategies,lt as computeAdaptiveBudget,Zt as computeRetryBackoff,ft as createCollapseStore,Mn as createReactiveCompactState,Cn as createTaskState,_n as createTurnLoopGuardState,hn as filterToolsByRole,sn as generateForkChildAgentId,fn as getBuiltInAgent,mn as getBuiltInAgents,St as getPatternStats,B as isAsyncCompressionStrategy,gn as isBuiltInAgent,Vt as isForegroundSource,en as isInForkChild,Qt as isPersistentRetryEnabled,rt as isRetryableCategory,Jt as isTransientCapacityError,dt as postCompactFileRecovery,Ce as recordPatternAndCheckThreshold,yt as recoverContextCollapseFromOverflow,Xt as recoverToolLoopStateFromChatConversation,Yt as recoverToolLoopStateFromResponsesItems,jt as repairOpenAiChatConversation,yn as resolveAgentToolSet,Rn as resolveApiErrorRecovery,rn as resolveForkChildTools,Sn as resolveOutputTokenEscalation,ct as selectCompressionTier,Kt as settleToolLoopState,xn as shouldAbortTurn,En as shouldAttemptReactiveCompact,mt as snipCompactIfNeeded};
package/dist/protocol.js CHANGED
@@ -1 +1 @@
1
- var q=["idle","running-right","running-left","waving","jumping","failed","waiting","running","review"];var Y="1.0.0",d={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TURN_ABORTED:-32e3,TURN_TIMEOUT:-32001,LLM_ERROR:-32010,LLM_AUTH_ERROR:-32011,LLM_RATE_LIMIT:-32012,LLM_QUOTA_EXHAUSTED:-32013,LLM_MODEL_NOT_FOUND:-32014,TOOL_INVOKE_FAILED:-32020,TOOL_TIMEOUT:-32021,PROTOCOL_MISMATCH:-32030,REQUEST_DEADLINE_EXCEEDED:-32040,REQUEST_CANCELLED:-32041,REQUEST_DEDUPED:-32042,REQUEST_IDEMPOTENCY_REQUIRED:-32043},H={REQUEST:"tool.approval.request"};function P(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&t.method.length>0}function C(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&(typeof t.id=="string"||typeof t.id=="number")&&!("method"in t)}function I(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function G(e){let t;try{t=JSON.parse(e)}catch{return null}return C(t)||P(t)||I(t)?t:null}import{randomUUID as z}from"node:crypto";var X=["settings.list","settings.get","settings.validate","provider.list","config.get","config.tunables","tools.list","todos.list","tasks.list","agents.list","agents.get","agents.processes","agents.scan","assistants.list","assistants.resolve","session.list","session.get","session.resolve","thread.list","project.list","files.list","files.gitStatus","instructions.list","instructions.read","skills.list","skills.stats","memory.atlas","memory.activity","memory.list","memory.read","memory.search","media.listModels","media.status","pet.status","agent.health","agent.metrics"],J=new Set(["memory.dream","memory.propose","memory.consolidate","media.stt","pet.forge","pet.asset.import","solo.start","solo.evaluate","product.plan","product.create","product.message"]),Q=["memory.","pet.","usage."],$=new Set(["memory.atlas","memory.activity","memory.list","memory.read","memory.search","memory.attachment.locate","memory.attachment.adopt","pet.status"]);function f(e){return J.has(e)?{channel:"task",mutability:"write",defaultTimeoutMs:12e4}:X.some(t=>e===t||e.startsWith(`${t}.`)||e.startsWith(t))?{channel:"query",mutability:"read",defaultTimeoutMs:1e4}:{channel:"task",mutability:"write",defaultTimeoutMs:3e4}}function h(e){return $.has(e)||f(e).mutability==="read"?!1:Q.some(t=>e.startsWith(t))}function Z(e,t={}){let r=t.now??Date.now(),n=f(e),o=t.timeoutMs??n.defaultTimeoutMs;return{requestId:t.requestId??z(),createdAt:r,deadlineAt:r+o,channel:t.channel??n.channel,idempotencyKey:t.idempotencyKey,traceId:t.traceId}}function v(e,t=Date.now()){let r=e.meta;if(!r||typeof r!="object")return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta is required."}};if(typeof r.requestId!="string"||r.requestId.length===0)return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.requestId is required."}};if(r.channel!=="query"&&r.channel!=="task")return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.channel must be query or task."}};if(typeof r.createdAt!="number"||!Number.isFinite(r.createdAt))return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.createdAt is required."}};if(typeof r.deadlineAt!="number"||!Number.isFinite(r.deadlineAt))return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.deadlineAt is required."}};if(r.deadlineAt<=t)return{ok:!1,error:{code:d.REQUEST_DEADLINE_EXCEEDED,message:"RPC request deadline has already expired."}};let n=f(e.method).channel;return r.channel!==n?{ok:!1,error:{code:d.INVALID_REQUEST,message:`RPC request channel mismatch: expected ${n}, got ${r.channel}.`}}:h(e.method)&&(typeof r.idempotencyKey!="string"||r.idempotencyKey.length===0)?{ok:!1,error:{code:d.REQUEST_IDEMPOTENCY_REQUIRED,message:`RPC method ${e.method} requires meta.idempotencyKey.`}}:{ok:!0,meta:r}}var R=class{now;active=new Map;idempotency=new Map;counters={completedRequests:0,cancelledRequests:0,deadlineExceededRequests:0,dedupedRequests:0,lateResponsesDropped:0,invalidRequests:0};constructor(t={}){this.now=t.now??(()=>Date.now())}begin(t,r){let n=v({method:t,meta:r},this.now());if(!n.ok)return this.counters.invalidRequests+=1,{status:"rejected",error:n.error};if(r.idempotencyKey){let o=this.idempotency.get(r.idempotencyKey);if(o)return this.counters.dedupedRequests+=1,o.error?{status:"deduped",error:o.error}:{status:"deduped",result:o.result}}return this.active.set(r.requestId,{method:t,meta:r,cancelled:!1,startedAt:this.now()}),{status:"started"}}cancel(t,r="cancelled"){let n=this.active.get(t);return!n||n.cancelled?!1:(n.cancelled=!0,n.cancelReason=r,this.counters.cancelledRequests+=1,!0)}expire(t){return this.active.get(t)?(this.active.delete(t),this.counters.deadlineExceededRequests+=1,!0):!1}settle(t,r,n){let o=this.active.get(t);return o?(this.active.delete(t),o.cancelled?(this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"cancelled"}):o.meta.deadlineAt<=this.now()?(this.counters.deadlineExceededRequests+=1,this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"deadline_exceeded"}):(this.counters.completedRequests+=1,o.meta.idempotencyKey&&this.idempotency.set(o.meta.idempotencyKey,{result:r,error:n,settledAt:this.now()}),{accepted:!0})):{accepted:!1,reason:"unknown"}}metrics(){return{activeRequests:this.active.size,...this.counters}}};var ee=["agent.health","agent.metrics","agent.cancel","session.list","session.get","session.create","session.update","session.delete","session.deleteAll","session.archive","session.moveToProject","session.getState","session.switchProject","session.getMessages","project.list","project.create","project.delete","project.rename","project.archive","project.unarchive","project.update","project.archiveByGroup","project.purgeAll","instructions.list","instructions.read","instructions.write","instructions.delete","files.list","files.read","files.create","files.rename","files.delete","files.gitStatus","skills.list","assistants.list","assistants.resolve","assistants.cloneBuiltin","assistants.upsert","assistants.create","assistants.update","assistants.delete","assistants.setState","memory.list-files","memory.atlas","memory.activity","memory.observe","memory.propose","memory.consolidate","memory.update","memory.attachment.adopt","memory.attachment.locate"];var M=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.approval_request","turn.skill_instruction","turn.ask_user","turn.media_result","turn.media_progress","turn.media_usage","turn.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_delta","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.usage_update","team.member.notification","session.info","memory.updated","skills.updated","pet.soul_ready","pet.reaction","pet.growth","pet.state","pet.confirm","pet.asset.updated","system.activity","workflow.created","workflow.updated","workflow.deleted","workflow.runStarted","workflow.runCompleted","workflow.runFailed","workflow.nodeStatus"],k=["solo.progress","solo.agentDelta","solo.agentUsage","solo.agentDiff","solo.evaluation","product.taskStarted","product.taskOutput","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.checkpointed","product.dagTopology","plan.interrupted"],te=[...M,...k];var re=1,ne={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_CLOSE:"session/close",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",SESSION_LOAD:"session/load",SESSION_CANCEL:"session/cancel",SESSION_UPDATE:"session/update",SESSION_REQUEST_PERMISSION:"session/request_permission",FS_READ_TEXT_FILE:"fs/read_text_file",FS_WRITE_TEXT_FILE:"fs/write_text_file"},ie={ABORT:"x/abort",DREAM:"x/dream",AGENTS_LIST:"x/agents.list",SOLO_START:"x/solo.start",SOLO_STATUS:"x/solo.status",SOLO_SELECT:"x/solo.select",SOLO_CANCEL:"x/solo.cancel",PRODUCT_CREATE:"x/product.create",PRODUCT_PLAN:"x/product.plan",PRODUCT_CONFIRM:"x/product.confirm",PRODUCT_MESSAGE:"x/product.message",PRODUCT_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_STATUS:"x/product.status",SOLO_SUBSCRIBE:"x/solo.subscribe",SOLO_MESSAGE:"x/solo.message",SOLO_EVALUATE:"x/solo.evaluate",SOLO_SPEC_CHAT:"x/solo.specChat",SOLO_SPEC_JUDGE:"x/solo.specJudge",WORKFLOW_CHAT:"x/workflow.chat",PRODUCT_SUBSCRIBE:"x/product.subscribe"},x={USER_MESSAGE_CHUNK:"user_message_chunk",AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",USAGE_UPDATE:"usage_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",AVAILABLE_COMMANDS_UPDATE:"available_commands_update",CURRENT_MODE_UPDATE:"current_mode_update"},oe={X_SKILL_INSTRUCTION:"x_skill_instruction",X_SESSION_INFO:"x_session_info",X_RELAY:"x_relay"};function O(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&"id"in t}function N(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function w(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&"id"in t&&!("method"in t)}function se(e){let t;try{t=JSON.parse(e)}catch{return null}return w(t)||O(t)||N(t)?t:null}function ae(e){return Object.values(x).includes(e)}function pe(e){return e.startsWith("x_")}var E=["gatewayVersion","toolNamespaces","workspaceIds","installedCapabilities","enabledCapabilities","features","approvalMode","toolManifests","skillManifests","pluginManifests","mcpManifests","approvalPolicy","workspaceSummaries"];function g(e){return e?e.map(t=>({...t})):void 0}function S(e){return e?e.map(t=>({...t})):void 0}function ce(e){return e?[...e]:void 0}function D(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort((t,r)=>t.localeCompare(r))}function m(e){return{...e,toolNamespaces:[...e.toolNamespaces],workspaceIds:[...e.workspaceIds],...e.changedSections?{changedSections:[...e.changedSections]}:{},...e.installedCapabilities?{installedCapabilities:[...e.installedCapabilities]}:{},...e.enabledCapabilities?{enabledCapabilities:[...e.enabledCapabilities]}:{},...e.features?{features:[...e.features]}:{},...e.toolManifests?{toolManifests:g(e.toolManifests)}:{},...e.skillManifests?{skillManifests:g(e.skillManifests)}:{},...e.pluginManifests?{pluginManifests:g(e.pluginManifests)}:{},...e.mcpManifests?{mcpManifests:g(e.mcpManifests)}:{},...e.approvalPolicy?{approvalPolicy:{...e.approvalPolicy}}:{},...e.workspaceSummaries?{workspaceSummaries:S(e.workspaceSummaries)}:{}}}function le(e){let{previous:t,update:r}=e;return!(r.syncMode==="diff"&&t&&(!r.baseSnapshotVersion||t.snapshotVersion===r.baseSnapshotVersion))||!t?m(r):{...m(t),snapshotVersion:r.snapshotVersion,updatedAt:r.updatedAt,...r.gatewayVersion!==void 0?{gatewayVersion:r.gatewayVersion}:{},...r.syncMode?{syncMode:r.syncMode}:{},...r.baseSnapshotVersion?{baseSnapshotVersion:r.baseSnapshotVersion}:{},...r.changedSections?{changedSections:[...r.changedSections]}:{},...r.toolNamespaces?{toolNamespaces:[...r.toolNamespaces]}:{},...r.workspaceIds?{workspaceIds:[...r.workspaceIds]}:{},...r.installedCapabilities?{installedCapabilities:[...r.installedCapabilities]}:{},...r.enabledCapabilities?{enabledCapabilities:[...r.enabledCapabilities]}:{},...r.features?{features:[...r.features]}:{},...r.approvalMode?{approvalMode:r.approvalMode}:{},...r.toolManifests?{toolManifests:g(r.toolManifests)}:{},...r.skillManifests?{skillManifests:g(r.skillManifests)}:{},...r.pluginManifests?{pluginManifests:g(r.pluginManifests)}:{},...r.mcpManifests?{mcpManifests:g(r.mcpManifests)}:{},...r.approvalPolicy?{approvalPolicy:{...r.approvalPolicy}}:{},...r.workspaceSummaries?{workspaceSummaries:S(r.workspaceSummaries)}:{}}}function de(e){return D(e.map(t=>t.name.split(".")[0]??"").filter(Boolean))}function ue(e){return D(e.map(t=>t.id))}function ge(e){let{previous:t,current:r}=e;if(!t)return{...m(r),syncMode:"full"};if(t.snapshotVersion===r.snapshotVersion)return null;let n=E.filter(s=>JSON.stringify(t[s])!==JSON.stringify(r[s]));if(n.length===E.length)return{...m(r),syncMode:"full"};let o={snapshotVersion:r.snapshotVersion,updatedAt:r.updatedAt,syncMode:"diff",baseSnapshotVersion:t.snapshotVersion,changedSections:n,toolNamespaces:[...r.toolNamespaces],workspaceIds:[...r.workspaceIds]},c=o;for(let s of n){let i=r[s];if(i!==void 0)switch(s){case"toolNamespaces":case"workspaceIds":case"installedCapabilities":case"enabledCapabilities":case"features":c[s]=ce(i);break;case"approvalPolicy":c[s]={...i};break;case"workspaceSummaries":c[s]=S(i);break;case"toolManifests":case"skillManifests":case"pluginManifests":case"mcpManifests":c[s]=g(i);break;default:c[s]=i;break}}return o}var me=["web_search","web_fetch","deep_research","browser_execution"],ye=["web-intelligence","browser-execution"],fe=["discovery","read-url","multi-source-research","interactive-browser"],Ae=["stateless","render-backend","interactive-session"],Re=["stateless","stateless-single-step","stateful-session-required"],Ee=["required","conditional","none"],Se=["browser-read","browser-authenticated-read","browser-state-changing"];var _e=["read-page","read-authenticated-page","fill-form","submit-form","download-file","reuse-session"],be=["web_search","web_fetch","deep_research","blocked"],Te=["requires-interaction","requires-login-state","requires-rendered-dom","requires-persistent-session","requires-state-changing-action"],Pe=["none","same-capability-once","degrade-only"];var Ce=["prefetch","sync_turn","on_pre_compress","on_session_end","on_delegation","on_memory_write"],Ie=["turn","sidechain","compress","session-end","agent-remember","auto-extract","implicit-extract","profile-extraction","dream"],he=["observe-only","parent-write","deny"];var ve=2,a={gatewayImage:"gateway.image.desktop-slim",whisperModelTiny:"speech.whisper.model.tiny",ffmpegWin32X64:"runtime.ffmpeg.win32-x64",nodeWin32X64:"runtime.node.win32-x64",dockerDesktopWin32X64:"runtime.docker-desktop.win32-x64",dockerDesktopDarwinX64:"runtime.docker-desktop.darwin-x64",dockerDesktopDarwinArm64:"runtime.docker-desktop.darwin-arm64"},y={desktopDockerBridge:"desktop.docker-bridge",desktopEmbeddedWin32X64:"desktop.embedded.win32-x64"};function U(e){return{...e,artifacts:e.artifacts.map(t=>({...t}))}}function Me(e){return{...e,assetIds:[...e.assetIds]}}function W(){return{[y.desktopDockerBridge]:{id:y.desktopDockerBridge,title:"Desktop Docker Bridge",platform:"any",assetIds:[a.gatewayImage,a.dockerDesktopWin32X64,a.dockerDesktopDarwinX64,a.dockerDesktopDarwinArm64],description:"Docker bridge mode downloads the desktop slim gateway image on demand."},[y.desktopEmbeddedWin32X64]:{id:y.desktopEmbeddedWin32X64,title:"Desktop Embedded Win32 x64",platform:"win32-x64",assetIds:[a.nodeWin32X64,a.ffmpegWin32X64,a.whisperModelTiny],description:"Embedded desktop mode requires the bundled Node/FFmpeg runtimes and the whisper model asset."}}}function K(e,t){return e.assets[t]}function V(e,t){return e.profiles[t]}function ke(e,t){let r=V(e,t);return r?r.assetIds.map(n=>K(e,n)).filter(n=>!!n):[]}function xe(e,t){return e.assets[t.id]=U(t),F(e)}function _(e){if(!e)return;let t=e.artifacts[0];if(!(!t?.url||!t.sha256||typeof t.size!="number"))return{version:e.version,sha256:t.sha256,size:t.size,url:t.url}}function F(e){let t=_(e.assets[a.gatewayImage]),r=_(e.assets[a.whisperModelTiny]);return{...e,gateway:t,whisperModel:r}}function L(e,t){if(!(typeof e.version!="string"||typeof e.url!="string"))return{...t,version:e.version,artifacts:[{fileName:e.url.split("/").pop()||`${t.id}.bin`,url:e.url,sha256:typeof e.sha256=="string"?e.sha256:void 0,size:typeof e.size=="number"?e.size:void 0}]}}function Oe(e){let t=e&&typeof e=="object"?e:{},r={},n=t.assets&&typeof t.assets=="object"?t.assets:{};for(let[i,p]of Object.entries(n)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.artifacts)||(r[i]=U(u))}if(!r[a.gatewayImage]&&t.gateway&&typeof t.gateway=="object"){let i=L(t.gateway,{id:a.gatewayImage,title:"OpenClaw Gateway Image (Desktop Slim)",kind:"container-image",delivery:"remote",platform:"any",description:"Desktop Docker mode gateway image."});i&&(r[i.id]=i)}if(!r[a.whisperModelTiny]&&t.whisperModel&&typeof t.whisperModel=="object"){let i=L(t.whisperModel,{id:a.whisperModelTiny,title:"Whisper Tiny Model",kind:"model",delivery:"remote",platform:"any",description:"Shared whisper.cpp tiny model asset for embedded desktop speech recognition."});i&&(r[i.id]=i)}let c={...W()},s=t.profiles&&typeof t.profiles=="object"?t.profiles:{};for(let[i,p]of Object.entries(s)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.assetIds)||(c[i]=Me(u))}return F({schemaVersion:typeof t.schemaVersion=="number"?t.schemaVersion:2,channel:typeof t.channel=="string"?t.channel:void 0,publishedAt:typeof t.publishedAt=="string"?t.publishedAt:void 0,minElectronVersion:typeof t.minElectronVersion=="string"?t.minElectronVersion:void 0,releaseNotes:typeof t.releaseNotes=="string"?t.releaseNotes:void 0,assets:r,profiles:c})}var Ne=["pending","captured","failed","restored"],we=["file","directory","missing"],De=["metadata-only","workspace-copy","shadow-git"];var Le=["api-key","oauth","token","aws-sdk"],Ue=["rate_limit","auth","server_error","timeout","network","unknown"],We=["requiresOpenAiAnthropicToolPayload"];function Ke(e,t){return!e||typeof e!="object"||Array.isArray(e)?!1:e[t]===!0}var j="openai-codex";function A(e){let t=e.trim().toLowerCase();return t==="z.ai"||t==="z-ai"?"zai":t==="opencode-zen"?"opencode":t==="kimi-code"?"kimi-coding":t==="bedrock"||t==="aws-bedrock"?"amazon-bedrock":t==="bytedance"||t==="doubao"?"volcengine":t}function B(e){let t=A(e);return t==="volcengine-plan"?"volcengine":t==="qwen-coding"?"qwen":t==="byteplus-plan"?"byteplus":t}var Ve=B,Fe={anthropicToolSchemaMode:"native",anthropicToolChoiceMode:"native",providerFamily:"default",preserveAnthropicThinkingSignatures:!0,openAiCompatTurnValidation:!0,providerThoughtSignatureSanitization:!1,transcriptToolCallIdMode:"default",transcriptToolCallIdModelHints:[],providerThoughtSignatureModelHints:[],dropThinkingBlockModelHints:[]},je={anthropic:{providerFamily:"anthropic"},"amazon-bedrock":{providerFamily:"anthropic"},"kimi-coding":{anthropicToolSchemaMode:"openai-functions",anthropicToolChoiceMode:"openai-string-modes",preserveAnthropicThinkingSignatures:!1},mistral:{transcriptToolCallIdMode:"strict9",transcriptToolCallIdModelHints:["mistral","mixtral","codestral","pixtral","devstral","ministral","mistralai"]},openai:{providerFamily:"openai"},[j]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};function b(e,t){let r=(e??"").toLowerCase();return!!r&&t.some(n=>r.includes(n))}function l(e){let t=A(e??"");return{...Fe,...je[t]}}function Be(e){return l(e).preserveAnthropicThinkingSignatures}function qe(e){let t=l(e);return t.anthropicToolSchemaMode!=="native"||t.anthropicToolChoiceMode!=="native"}function Ye(e){return l(e).anthropicToolSchemaMode==="openai-functions"}function He(e){return l(e).anthropicToolChoiceMode==="openai-string-modes"}function Ge(e){return l(e).openAiCompatTurnValidation}function ze(e){return l(e).providerFamily==="openai"}function Xe(e){return l(e).providerFamily==="anthropic"}function Je(e){return b(e.modelId,l(e.provider).dropThinkingBlockModelHints)}function Qe(e){let t=l(e.provider);return t.providerThoughtSignatureSanitization&&b(e.modelId,t.providerThoughtSignatureModelHints)}function $e(e,t){let r=l(e),n=r.transcriptToolCallIdMode;if(n==="strict9")return n;if(b(t,r.transcriptToolCallIdModelHints))return"strict9"}var T={anthropic:["ANTHROPIC_OAUTH_TOKEN","ANTHROPIC_API_KEY"],chutes:["CHUTES_OAUTH_TOKEN","CHUTES_API_KEY"],zai:["ZAI_API_KEY","Z_AI_API_KEY"],opencode:["OPENCODE_API_KEY","OPENCODE_ZEN_API_KEY"],qwen:["DASHSCOPE_API_KEY","QWEN_API_KEY"],"qwen-coding":["DASHSCOPE_API_KEY","QWEN_API_KEY"],volcengine:["VOLCANO_ENGINE_API_KEY","ARK_API_KEY","DOUBAO_API_KEY"],"volcengine-plan":["VOLCANO_ENGINE_API_KEY","ARK_API_KEY","DOUBAO_API_KEY"],byteplus:["BYTEPLUS_API_KEY"],"byteplus-plan":["BYTEPLUS_API_KEY"],"kimi-coding":["KIMI_API_KEY","KIMICODE_API_KEY"],huggingface:["HUGGINGFACE_HUB_TOKEN","HF_TOKEN"],openai:["OPENAI_API_KEY"],voyage:["VOYAGE_API_KEY"],groq:["GROQ_API_KEY"],deepgram:["DEEPGRAM_API_KEY"],cerebras:["CEREBRAS_API_KEY"],xai:["XAI_API_KEY"],openrouter:["OPENROUTER_API_KEY"],litellm:["LITELLM_API_KEY"],"vercel-ai-gateway":["AI_GATEWAY_API_KEY"],"cloudflare-ai-gateway":["CLOUDFLARE_AI_GATEWAY_API_KEY"],moonshot:["MOONSHOT_API_KEY"],minimax:["MINIMAX_API_KEY"],"minimax-cn":["MINIMAX_CN_API_KEY","MINIMAX_API_KEY"],nvidia:["NVIDIA_API_KEY"],xiaomi:["XIAOMI_API_KEY"],synthetic:["SYNTHETIC_API_KEY"],venice:["VENICE_API_KEY"],mistral:["MISTRAL_API_KEY"],together:["TOGETHER_API_KEY"],qianfan:["QIANFAN_API_KEY"],ollama:["OLLAMA_API_KEY"],vllm:["VLLM_API_KEY"],kilocode:["KILOCODE_API_KEY"]};function Ze(){return[...new Set(Object.values(T).flat())]}function et(e){let t=A(e.provider),r=e.env??process.env,n=new Set(e.appliedEnvKeys??[]),o=i=>{let p=r[i]?.trim();if(!p)return null;let u=n.has(i)?`shell env: ${i}`:`env: ${i}`;return{apiKey:p,source:u}},c=e.resolveSpecialApiKey?.(t,r,n);if(c)return c;let s=T[t];if(!s||s.length===0)return null;for(let i of s){let p=o(i);if(p)return p}return null}export{ie as ACP_EXTENDED_METHODS,oe as ACP_EXTENDED_SESSION_UPDATE_TYPES,ne as ACP_METHODS,re as ACP_PROTOCOL_VERSION,x as ACP_SESSION_UPDATE_TYPES,H as AGENT_RPC_APPROVAL_METHODS,d as AGENT_RPC_ERROR_CODES,Y as AGENT_RPC_PROTOCOL_VERSION,k as AGENT_TEAM_WS_EVENT_NAMES,M as AGENT_WS_EVENT_NAMES,te as ALL_AGENT_WS_EVENT_NAMES,E as CAPABILITY_MANIFEST_DIFF_SECTIONS,ee as GATEWAY_RPC_METHODS,R as GatewayRpcContract,Ce as MEMORY_OBSERVATION_HOOK_VALUES,Ie as MEMORY_OBSERVATION_SOURCE_VALUES,he as MEMORY_WRITE_ACCESS_VALUES,De as MUTATION_CHECKPOINT_BACKEND_VALUES,we as MUTATION_CHECKPOINT_ENTRY_KIND_VALUES,Ne as MUTATION_CHECKPOINT_PHASE_VALUES,q as PETDEX_ANIMATION_IDS,Le as PROVIDER_RUNTIME_AUTH_MODE_VALUES,We as PROVIDER_RUNTIME_COMPAT_FLAG_VALUES,T as PROVIDER_RUNTIME_ENV_API_KEY_CANDIDATES,j as PROVIDER_RUNTIME_OPENAI_CODEX_PROVIDER_ID,Ue as PROVIDER_RUNTIME_VAULT_ERROR_TYPE_VALUES,ve as RESOURCE_MANIFEST_SCHEMA_VERSION,a as RUNTIME_ASSET_IDS,y as RUNTIME_PROFILE_IDS,_e as WEB_ACTION_SCOPE_VALUES,Ee as WEB_APPROVAL_DEFAULT_VALUES,ye as WEB_CAPABILITY_FAMILY_VALUES,me as WEB_CAPABILITY_ID_VALUES,be as WEB_DEGRADATION_TARGET_VALUES,Te as WEB_ESCALATION_REASON_VALUES,Ae as WEB_EXECUTION_MODE_VALUES,Se as WEB_POLICY_RISK_CLASS_VALUES,Pe as WEB_RETRY_POLICY_VALUES,Re as WEB_STATEFULNESS_VALUES,fe as WEB_TASK_MODE_VALUES,Z as buildAgentRpcMeta,f as classifyGatewayRpcMethod,m as cloneCapabilityManifestSnapshot,ge as createCapabilityManifestDiffPayload,W as createDefaultRuntimeResourceProfiles,de as deriveCapabilityToolNamespaces,ue as deriveCapabilityWorkspaceIds,_ as getManifestShortcutEntry,K as getRuntimeResourceAsset,V as getRuntimeResourceProfile,ke as getRuntimeResourceProfileAssets,N as isAcpJsonRpcNotification,O as isAcpJsonRpcRequest,w as isAcpJsonRpcResponse,I as isAgentRpcNotification,P as isAgentRpcRequest,C as isAgentRpcResponse,Xe as isAnthropicProviderRuntimeFamily,pe as isExtendedSessionUpdateType,ze as isOpenAiProviderRuntimeFamily,ae as isStandardSessionUpdateType,Ze as listProviderRuntimeEnvApiKeyNames,le as mergeCapabilityManifestSnapshot,A as normalizeProviderRuntimeId,B as normalizeProviderRuntimeIdForAuth,Oe as normalizeRuntimeResourceManifest,se as parseAcpMessage,G as parseAgentRpcMessage,Be as preservesProviderRuntimeAnthropicThinkingSignatures,Ke as readProviderRuntimeCompatFlag,v as requireGatewayRpcMeta,h as requiresIdempotencyKey,qe as requiresOpenAiCompatibleAnthropicToolPayloadForProviderRuntime,l as resolveProviderRuntimeCapabilities,et as resolveProviderRuntimeEnvApiKey,Ve as resolveProviderRuntimeKeyFamily,$e as resolveProviderRuntimeTranscriptToolCallIdMode,Je as shouldDropThinkingBlocksForProviderRuntimeModel,Qe as shouldSanitizeProviderRuntimeThoughtSignaturesForModel,Ge as supportsOpenAiCompatTurnValidationForProviderRuntime,xe as upsertRuntimeResourceAsset,Ye as usesOpenAiFunctionAnthropicToolSchemaForProviderRuntime,He as usesOpenAiStringModeAnthropicToolChoiceForProviderRuntime};
1
+ var q=["idle","running-right","running-left","waving","jumping","failed","waiting","running","review"];var Y="1.0.0",d={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TURN_ABORTED:-32e3,TURN_TIMEOUT:-32001,LLM_ERROR:-32010,LLM_AUTH_ERROR:-32011,LLM_RATE_LIMIT:-32012,LLM_QUOTA_EXHAUSTED:-32013,LLM_MODEL_NOT_FOUND:-32014,TOOL_INVOKE_FAILED:-32020,TOOL_TIMEOUT:-32021,PROTOCOL_MISMATCH:-32030,REQUEST_DEADLINE_EXCEEDED:-32040,REQUEST_CANCELLED:-32041,REQUEST_DEDUPED:-32042,REQUEST_IDEMPOTENCY_REQUIRED:-32043},H={REQUEST:"tool.approval.request"};function P(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&t.method.length>0}function C(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&(typeof t.id=="string"||typeof t.id=="number")&&!("method"in t)}function h(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function G(e){let t;try{t=JSON.parse(e)}catch{return null}return C(t)||P(t)||h(t)?t:null}import{randomUUID as z}from"node:crypto";var X=["settings.list","settings.get","settings.validate","provider.list","config.get","config.tunables","tools.list","todos.list","tasks.list","agents.list","agents.get","agents.processes","agents.scan","session.list","session.get","session.resolve","thread.list","project.list","files.list","files.gitStatus","instructions.list","instructions.read","skills.list","skills.stats","memory.atlas","memory.activity","memory.list","memory.read","memory.search","media.listModels","media.status","pet.status","agent.health","agent.metrics"],J=new Set(["memory.dream","memory.propose","memory.consolidate","media.stt","pet.forge","pet.asset.import","solo.start","solo.evaluate","product.plan","product.create","product.message"]),Q=["memory.","pet.","usage."],$=new Set(["memory.atlas","memory.activity","memory.list","memory.read","memory.search","memory.attachment.locate","memory.attachment.adopt","pet.status"]);function f(e){return J.has(e)?{channel:"task",mutability:"write",defaultTimeoutMs:12e4}:X.some(t=>e===t||e.startsWith(`${t}.`)||e.startsWith(t))?{channel:"query",mutability:"read",defaultTimeoutMs:1e4}:{channel:"task",mutability:"write",defaultTimeoutMs:3e4}}function I(e){return $.has(e)||f(e).mutability==="read"?!1:Q.some(t=>e.startsWith(t))}function Z(e,t={}){let r=t.now??Date.now(),o=f(e),i=t.timeoutMs??o.defaultTimeoutMs;return{requestId:t.requestId??z(),createdAt:r,deadlineAt:r+i,channel:t.channel??o.channel,idempotencyKey:t.idempotencyKey,traceId:t.traceId}}function v(e,t=Date.now()){let r=e.meta;if(!r||typeof r!="object")return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta is required."}};if(typeof r.requestId!="string"||r.requestId.length===0)return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.requestId is required."}};if(r.channel!=="query"&&r.channel!=="task")return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.channel must be query or task."}};if(typeof r.createdAt!="number"||!Number.isFinite(r.createdAt))return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.createdAt is required."}};if(typeof r.deadlineAt!="number"||!Number.isFinite(r.deadlineAt))return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.deadlineAt is required."}};if(r.deadlineAt<=t)return{ok:!1,error:{code:d.REQUEST_DEADLINE_EXCEEDED,message:"RPC request deadline has already expired."}};let o=f(e.method).channel;return r.channel!==o?{ok:!1,error:{code:d.INVALID_REQUEST,message:`RPC request channel mismatch: expected ${o}, got ${r.channel}.`}}:I(e.method)&&(typeof r.idempotencyKey!="string"||r.idempotencyKey.length===0)?{ok:!1,error:{code:d.REQUEST_IDEMPOTENCY_REQUIRED,message:`RPC method ${e.method} requires meta.idempotencyKey.`}}:{ok:!0,meta:r}}var R=class{now;active=new Map;idempotency=new Map;counters={completedRequests:0,cancelledRequests:0,deadlineExceededRequests:0,dedupedRequests:0,lateResponsesDropped:0,invalidRequests:0};constructor(t={}){this.now=t.now??(()=>Date.now())}begin(t,r){let o=v({method:t,meta:r},this.now());if(!o.ok)return this.counters.invalidRequests+=1,{status:"rejected",error:o.error};if(r.idempotencyKey){let i=this.idempotency.get(r.idempotencyKey);if(i)return this.counters.dedupedRequests+=1,i.error?{status:"deduped",error:i.error}:{status:"deduped",result:i.result}}return this.active.set(r.requestId,{method:t,meta:r,cancelled:!1,startedAt:this.now()}),{status:"started"}}cancel(t,r="cancelled"){let o=this.active.get(t);return!o||o.cancelled?!1:(o.cancelled=!0,o.cancelReason=r,this.counters.cancelledRequests+=1,!0)}expire(t){return this.active.get(t)?(this.active.delete(t),this.counters.deadlineExceededRequests+=1,!0):!1}settle(t,r,o){let i=this.active.get(t);return i?(this.active.delete(t),i.cancelled?(this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"cancelled"}):i.meta.deadlineAt<=this.now()?(this.counters.deadlineExceededRequests+=1,this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"deadline_exceeded"}):(this.counters.completedRequests+=1,i.meta.idempotencyKey&&this.idempotency.set(i.meta.idempotencyKey,{result:r,error:o,settledAt:this.now()}),{accepted:!0})):{accepted:!1,reason:"unknown"}}metrics(){return{activeRequests:this.active.size,...this.counters}}};var ee=["agent.health","agent.metrics","agent.cancel","session.list","session.get","session.create","session.update","session.delete","session.deleteAll","session.archive","session.moveToProject","session.getState","session.switchProject","session.getMessages","project.list","project.create","project.delete","project.rename","project.archive","project.unarchive","project.update","project.archiveByGroup","project.purgeAll","instructions.list","instructions.read","instructions.write","instructions.delete","files.list","files.read","files.create","files.rename","files.delete","files.gitStatus","skills.list","memory.list-files","memory.atlas","memory.activity","memory.observe","memory.propose","memory.consolidate","memory.update","memory.attachment.adopt","memory.attachment.locate"];var M=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.approval_request","turn.skill_instruction","turn.ask_user","turn.media_result","turn.media_progress","turn.media_usage","turn.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_delta","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.usage_update","team.member.notification","session.info","memory.updated","skills.updated","pet.soul_ready","pet.reaction","pet.growth","pet.state","pet.confirm","pet.asset.updated","system.activity","workflow.created","workflow.updated","workflow.deleted","workflow.runStarted","workflow.runCompleted","workflow.runFailed","workflow.nodeStatus"],k=["solo.progress","solo.agentDelta","solo.agentUsage","solo.agentDiff","solo.evaluation","product.taskStarted","product.taskOutput","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.checkpointed","product.dagTopology","plan.interrupted"],te=[...M,...k];var re=1,oe={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_CLOSE:"session/close",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",SESSION_LOAD:"session/load",SESSION_CANCEL:"session/cancel",SESSION_UPDATE:"session/update",SESSION_REQUEST_PERMISSION:"session/request_permission",FS_READ_TEXT_FILE:"fs/read_text_file",FS_WRITE_TEXT_FILE:"fs/write_text_file"},ne={ABORT:"x/abort",DREAM:"x/dream",AGENTS_LIST:"x/agents.list",SOLO_START:"x/solo.start",SOLO_STATUS:"x/solo.status",SOLO_SELECT:"x/solo.select",SOLO_CANCEL:"x/solo.cancel",PRODUCT_CREATE:"x/product.create",PRODUCT_PLAN:"x/product.plan",PRODUCT_CONFIRM:"x/product.confirm",PRODUCT_MESSAGE:"x/product.message",PRODUCT_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_STATUS:"x/product.status",SOLO_SUBSCRIBE:"x/solo.subscribe",SOLO_MESSAGE:"x/solo.message",SOLO_EVALUATE:"x/solo.evaluate",SOLO_SPEC_CHAT:"x/solo.specChat",SOLO_SPEC_JUDGE:"x/solo.specJudge",WORKFLOW_CHAT:"x/workflow.chat",PRODUCT_SUBSCRIBE:"x/product.subscribe"},x={USER_MESSAGE_CHUNK:"user_message_chunk",AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",USAGE_UPDATE:"usage_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",AVAILABLE_COMMANDS_UPDATE:"available_commands_update",CURRENT_MODE_UPDATE:"current_mode_update"},ie={X_SKILL_INSTRUCTION:"x_skill_instruction",X_SESSION_INFO:"x_session_info",X_RELAY:"x_relay"};function O(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&"id"in t}function N(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function w(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&"id"in t&&!("method"in t)}function se(e){let t;try{t=JSON.parse(e)}catch{return null}return w(t)||O(t)||N(t)?t:null}function ae(e){return Object.values(x).includes(e)}function pe(e){return e.startsWith("x_")}var E=["gatewayVersion","toolNamespaces","workspaceIds","installedCapabilities","enabledCapabilities","features","approvalMode","toolManifests","skillManifests","pluginManifests","mcpManifests","approvalPolicy","workspaceSummaries"];function g(e){return e?e.map(t=>({...t})):void 0}function S(e){return e?e.map(t=>({...t})):void 0}function ce(e){return e?[...e]:void 0}function D(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort((t,r)=>t.localeCompare(r))}function m(e){return{...e,toolNamespaces:[...e.toolNamespaces],workspaceIds:[...e.workspaceIds],...e.changedSections?{changedSections:[...e.changedSections]}:{},...e.installedCapabilities?{installedCapabilities:[...e.installedCapabilities]}:{},...e.enabledCapabilities?{enabledCapabilities:[...e.enabledCapabilities]}:{},...e.features?{features:[...e.features]}:{},...e.toolManifests?{toolManifests:g(e.toolManifests)}:{},...e.skillManifests?{skillManifests:g(e.skillManifests)}:{},...e.pluginManifests?{pluginManifests:g(e.pluginManifests)}:{},...e.mcpManifests?{mcpManifests:g(e.mcpManifests)}:{},...e.approvalPolicy?{approvalPolicy:{...e.approvalPolicy}}:{},...e.workspaceSummaries?{workspaceSummaries:S(e.workspaceSummaries)}:{}}}function le(e){let{previous:t,update:r}=e;return!(r.syncMode==="diff"&&t&&(!r.baseSnapshotVersion||t.snapshotVersion===r.baseSnapshotVersion))||!t?m(r):{...m(t),snapshotVersion:r.snapshotVersion,updatedAt:r.updatedAt,...r.gatewayVersion!==void 0?{gatewayVersion:r.gatewayVersion}:{},...r.syncMode?{syncMode:r.syncMode}:{},...r.baseSnapshotVersion?{baseSnapshotVersion:r.baseSnapshotVersion}:{},...r.changedSections?{changedSections:[...r.changedSections]}:{},...r.toolNamespaces?{toolNamespaces:[...r.toolNamespaces]}:{},...r.workspaceIds?{workspaceIds:[...r.workspaceIds]}:{},...r.installedCapabilities?{installedCapabilities:[...r.installedCapabilities]}:{},...r.enabledCapabilities?{enabledCapabilities:[...r.enabledCapabilities]}:{},...r.features?{features:[...r.features]}:{},...r.approvalMode?{approvalMode:r.approvalMode}:{},...r.toolManifests?{toolManifests:g(r.toolManifests)}:{},...r.skillManifests?{skillManifests:g(r.skillManifests)}:{},...r.pluginManifests?{pluginManifests:g(r.pluginManifests)}:{},...r.mcpManifests?{mcpManifests:g(r.mcpManifests)}:{},...r.approvalPolicy?{approvalPolicy:{...r.approvalPolicy}}:{},...r.workspaceSummaries?{workspaceSummaries:S(r.workspaceSummaries)}:{}}}function de(e){return D(e.map(t=>t.name.split(".")[0]??"").filter(Boolean))}function ue(e){return D(e.map(t=>t.id))}function ge(e){let{previous:t,current:r}=e;if(!t)return{...m(r),syncMode:"full"};if(t.snapshotVersion===r.snapshotVersion)return null;let o=E.filter(s=>JSON.stringify(t[s])!==JSON.stringify(r[s]));if(o.length===E.length)return{...m(r),syncMode:"full"};let i={snapshotVersion:r.snapshotVersion,updatedAt:r.updatedAt,syncMode:"diff",baseSnapshotVersion:t.snapshotVersion,changedSections:o,toolNamespaces:[...r.toolNamespaces],workspaceIds:[...r.workspaceIds]},c=i;for(let s of o){let n=r[s];if(n!==void 0)switch(s){case"toolNamespaces":case"workspaceIds":case"installedCapabilities":case"enabledCapabilities":case"features":c[s]=ce(n);break;case"approvalPolicy":c[s]={...n};break;case"workspaceSummaries":c[s]=S(n);break;case"toolManifests":case"skillManifests":case"pluginManifests":case"mcpManifests":c[s]=g(n);break;default:c[s]=n;break}}return i}var me=["web_search","web_fetch","deep_research","browser_execution"],ye=["web-intelligence","browser-execution"],fe=["discovery","read-url","multi-source-research","interactive-browser"],Ae=["stateless","render-backend","interactive-session"],Re=["stateless","stateless-single-step","stateful-session-required"],Ee=["required","conditional","none"],Se=["browser-read","browser-authenticated-read","browser-state-changing"];var _e=["read-page","read-authenticated-page","fill-form","submit-form","download-file","reuse-session"],be=["web_search","web_fetch","deep_research","blocked"],Te=["requires-interaction","requires-login-state","requires-rendered-dom","requires-persistent-session","requires-state-changing-action"],Pe=["none","same-capability-once","degrade-only"];var Ce=["prefetch","sync_turn","on_pre_compress","on_session_end","on_delegation","on_memory_write"],he=["turn","sidechain","compress","session-end","agent-remember","auto-extract","implicit-extract","profile-extraction","dream"],Ie=["observe-only","parent-write","deny"];var ve=2,a={gatewayImage:"gateway.image.desktop-slim",whisperModelTiny:"speech.whisper.model.tiny",ffmpegWin32X64:"runtime.ffmpeg.win32-x64",nodeWin32X64:"runtime.node.win32-x64",dockerDesktopWin32X64:"runtime.docker-desktop.win32-x64",dockerDesktopDarwinX64:"runtime.docker-desktop.darwin-x64",dockerDesktopDarwinArm64:"runtime.docker-desktop.darwin-arm64"},y={desktopDockerBridge:"desktop.docker-bridge",desktopEmbeddedWin32X64:"desktop.embedded.win32-x64"};function U(e){return{...e,artifacts:e.artifacts.map(t=>({...t}))}}function Me(e){return{...e,assetIds:[...e.assetIds]}}function K(){return{[y.desktopDockerBridge]:{id:y.desktopDockerBridge,title:"Desktop Docker Bridge",platform:"any",assetIds:[a.gatewayImage,a.dockerDesktopWin32X64,a.dockerDesktopDarwinX64,a.dockerDesktopDarwinArm64],description:"Docker bridge mode downloads the desktop slim gateway image on demand."},[y.desktopEmbeddedWin32X64]:{id:y.desktopEmbeddedWin32X64,title:"Desktop Embedded Win32 x64",platform:"win32-x64",assetIds:[a.nodeWin32X64,a.ffmpegWin32X64,a.whisperModelTiny],description:"Embedded desktop mode requires the bundled Node/FFmpeg runtimes and the whisper model asset."}}}function W(e,t){return e.assets[t]}function V(e,t){return e.profiles[t]}function ke(e,t){let r=V(e,t);return r?r.assetIds.map(o=>W(e,o)).filter(o=>!!o):[]}function xe(e,t){return e.assets[t.id]=U(t),F(e)}function _(e){if(!e)return;let t=e.artifacts[0];if(!(!t?.url||!t.sha256||typeof t.size!="number"))return{version:e.version,sha256:t.sha256,size:t.size,url:t.url}}function F(e){let t=_(e.assets[a.gatewayImage]),r=_(e.assets[a.whisperModelTiny]);return{...e,gateway:t,whisperModel:r}}function L(e,t){if(!(typeof e.version!="string"||typeof e.url!="string"))return{...t,version:e.version,artifacts:[{fileName:e.url.split("/").pop()||`${t.id}.bin`,url:e.url,sha256:typeof e.sha256=="string"?e.sha256:void 0,size:typeof e.size=="number"?e.size:void 0}]}}function Oe(e){let t=e&&typeof e=="object"?e:{},r={},o=t.assets&&typeof t.assets=="object"?t.assets:{};for(let[n,p]of Object.entries(o)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.artifacts)||(r[n]=U(u))}if(!r[a.gatewayImage]&&t.gateway&&typeof t.gateway=="object"){let n=L(t.gateway,{id:a.gatewayImage,title:"OpenClaw Gateway Image (Desktop Slim)",kind:"container-image",delivery:"remote",platform:"any",description:"Desktop Docker mode gateway image."});n&&(r[n.id]=n)}if(!r[a.whisperModelTiny]&&t.whisperModel&&typeof t.whisperModel=="object"){let n=L(t.whisperModel,{id:a.whisperModelTiny,title:"Whisper Tiny Model",kind:"model",delivery:"remote",platform:"any",description:"Shared whisper.cpp tiny model asset for embedded desktop speech recognition."});n&&(r[n.id]=n)}let c={...K()},s=t.profiles&&typeof t.profiles=="object"?t.profiles:{};for(let[n,p]of Object.entries(s)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.assetIds)||(c[n]=Me(u))}return F({schemaVersion:typeof t.schemaVersion=="number"?t.schemaVersion:2,channel:typeof t.channel=="string"?t.channel:void 0,publishedAt:typeof t.publishedAt=="string"?t.publishedAt:void 0,minElectronVersion:typeof t.minElectronVersion=="string"?t.minElectronVersion:void 0,releaseNotes:typeof t.releaseNotes=="string"?t.releaseNotes:void 0,assets:r,profiles:c})}var Ne=["pending","captured","failed","restored"],we=["file","directory","missing"],De=["metadata-only","workspace-copy","shadow-git"];var Le=["api-key","oauth","token","aws-sdk"],Ue=["rate_limit","auth","server_error","timeout","network","unknown"],Ke=["requiresOpenAiAnthropicToolPayload"];function We(e,t){return!e||typeof e!="object"||Array.isArray(e)?!1:e[t]===!0}var j="openai-codex";function A(e){let t=e.trim().toLowerCase();return t==="z.ai"||t==="z-ai"?"zai":t==="opencode-zen"?"opencode":t==="kimi-code"?"kimi-coding":t==="bedrock"||t==="aws-bedrock"?"amazon-bedrock":t==="bytedance"||t==="doubao"?"volcengine":t}function B(e){let t=A(e);return t==="volcengine-plan"?"volcengine":t==="qwen-coding"?"qwen":t==="byteplus-plan"?"byteplus":t}var Ve=B,Fe={anthropicToolSchemaMode:"native",anthropicToolChoiceMode:"native",providerFamily:"default",preserveAnthropicThinkingSignatures:!0,openAiCompatTurnValidation:!0,providerThoughtSignatureSanitization:!1,transcriptToolCallIdMode:"default",transcriptToolCallIdModelHints:[],providerThoughtSignatureModelHints:[],dropThinkingBlockModelHints:[]},je={anthropic:{providerFamily:"anthropic"},"amazon-bedrock":{providerFamily:"anthropic"},"kimi-coding":{anthropicToolSchemaMode:"openai-functions",anthropicToolChoiceMode:"openai-string-modes",preserveAnthropicThinkingSignatures:!1},mistral:{transcriptToolCallIdMode:"strict9",transcriptToolCallIdModelHints:["mistral","mixtral","codestral","pixtral","devstral","ministral","mistralai"]},openai:{providerFamily:"openai"},[j]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};function b(e,t){let r=(e??"").toLowerCase();return!!r&&t.some(o=>r.includes(o))}function l(e){let t=A(e??"");return{...Fe,...je[t]}}function Be(e){return l(e).preserveAnthropicThinkingSignatures}function qe(e){let t=l(e);return t.anthropicToolSchemaMode!=="native"||t.anthropicToolChoiceMode!=="native"}function Ye(e){return l(e).anthropicToolSchemaMode==="openai-functions"}function He(e){return l(e).anthropicToolChoiceMode==="openai-string-modes"}function Ge(e){return l(e).openAiCompatTurnValidation}function ze(e){return l(e).providerFamily==="openai"}function Xe(e){return l(e).providerFamily==="anthropic"}function Je(e){return b(e.modelId,l(e.provider).dropThinkingBlockModelHints)}function Qe(e){let t=l(e.provider);return t.providerThoughtSignatureSanitization&&b(e.modelId,t.providerThoughtSignatureModelHints)}function $e(e,t){let r=l(e),o=r.transcriptToolCallIdMode;if(o==="strict9")return o;if(b(t,r.transcriptToolCallIdModelHints))return"strict9"}var T={anthropic:["ANTHROPIC_OAUTH_TOKEN","ANTHROPIC_API_KEY"],chutes:["CHUTES_OAUTH_TOKEN","CHUTES_API_KEY"],zai:["ZAI_API_KEY","Z_AI_API_KEY"],opencode:["OPENCODE_API_KEY","OPENCODE_ZEN_API_KEY"],qwen:["DASHSCOPE_API_KEY","QWEN_API_KEY"],"qwen-coding":["DASHSCOPE_API_KEY","QWEN_API_KEY"],volcengine:["VOLCANO_ENGINE_API_KEY","ARK_API_KEY","DOUBAO_API_KEY"],"volcengine-plan":["VOLCANO_ENGINE_API_KEY","ARK_API_KEY","DOUBAO_API_KEY"],byteplus:["BYTEPLUS_API_KEY"],"byteplus-plan":["BYTEPLUS_API_KEY"],"kimi-coding":["KIMI_API_KEY","KIMICODE_API_KEY"],huggingface:["HUGGINGFACE_HUB_TOKEN","HF_TOKEN"],openai:["OPENAI_API_KEY"],voyage:["VOYAGE_API_KEY"],groq:["GROQ_API_KEY"],deepgram:["DEEPGRAM_API_KEY"],cerebras:["CEREBRAS_API_KEY"],xai:["XAI_API_KEY"],openrouter:["OPENROUTER_API_KEY"],litellm:["LITELLM_API_KEY"],"vercel-ai-gateway":["AI_GATEWAY_API_KEY"],"cloudflare-ai-gateway":["CLOUDFLARE_AI_GATEWAY_API_KEY"],moonshot:["MOONSHOT_API_KEY"],minimax:["MINIMAX_API_KEY"],"minimax-cn":["MINIMAX_CN_API_KEY","MINIMAX_API_KEY"],nvidia:["NVIDIA_API_KEY"],xiaomi:["XIAOMI_API_KEY"],synthetic:["SYNTHETIC_API_KEY"],venice:["VENICE_API_KEY"],mistral:["MISTRAL_API_KEY"],together:["TOGETHER_API_KEY"],qianfan:["QIANFAN_API_KEY"],ollama:["OLLAMA_API_KEY"],vllm:["VLLM_API_KEY"],kilocode:["KILOCODE_API_KEY"]};function Ze(){return[...new Set(Object.values(T).flat())]}function et(e){let t=A(e.provider),r=e.env??process.env,o=new Set(e.appliedEnvKeys??[]),i=n=>{let p=r[n]?.trim();if(!p)return null;let u=o.has(n)?`shell env: ${n}`:`env: ${n}`;return{apiKey:p,source:u}},c=e.resolveSpecialApiKey?.(t,r,o);if(c)return c;let s=T[t];if(!s||s.length===0)return null;for(let n of s){let p=i(n);if(p)return p}return null}export{ne as ACP_EXTENDED_METHODS,ie as ACP_EXTENDED_SESSION_UPDATE_TYPES,oe as ACP_METHODS,re as ACP_PROTOCOL_VERSION,x as ACP_SESSION_UPDATE_TYPES,H as AGENT_RPC_APPROVAL_METHODS,d as AGENT_RPC_ERROR_CODES,Y as AGENT_RPC_PROTOCOL_VERSION,k as AGENT_TEAM_WS_EVENT_NAMES,M as AGENT_WS_EVENT_NAMES,te as ALL_AGENT_WS_EVENT_NAMES,E as CAPABILITY_MANIFEST_DIFF_SECTIONS,ee as GATEWAY_RPC_METHODS,R as GatewayRpcContract,Ce as MEMORY_OBSERVATION_HOOK_VALUES,he as MEMORY_OBSERVATION_SOURCE_VALUES,Ie as MEMORY_WRITE_ACCESS_VALUES,De as MUTATION_CHECKPOINT_BACKEND_VALUES,we as MUTATION_CHECKPOINT_ENTRY_KIND_VALUES,Ne as MUTATION_CHECKPOINT_PHASE_VALUES,q as PETDEX_ANIMATION_IDS,Le as PROVIDER_RUNTIME_AUTH_MODE_VALUES,Ke as PROVIDER_RUNTIME_COMPAT_FLAG_VALUES,T as PROVIDER_RUNTIME_ENV_API_KEY_CANDIDATES,j as PROVIDER_RUNTIME_OPENAI_CODEX_PROVIDER_ID,Ue as PROVIDER_RUNTIME_VAULT_ERROR_TYPE_VALUES,ve as RESOURCE_MANIFEST_SCHEMA_VERSION,a as RUNTIME_ASSET_IDS,y as RUNTIME_PROFILE_IDS,_e as WEB_ACTION_SCOPE_VALUES,Ee as WEB_APPROVAL_DEFAULT_VALUES,ye as WEB_CAPABILITY_FAMILY_VALUES,me as WEB_CAPABILITY_ID_VALUES,be as WEB_DEGRADATION_TARGET_VALUES,Te as WEB_ESCALATION_REASON_VALUES,Ae as WEB_EXECUTION_MODE_VALUES,Se as WEB_POLICY_RISK_CLASS_VALUES,Pe as WEB_RETRY_POLICY_VALUES,Re as WEB_STATEFULNESS_VALUES,fe as WEB_TASK_MODE_VALUES,Z as buildAgentRpcMeta,f as classifyGatewayRpcMethod,m as cloneCapabilityManifestSnapshot,ge as createCapabilityManifestDiffPayload,K as createDefaultRuntimeResourceProfiles,de as deriveCapabilityToolNamespaces,ue as deriveCapabilityWorkspaceIds,_ as getManifestShortcutEntry,W as getRuntimeResourceAsset,V as getRuntimeResourceProfile,ke as getRuntimeResourceProfileAssets,N as isAcpJsonRpcNotification,O as isAcpJsonRpcRequest,w as isAcpJsonRpcResponse,h as isAgentRpcNotification,P as isAgentRpcRequest,C as isAgentRpcResponse,Xe as isAnthropicProviderRuntimeFamily,pe as isExtendedSessionUpdateType,ze as isOpenAiProviderRuntimeFamily,ae as isStandardSessionUpdateType,Ze as listProviderRuntimeEnvApiKeyNames,le as mergeCapabilityManifestSnapshot,A as normalizeProviderRuntimeId,B as normalizeProviderRuntimeIdForAuth,Oe as normalizeRuntimeResourceManifest,se as parseAcpMessage,G as parseAgentRpcMessage,Be as preservesProviderRuntimeAnthropicThinkingSignatures,We as readProviderRuntimeCompatFlag,v as requireGatewayRpcMeta,I as requiresIdempotencyKey,qe as requiresOpenAiCompatibleAnthropicToolPayloadForProviderRuntime,l as resolveProviderRuntimeCapabilities,et as resolveProviderRuntimeEnvApiKey,Ve as resolveProviderRuntimeKeyFamily,$e as resolveProviderRuntimeTranscriptToolCallIdMode,Je as shouldDropThinkingBlocksForProviderRuntimeModel,Qe as shouldSanitizeProviderRuntimeThoughtSignaturesForModel,Ge as supportsOpenAiCompatTurnValidationForProviderRuntime,xe as upsertRuntimeResourceAsset,Ye as usesOpenAiFunctionAnthropicToolSchemaForProviderRuntime,He as usesOpenAiStringModeAnthropicToolChoiceForProviderRuntime};
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Turn-time QMemory recall orchestration (hippocampus bridge).
3
+ *
4
+ * Impure counterpart to the pure memory-recall-context.ts: it drives the
5
+ * `memory.before_recall` hook, caps the recalled set by a per-turn byte budget,
6
+ * and fires `memory.after_recall`. Kept out of Agent.run so the turn entrypoint
7
+ * stays a thin lifecycle wrapper; the pure prompt-building (and conflict
8
+ * detection) stays in memory-recall-context.ts.
9
+ *
10
+ * Returns the system-message content to inject (already prefixed), or null when
11
+ * there is nothing to inject. Recall failures are swallowed — a recall miss must
12
+ * never block the turn. The caller decides WHERE to splice the message; this
13
+ * module only decides WHAT (if anything) to inject.
14
+ */
15
+ import type { AgentLogger, HookRegistry } from "./types.js";
16
+ export interface RecallMemoriesDeps {
17
+ hooks: HookRegistry;
18
+ /** P6: maps the query to category recall preferences (runtime port). */
19
+ detectRecallCategories: (query: string) => {
20
+ preferred: string[];
21
+ deprioritized: string[];
22
+ };
23
+ log: AgentLogger;
24
+ sessionId: string;
25
+ turnId: string;
26
+ /** Last user message (already truncated by the caller). */
27
+ query: string;
28
+ }
29
+ /**
30
+ * Recall long-term memories for this turn and build the system-message content
31
+ * to inject. Always fires `memory.after_recall` (with the pre-cap count) when the
32
+ * recall hook runs. Returns null when there is nothing worth injecting.
33
+ */
34
+ export declare function recallMemoriesForTurn(deps: RecallMemoriesDeps): Promise<string | null>;
@@ -0,0 +1,22 @@
1
+ import type { AgentLogger, ThinkingBlock, TokenUsage, ToolLoopTransition } from "../types.js";
2
+ export interface BudgetContinuationPolicyInput {
3
+ tokenBudget: number | undefined;
4
+ totalUsage: TokenUsage;
5
+ budgetContinuationCount: number;
6
+ lastBudgetDeltaTokens: number;
7
+ lastBudgetGlobalTokens: number;
8
+ messages: unknown[];
9
+ finalText: string;
10
+ thinkingBlocks: readonly ThinkingBlock[];
11
+ getBudgetContinuationMessage(usagePct: number, totalUsed: number, tokenBudget?: number): string;
12
+ log: Pick<AgentLogger, "info">;
13
+ }
14
+ export interface BudgetContinuationPolicyDecision {
15
+ messages: unknown[];
16
+ budgetContinuationCount: number;
17
+ lastBudgetDeltaTokens: number;
18
+ lastBudgetGlobalTokens: number;
19
+ recoveryDetail: string;
20
+ transition: ToolLoopTransition;
21
+ }
22
+ export declare function resolveBudgetContinuationPolicy(input: BudgetContinuationPolicyInput): BudgetContinuationPolicyDecision | null;
@@ -0,0 +1,19 @@
1
+ import type { AgentLogger, ChatMessage, ThinkingBlock, ToolLoopTransition } from "../types.js";
2
+ export type CompletionActionPolicyReason = "file_action_verification" | "multi_file_skeleton_verification";
3
+ export interface CompletionActionPolicyInput {
4
+ inputMessages: readonly ChatMessage[];
5
+ messages: unknown[];
6
+ finalText: string;
7
+ thinkingBlocks: readonly ThinkingBlock[];
8
+ stopHookActive: boolean | undefined;
9
+ totalToolCallCount: number;
10
+ distinctToolNames: ReadonlySet<string>;
11
+ log: Pick<AgentLogger, "info">;
12
+ }
13
+ export interface CompletionActionPolicyDecision {
14
+ reason: CompletionActionPolicyReason;
15
+ messages: unknown[];
16
+ stopHookActive: true;
17
+ transition: ToolLoopTransition;
18
+ }
19
+ export declare function resolveCompletionActionPolicy(input: CompletionActionPolicyInput): CompletionActionPolicyDecision | null;
@@ -0,0 +1,19 @@
1
+ import type { AgentLogger, HookRegistry, ThinkingBlock, ToolLoopTransition } from "../types.js";
2
+ export type CompletionStopPolicyDecision = {
3
+ action: "end";
4
+ content: string;
5
+ } | {
6
+ action: "continue";
7
+ messages: unknown[];
8
+ stopHookActive: true;
9
+ transition: ToolLoopTransition;
10
+ };
11
+ export interface CompletionStopPolicyInput {
12
+ hooks: HookRegistry | undefined;
13
+ sessionId: string;
14
+ messages: unknown[];
15
+ finalText: string;
16
+ thinkingBlocks: readonly ThinkingBlock[];
17
+ log: Pick<AgentLogger, "info">;
18
+ }
19
+ export declare function resolveCompletionStopPolicy(input: CompletionStopPolicyInput): Promise<CompletionStopPolicyDecision | null>;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Context compression pipeline — extracted phase of the tool loop (CC query.ts parity).
3
+ *
4
+ * Pure-ish transform with a side-channel of `recovery` events: takes the round's
5
+ * messages and runs the staged compaction
6
+ * tool-result-budget → snip → microcompact → context-collapse → autocompact
7
+ * → whitespace filter, returning the messages to send to the LLM. Each stage runs
8
+ * before the next; an earlier stage that brings us under threshold makes later
9
+ * stages no-ops.
10
+ *
11
+ * Extracted from the main loop to cut its reading cost: this phase has no control-flow
12
+ * escape (never continues/returns the outer loop), so it is a clean `yield*` boundary.
13
+ * The only outward state mutation (resetting the reactive-compact guard after autocompact)
14
+ * is handed back through `onAutocompact` so the loop keeps ownership of its State.
15
+ */
16
+ import type { AgentLogger, HookRegistry, TurnEvent } from "../types.js";
17
+ import type { ToolLoopRuntimePorts } from "../../runtime/ports/index.js";
18
+ import { type CollapseStore, type TurnLoopGuardConfig, type TurnLoopGuardState } from "../../orchestration/index.js";
19
+ export interface CompressionPipelineDeps {
20
+ messages: unknown[];
21
+ contentReplacementState: unknown;
22
+ snipRemovedIds: Set<string>;
23
+ collapseStore: CollapseStore;
24
+ guardState: TurnLoopGuardState;
25
+ guardConfig: TurnLoopGuardConfig;
26
+ runtimePorts: ToolLoopRuntimePorts;
27
+ hooks: HookRegistry | undefined;
28
+ hookCtx: {
29
+ sessionId: string;
30
+ turnId: string;
31
+ };
32
+ sessionId: string;
33
+ currentModel: string;
34
+ log: AgentLogger;
35
+ /** Build + record a recovery event (centralized in the loop's recovery trace). */
36
+ recovery: (action: string, detail?: string) => TurnEvent;
37
+ /** Invoked when autocompact drops messages — caller resets its reactive-compact guard. */
38
+ onAutocompact: () => void;
39
+ }
40
+ /**
41
+ * Run the compression pipeline for one round. Yields `recovery` events for stages
42
+ * that actually fired; returns the (possibly compacted) messages to query with.
43
+ */
44
+ export declare function runCompressionPipeline(deps: CompressionPipelineDeps): AsyncGenerator<TurnEvent, unknown[]>;
@@ -0,0 +1,7 @@
1
+ import { buildSkillInstruction } from "../../orchestration/index.js";
2
+ export interface SkillInstructionPolicyInput {
3
+ totalToolCallCount: number;
4
+ distinctToolNames: ReadonlySet<string>;
5
+ projectRoot?: string;
6
+ }
7
+ export declare function resolveToolUsageSkillInstruction(input: SkillInstructionPolicyInput): ReturnType<typeof buildSkillInstruction>;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Stream-error recovery — extracted phase of the tool loop (CC withRetry.ts parity).
3
+ *
4
+ * Handles an error thrown while streaming the LLM round. This is the loop's densest,
5
+ * most regression-prone branch, so it is pulled out behind a small control-flow
6
+ * protocol: the generator yields any user-facing events (recovery / error / heartbeat)
7
+ * and RETURNS a decision the loop acts on, instead of `continue`/`return`-ing the outer
8
+ * loop itself (which a sub-generator cannot do):
9
+ *
10
+ * - { kind: "continue", patch } → loop applies `state = { ...state, ...patch }` and retries
11
+ * - { kind: "return" } → loop returns (a terminal error event was already yielded)
12
+ * - { kind: "streamError", … } → loop sets streamError and falls through to error withholding
13
+ *
14
+ * Behavior is byte-for-byte the same as the former inline catch block, including the
15
+ * in-place `consecutive529Errors` increment (so the count persists onto the loop's State
16
+ * whether we continue or fall through). Covered by tool-loop.states.test.ts:
17
+ * fallback / stale-connection / max-tokens-overflow / 429-retry.
18
+ */
19
+ import type { AgentLogger, TokenUsage, ToolLoopTransition, TurnEvent } from "../types.js";
20
+ /** Subset of the loop's State this phase reads / mutates in place. */
21
+ export interface StreamErrorState {
22
+ consecutive529Errors: number;
23
+ consecutiveApiRetries: number;
24
+ currentModel: string;
25
+ totalUsage: TokenUsage;
26
+ }
27
+ /** Fields the loop should merge into State before continuing. */
28
+ export interface StreamErrorPatch {
29
+ currentModel?: string;
30
+ consecutive529Errors?: number;
31
+ consecutiveApiRetries?: number;
32
+ maxOutputTokensOverride?: number;
33
+ transition?: ToolLoopTransition | undefined;
34
+ }
35
+ export type StreamErrorDecision = {
36
+ kind: "continue";
37
+ patch: StreamErrorPatch;
38
+ } | {
39
+ kind: "return";
40
+ } | {
41
+ kind: "streamError";
42
+ streamError: {
43
+ status?: number;
44
+ message: string;
45
+ };
46
+ };
47
+ export interface StreamErrorCtx {
48
+ state: StreamErrorState;
49
+ guardState: {
50
+ currentMaxOutputTokens: number;
51
+ };
52
+ fallbackModel: string | undefined;
53
+ signal: AbortSignal | undefined;
54
+ querySource: string | undefined;
55
+ turnId: string;
56
+ log: AgentLogger;
57
+ emitRecovery: (action: string, detail?: string) => TurnEvent;
58
+ }
59
+ export declare function handleStreamError(err: unknown, ctx: StreamErrorCtx): AsyncGenerator<TurnEvent, StreamErrorDecision>;
@@ -0,0 +1,22 @@
1
+ import type { ChatMessage } from "../types.js";
2
+ import type { OpenAiToolCall } from "../../orchestration/index.js";
3
+ export interface VariantBlockedToolCall {
4
+ call: OpenAiToolCall;
5
+ failCount: number;
6
+ error: string;
7
+ }
8
+ export declare function splitVariantToolCalls(calls: readonly OpenAiToolCall[], toolFailureCounts: ReadonlyMap<string, number>): {
9
+ allowed: OpenAiToolCall[];
10
+ blocked: VariantBlockedToolCall[];
11
+ };
12
+ export declare function variantBlockNudge(): ChatMessage;
13
+ export declare function recordToolFailureResult(input: {
14
+ toolFailureCounts: Map<string, number>;
15
+ toolName: string;
16
+ ok: boolean;
17
+ softEmpty: boolean;
18
+ }): void;
19
+ export declare function newVariantFailureNudges(input: {
20
+ toolFailureCounts: ReadonlyMap<string, number>;
21
+ snapshot: ReadonlyMap<string, number>;
22
+ }): ChatMessage[];
@@ -104,8 +104,6 @@ export interface TurnConfig {
104
104
  modelMaxOutputTokens?: number;
105
105
  /** Tool choice strategy: "auto" (default), "none", "required" */
106
106
  toolChoice?: "auto" | "none" | "required";
107
- /** Declarative assistant preset id. Does not change model, tools, or permissions. */
108
- assistantId?: string;
109
107
  /** Parent fork depth (0 = top-level, default 0). CC: depth tracking for fork recursion limit. */
110
108
  parentDepth?: number;
111
109
  /** Per-turn token budget (prompt + completion). 0 or undefined = unlimited. */
@@ -174,6 +172,8 @@ export type TurnEvent = {
174
172
  usage?: TokenUsage;
175
173
  model?: string;
176
174
  provider?: string;
175
+ /** Per-turn recovery trace (action -> count); present only when recoveries fired. */
176
+ recoveryTrace?: Record<string, number>;
177
177
  } | {
178
178
  type: "error";
179
179
  turnId: string;
@@ -0,0 +1,8 @@
1
+ export type IncomingRoute = "acp" | "legacy" | "ignore";
2
+ /**
3
+ * Classify a parsed inbound frame.
4
+ * - "acp" → hand to the ACP server (only when ACP is active)
5
+ * - "legacy" → hand to the native gateway handler (a valid AgentRpcRequest)
6
+ * - "ignore" → neither; drop with a warning
7
+ */
8
+ export declare function classifyIncomingMessage(parsed: unknown, acpActive: boolean): IncomingRoute;