qlogicagent 2.18.2 → 2.18.4

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 (91) hide show
  1. package/dist/agent.js +38 -24
  2. package/dist/cli.js +1 -1
  3. package/dist/index.js +553 -485
  4. package/dist/orchestration.js +11 -11
  5. package/dist/protocol.js +1 -1
  6. package/dist/skills/mcp/astraclaw-native-mcp-server.js +8 -6
  7. package/dist/types/agent/memory-recall-injection.d.ts +2 -1
  8. package/dist/types/agent/tool-loop/budget-continuation-policy.d.ts +4 -0
  9. package/dist/types/agent/tool-loop/completion-action-policy.d.ts +9 -1
  10. package/dist/types/cli/credential-vault.d.ts +6 -0
  11. package/dist/types/cli/handlers/community-handler.d.ts +1 -2
  12. package/dist/types/cli/handlers/memory-handler.d.ts +7 -0
  13. package/dist/types/cli/handlers/turn-handler.d.ts +50 -1
  14. package/dist/types/cli/memory-coordinator.d.ts +4 -0
  15. package/dist/types/cli/pet-runtime.d.ts +2 -0
  16. package/dist/types/cli/rpc-registry.d.ts +11 -0
  17. package/dist/types/cli/runtime-hook-bootstrap.d.ts +2 -0
  18. package/dist/types/cli/skill-tools-bootstrap.d.ts +5 -0
  19. package/dist/types/cli/stdio-acp-request-host.d.ts +2 -1
  20. package/dist/types/cli/stdio-rpc-handler-hosts.d.ts +1 -0
  21. package/dist/types/cli/stdio-server.d.ts +4 -0
  22. package/dist/types/cli/task-distillation-coordinator.d.ts +79 -0
  23. package/dist/types/cli/tool-bootstrap-core-registration.d.ts +24 -0
  24. package/dist/types/cli/turn-core.d.ts +0 -6
  25. package/dist/types/cli/turn-project-router.d.ts +9 -0
  26. package/dist/types/contracts/hooks.d.ts +3 -0
  27. package/dist/types/contracts/turn-event.d.ts +8 -4
  28. package/dist/types/orchestration/agent-instance.d.ts +4 -0
  29. package/dist/types/orchestration/context/reactive-compact.d.ts +4 -6
  30. package/dist/types/orchestration/error-handling/retry-loop.d.ts +0 -22
  31. package/dist/types/orchestration/goal-loop-coordinator.d.ts +6 -0
  32. package/dist/types/orchestration/goal-mode-adapters.d.ts +20 -1
  33. package/dist/types/orchestration/goal-run-types.d.ts +10 -0
  34. package/dist/types/orchestration/skill-improvement.d.ts +7 -2
  35. package/dist/types/orchestration/workflow/run-history-store.d.ts +2 -0
  36. package/dist/types/orchestration/workflow/workflow-runtime.d.ts +8 -0
  37. package/dist/types/protocol/methods.d.ts +0 -26
  38. package/dist/types/protocol/wire/acp-agent-management.d.ts +3 -0
  39. package/dist/types/protocol/wire/agent-events.d.ts +2 -2
  40. package/dist/types/protocol/wire/agent-methods.d.ts +0 -11
  41. package/dist/types/protocol/wire/gateway-rpc.d.ts +1 -0
  42. package/dist/types/protocol/wire/memory-provider-lifecycle.d.ts +3 -0
  43. package/dist/types/protocol/wire/notification-payloads.d.ts +27 -0
  44. package/dist/types/runtime/community/community-consent-client.d.ts +0 -21
  45. package/dist/types/runtime/config/tunable-defaults.d.ts +6 -0
  46. package/dist/types/runtime/execution/memory-decay.d.ts +5 -1
  47. package/dist/types/runtime/hooks/context-compression.d.ts +5 -0
  48. package/dist/types/runtime/hooks/memory-hooks.d.ts +16 -0
  49. package/dist/types/runtime/infra/acp-detector.d.ts +8 -0
  50. package/dist/types/runtime/infra/acp-protocol-adapter.d.ts +10 -0
  51. package/dist/types/runtime/infra/agent-paths.d.ts +9 -7
  52. package/dist/types/runtime/infra/agent-process.d.ts +6 -0
  53. package/dist/types/runtime/infra/astraclaw-capabilities.d.ts +9 -6
  54. package/dist/types/runtime/infra/checkpoint-backend.d.ts +1 -1
  55. package/dist/types/runtime/infra/migrate-device-scope.d.ts +49 -0
  56. package/dist/types/runtime/infra/project-data-paths.d.ts +4 -3
  57. package/dist/types/runtime/infra/project-skill-manifest.d.ts +3 -2
  58. package/dist/types/runtime/infra/working-materials-store.d.ts +8 -14
  59. package/dist/types/runtime/pet/pet-profile-service.d.ts +7 -0
  60. package/dist/types/runtime/pet/petdex-forge-service.d.ts +3 -1
  61. package/dist/types/runtime/ports/memory-provider.d.ts +23 -0
  62. package/dist/types/runtime/ports/project-memory-store.d.ts +2 -0
  63. package/dist/types/runtime/prompt/environment-context.d.ts +15 -3
  64. package/dist/types/runtime/prompt/fresh-workspace-evidence.d.ts +7 -0
  65. package/dist/types/runtime/prompt/instruction-loader.d.ts +0 -1
  66. package/dist/types/runtime/session/inbound-upload-persistence.d.ts +4 -0
  67. package/dist/types/runtime/session/session-catalog.d.ts +8 -0
  68. package/dist/types/runtime/session/session-resume.d.ts +5 -0
  69. package/dist/types/runtime/session/session-transcript-store.d.ts +8 -1
  70. package/dist/types/skills/mcp/mcp-manager.d.ts +25 -1
  71. package/dist/types/skills/memory/fts-segment.d.ts +20 -0
  72. package/dist/types/skills/memory/local-memory-provider.d.ts +66 -4
  73. package/dist/types/skills/memory/local-store-records.d.ts +6 -1
  74. package/dist/types/skills/memory/local-store.d.ts +63 -10
  75. package/dist/types/skills/memory/memdir.d.ts +17 -4
  76. package/dist/types/skills/memory/memory-consolidation.d.ts +7 -0
  77. package/dist/types/skills/memory/proposal-consumer.d.ts +51 -0
  78. package/dist/types/skills/memory/sqlite-memory-mappers.d.ts +2 -1
  79. package/dist/types/skills/memory/sqlite-memory-schema.d.ts +9 -1
  80. package/dist/types/skills/memory/task-distillation.d.ts +148 -0
  81. package/dist/types/skills/tools/search-tool.d.ts +6 -0
  82. package/dist/types/skills/tools/shell/task-output.d.ts +2 -0
  83. package/package.json +3 -2
  84. package/dist/types/agent/tool-loop/skill-instruction-policy.d.ts +0 -7
  85. package/dist/types/agent/tool-loop/tool-guardrails.d.ts +0 -24
  86. package/dist/types/cli/tool-bootstrap-community-registration.d.ts +0 -9
  87. package/dist/types/cli/turn-skill-autopersist.d.ts +0 -22
  88. package/dist/types/runtime/community/community-discovery-cache.d.ts +0 -24
  89. package/dist/types/runtime/community/community-discovery-coordinator.d.ts +0 -33
  90. package/dist/types/runtime/hooks/community-discovery-hook.d.ts +0 -18
  91. package/dist/types/skills/tools/community-seek-tool.d.ts +0 -49
@@ -1,29 +1,29 @@
1
- function Re(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function xe(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 Se=/\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]},ke=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Ae=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Me=512,Ee=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Ie=new Set([500,502,503,504,521,522,523,524,529]),ve=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],we=["upgrade your plan","upgrade plan","current plan","subscription"],Oe=["daily","weekly","monthly"],Le=["try again","retry","temporary","cooldown"],Pe=["usage limit","rate limit","organization usage"],Ne=["organization","workspace"],Fe=["billing period","exceeded","reached","exhausted"],De=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,Be=/^(?: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 Ue(e){return h(e,T.format)}function X(e){return h(e,T.rateLimit)}function Ge(e){return h(e,T.timeout)}function je(e){return Se.test(e)}function E(e){let t=e.toLowerCase();return t?e.length>Me?Ae.test(t):h(t,T.billing)?!0:ke.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function K(e){return h(e,T.authPermanent)}function $e(e){return h(e,T.auth)}function W(e){return h(e,T.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function He(e){return y(e,ve)||y(e,we)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function ze(e){let t=y(e,Oe),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,Ne);return y(e,Le)&&y(e,Pe)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,Fe))}function qe(e){return e.trim().toLowerCase().replace(Be,"").trim()}function V(e){let t=qe(e);return!t||He(t)?"billing":X(t)||ze(t)?"rate_limit":"billing"}function Ye(e){return De.test(e)?V(e):null}function J(e){let t=e.match(Ee);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Xe(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Ke(e){let t=e.trim();if(!t)return!1;let n=J(t);return n?Ie.has(n.code):!1}function Z(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?V(t):"billing":e===429?"rate_limit":e===401||e===403?t&&K(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&W(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&E(t)?"billing":"format":null}function We(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function Ve(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 Q(e){if(Ve(e))return"session_expired";if(We(e))return"model_not_found";let t=Ye(e);return t||(je(e)?E(e)?"billing":"rate_limit":X(e)?"rate_limit":W(e)?"overloaded":Ke(e)?J(e.trim())?.code===529?"overloaded":"timeout":Xe(e)?"timeout":Ue(e)?"format":E(e)?"billing":Ge(e)?"timeout":K(e)?"auth_permanent":$e(e)?"auth":null)}var Je={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"},Ze=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function Qe(e,t){let n=Z(e,t)??(t?Q(t):null);return n?Je[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function et(e){return Ze.has(e)}function B(e){return typeof e.compressAsync=="function"}var ee=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 s=n;for(let c of o)s-=this.estimateTokens(c);let i;for(let c of r)if(c.role==="user"){i=c;break}if(i&&(s-=this.estimateTokens(i)),s<=0)return{messages:i?[...o,i]:o,droppedCount:r.length-(i?1:0),strategy:"sliding-window"};let a=[],l=0;for(let c=r.length-1;c>=0;c--){let d=r[c];if(d===i)continue;let p=this.estimateTokens(d);if(s-p<0&&l>=ee)break;if(s-p<0&&l<ee){a.unshift(d),l++;continue}s-=p,a.unshift(d),l++}let u=[...o];return i&&!a.includes(i)&&u.push(i),u.push(...a),{messages:u,droppedCount:r.length-(a.length+(i&&!a.includes(i)?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 s=r.slice(0,r.length-this.recentCount),i=r.slice(r.length-this.recentCount),a=this.summarize(s);return{messages:[...o,{role:"system",content:`[Conversation summary]
2
- ${a}`},...i],droppedCount:s.length,strategy:"summarize-old"}}},w=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(s=>s.role!=="tool"||typeof s.content!="string"||s.content.length<=this.maxToolResultChars?s:(o++,{...s,content:tt(s.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function tt(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let s=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
1
+ function Se(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function xe(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 ke=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,T={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Ae=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Ee=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Me=512,ve=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Ie=new Set([500,502,503,504,521,522,523,524,529]),we=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Oe=["upgrade your plan","upgrade plan","current plan","subscription"],Le=["daily","weekly","monthly"],Pe=["try again","retry","temporary","cooldown"],Ne=["usage limit","rate limit","organization usage"],De=["organization","workspace"],Fe=["billing period","exceeded","reached","exhausted"],Be=/["']?(?: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,Ue=/^(?: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 Ge(e){return h(e,T.format)}function X(e){return h(e,T.rateLimit)}function je(e){return h(e,T.timeout)}function $e(e){return ke.test(e)}function M(e){let t=e.toLowerCase();return t?e.length>Me?Ee.test(t):h(t,T.billing)?!0:Ae.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function K(e){return h(e,T.authPermanent)}function He(e){return h(e,T.auth)}function W(e){return h(e,T.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function ze(e){return y(e,we)||y(e,Oe)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function qe(e){let t=y(e,Le),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,De);return y(e,Pe)&&y(e,Ne)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,Fe))}function Ye(e){return e.trim().toLowerCase().replace(Ue,"").trim()}function V(e){let t=Ye(e);return!t||ze(t)?"billing":X(t)||qe(t)?"rate_limit":"billing"}function Xe(e){return Be.test(e)?V(e):null}function J(e){let t=e.match(ve);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Ke(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function We(e){let t=e.trim();if(!t)return!1;let n=J(t);return n?Ie.has(n.code):!1}function Z(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?V(t):"billing":e===429?"rate_limit":e===401||e===403?t&&K(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&W(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&M(t)?"billing":"format":null}function Ve(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 Je(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 Q(e){if(Je(e))return"session_expired";if(Ve(e))return"model_not_found";let t=Xe(e);return t||($e(e)?M(e)?"billing":"rate_limit":X(e)?"rate_limit":W(e)?"overloaded":We(e)?J(e.trim())?.code===529?"overloaded":"timeout":Ke(e)?"timeout":Ge(e)?"format":M(e)?"billing":je(e)?"timeout":K(e)?"auth_permanent":He(e)?"auth":null)}var Ze={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"},Qe=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function et(e,t){let n=Z(e,t)??(t?Q(t):null);return n?Ze[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function tt(e){return Qe.has(e)}function B(e){return typeof e.compressAsync=="function"}var ee=4;function te(e){return{role:"system",content:`[${e} earlier messages removed to fit the context budget]`}}var v=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let p of t)p.role==="system"?o.push(p):r.push(p);let s=n;for(let p of o)s-=this.estimateTokens(p);let i;for(let p of r)if(p.role==="user"){i=p;break}if(i&&(s-=this.estimateTokens(i)),s<=0){let p=r.length-(i?1:0),d=i?[...o,i]:[...o];return p>0&&d.push(te(p)),{messages:d,droppedCount:p,strategy:"sliding-window"}}let a=[],l=0;for(let p=r.length-1;p>=0;p--){let d=r[p];if(d===i)continue;let m=this.estimateTokens(d);if(s-m<0&&l>=ee)break;if(s-m<0&&l<ee){a.unshift(d),l++;continue}s-=m,a.unshift(d),l++}let c=r.length-(a.length+(i&&!a.includes(i)?1:0)),u=[...o];return i&&!a.includes(i)&&u.push(i),c>0&&u.push(te(c)),u.push(...a),{messages:u,droppedCount:c,strategy:"sliding-window"}}},I=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 s=r.slice(0,r.length-this.recentCount),i=r.slice(r.length-this.recentCount),a=this.summarize(s);return{messages:[...o,{role:"system",content:`[Conversation summary]
2
+ ${a}`},...i],droppedCount:s.length,strategy:"summarize-old"}}},w=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(s=>s.role!=="tool"||typeof s.content!="string"||s.content.length<=this.maxToolResultChars?s:(o++,{...s,content:nt(s.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function nt(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let s=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
3
3
  `),n.lastIndexOf(`]
4
4
  `));if(s>t*.5)return n.slice(0,s+1)+`
5
5
  [...truncated: ${e.length-s-1} chars omitted]`}let r=n.lastIndexOf(`
6
6
  `);return r>t*.7?n.slice(0,r)+`
7
7
  [...truncated: ${e.length-r} chars omitted]`:n+`
8
- [...truncated: ${e.length-t} chars omitted]`}function nt(...e){return{compress(t,n){let o=t,r=0,s=[];for(let i of e){let a=i.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}}}}function ot(...e){return{compress(t,n){let o=t,r=0,s=[];for(let i of e){let a=i.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}},async compressAsync(t,n){let o=t,r=0,s=[],i=0,a=!1,l=!1;for(let u of e){let c=B(u)?await u.compressAsync(o,n):u.compress(o,n);o=c.messages,r+=c.droppedCount,c.droppedCount>0&&s.push(c.strategy),c.metrics&&(i+=c.metrics.latencyMs,a=a||c.metrics.usedLlm,l=l||!!c.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none",metrics:i>0||a?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:i,usedLlm:a,cacheInvalidated:l}:void 0}}}}function U(e,t){let n=e.filter(i=>i.role==="user"),o=e.filter(i=>i.tool_calls!=null),r=e.filter(i=>i.role==="tool"),s=["You are a conversation summarizer. Produce a structured summary of the conversation history below.","","## Instructions","Analyze the conversation and produce a summary with these sections:","","### 1. Primary Objective","What is the user's main goal or task? State it in one sentence.","","### 2. Key Decisions Made","List the important decisions, choices, or conclusions reached during the conversation.","","### 3. Current Progress",`Describe the current state. ${o.length>0?`${o.length} tool calls and ${r.length} tool results were exchanged.`:"No tools were used."}`,"","### 4. Pending Tasks","List any tasks that are in-progress or planned but not yet completed.","","### 5. Important Context","MUST preserve verbatim: IP addresses, file paths, URLs, port numbers, credentials/tokens, specific numeric values, version numbers, proper nouns, identifiers, and any user-provided data points. These MUST appear exactly as stated in the original conversation.","","### 6. All User Messages",`List ALL ${n.length} user messages chronologically, each as 1-2 sentences capturing the core request. Include exact values, identifiers, keywords, or secrets the user mentioned or asked you to remember. Do NOT omit any user message \u2014 every user request must be traceable in this summary.`,"","### 7. Error & Recovery History","Summarize any errors encountered and how they were resolved.","","### 8. User Preferences Expressed","Note any stated preferences about style, approach, or constraints.","","### 9. Technical State","Note file paths, variable names, API endpoints, or configuration values that were discussed.","","### 10. Conversation Flow","Briefly describe the overall flow: what happened first, what changed, where we are now."];return t?.taskContext&&s.push("","## Additional Context",t.taskContext),s.push("","## Conversation to Summarize","",...e.map(i=>{let a=typeof i.content=="string"?i.content:JSON.stringify(i.content??""),l=i.role==="user"?a:a.length>2e3?a.slice(0,2e3)+"...":a;return`[${i.role}]: ${l}`}),"","## Output Format","Respond with a concise summary covering all 10 sections above. Use markdown headers.","Keep the total summary under 1000 words. Focus on actionable information and exact user requests."),s.join(`
9
- `)}var O=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??x,taskContext:t.taskContext}}compress(t,n){return{messages:t,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:s}=ne(t),i=t.reduce((m,g)=>m+this.config.estimateTokens(g),0);if(i<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let a=0,l=0;for(let m=0;m<s.length&&(s[m].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));m++)a=m+1;let u=Math.max(this.config.protectedTailMessages,Math.floor(s.length*.4)),c=Math.max(a,s.length-u);if(c<=a)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let d=s.slice(0,a),p=s.slice(a,c),f=s.slice(c),C=U(p,{taskContext:this.config.taskContext}),k=await this.config.summarize(p,C),A={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
8
+ [...truncated: ${e.length-t} chars omitted]`}function ot(...e){return{compress(t,n){let o=t,r=0,s=[];for(let i of e){let a=i.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}}}}function rt(...e){return{compress(t,n){let o=t,r=0,s=[];for(let i of e){let a=i.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}},async compressAsync(t,n){let o=t,r=0,s=[],i=0,a=!1,l=!1;for(let c of e){let u=B(c)?await c.compressAsync(o,n):c.compress(o,n);o=u.messages,r+=u.droppedCount,u.droppedCount>0&&s.push(u.strategy),u.metrics&&(i+=u.metrics.latencyMs,a=a||u.metrics.usedLlm,l=l||!!u.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none",metrics:i>0||a?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:i,usedLlm:a,cacheInvalidated:l}:void 0}}}}function U(e,t){let n=e.filter(i=>i.role==="user"),o=e.filter(i=>i.tool_calls!=null),r=e.filter(i=>i.role==="tool"),s=["You are a conversation summarizer. Produce a structured summary of the conversation history below.","","## Instructions","Analyze the conversation and produce a summary with these sections:","","### 1. Primary Objective","What is the user's main goal or task? State it in one sentence.","","### 2. Key Decisions Made","List the important decisions, choices, or conclusions reached during the conversation.","","### 3. Current Progress",`Describe the current state. ${o.length>0?`${o.length} tool calls and ${r.length} tool results were exchanged.`:"No tools were used."}`,"","### 4. Pending Tasks","List any tasks that are in-progress or planned but not yet completed.","","### 5. Important Context","MUST preserve verbatim: IP addresses, file paths, URLs, port numbers, credentials/tokens, specific numeric values, version numbers, proper nouns, identifiers, and any user-provided data points. These MUST appear exactly as stated in the original conversation.","","### 6. All User Messages",`List ALL ${n.length} user messages chronologically, each as 1-2 sentences capturing the core request. Include exact values, identifiers, keywords, or secrets the user mentioned or asked you to remember. Do NOT omit any user message \u2014 every user request must be traceable in this summary.`,"","### 7. Error & Recovery History","Summarize any errors encountered and how they were resolved.","","### 8. User Preferences Expressed","Note any stated preferences about style, approach, or constraints.","","### 9. Technical State","Note file paths, variable names, API endpoints, or configuration values that were discussed.","","### 10. Conversation Flow","Briefly describe the overall flow: what happened first, what changed, where we are now."];return t?.taskContext&&s.push("","## Additional Context",t.taskContext),s.push("","## Conversation to Summarize","",...e.map(i=>{let a=typeof i.content=="string"?i.content:JSON.stringify(i.content??""),l=i.role==="user"?a:a.length>2e3?a.slice(0,2e3)+"...":a;return`[${i.role}]: ${l}`}),"","## Output Format","Respond with a concise summary covering all 10 sections above. Use markdown headers.","Keep the total summary under 1000 words. Focus on actionable information and exact user requests."),s.join(`
9
+ `)}var O=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??S,taskContext:t.taskContext}}compress(t,n){return{messages:t,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:s}=oe(t),i=t.reduce((f,g)=>f+this.config.estimateTokens(g),0);if(i<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let a=0,l=0;for(let f=0;f<s.length&&(s[f].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));f++)a=f+1;let c=Math.max(this.config.protectedTailMessages,Math.floor(s.length*.4)),u=Math.max(a,s.length-c);if(u<=a)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let p=s.slice(0,a),d=s.slice(a,u),m=s.slice(u),C=U(d,{taskContext:this.config.taskContext}),k=await this.config.summarize(d,C),A={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
10
10
 
11
- ${k}`},_=[...r,...d,A,...f],M=Date.now()-o,b=_.reduce((m,g)=>m+this.config.estimateTokens(g),0);return{messages:_,droppedCount:p.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:b,compressionRatio:i>0?b/i:1,latencyMs:M,usedLlm:!0,cacheInvalidated:!0}}}},L=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??x}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:s}=ne(t),i=r.findIndex(m=>typeof m.content=="string"&&m.content.startsWith("[Conversation summary")),a=i>=0?r[i]:void 0,l=i>=0?[...r.slice(0,i),...r.slice(i+1)]:r,u=Math.max(0,s.length-this.config.preserveRecentCount);if(u<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let c=t.reduce((m,g)=>m+this.config.estimateTokens(g),0);if(c<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=s.slice(0,u),p=s.slice(u),f=a&&typeof a.content=="string"?`Previous summary:
11
+ ${k}`},_=[...r,...p,A,...m],E=Date.now()-o,b=_.reduce((f,g)=>f+this.config.estimateTokens(g),0);return{messages:_,droppedCount:d.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:b,compressionRatio:i>0?b/i:1,latencyMs:E,usedLlm:!0,cacheInvalidated:!0}}}},L=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??S}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:s}=oe(t),i=r.findIndex(f=>typeof f.content=="string"&&f.content.startsWith("[Conversation summary")),a=i>=0?r[i]:void 0,l=i>=0?[...r.slice(0,i),...r.slice(i+1)]:r,c=Math.max(0,s.length-this.config.preserveRecentCount);if(c<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let u=t.reduce((f,g)=>f+this.config.estimateTokens(g),0);if(u<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let p=s.slice(0,c),d=s.slice(c),m=a&&typeof a.content=="string"?`Previous summary:
12
12
  ${a.content}
13
13
 
14
- New messages to integrate:`:void 0,C=U(d,{taskContext:f}),k=await this.config.summarize(d,C),A={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
14
+ New messages to integrate:`:void 0,C=U(p,{taskContext:m}),k=await this.config.summarize(p,C),A={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
15
15
 
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),s=R(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}async compressAsync(t,n){let o=R(t),r=B(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),s=R(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}},te={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function rt(e={}){let t={...te,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function st(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,s=0,i=0;for(let a of this.events)n+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,o+=a.latencyMs,r+=Math.max(0,a.tokensBefore-a.tokensAfter),a.usedLlm&&s++,a.cacheInvalidated&&i++;return{totalCompressions:t,totalLlmCalls:s,totalCacheInvalidations:i,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},F=class{engines=new Map;activeId;register(t){this.engines.set(t.id,t)}activate(t){return this.engines.has(t)?(this.activeId=t,!0):!1}getActive(){return this.activeId?this.engines.get(this.activeId):void 0}listEngines(){return Array.from(this.engines.values()).map(t=>({id:t.id,label:t.label,active:t.id===this.activeId}))}};function ne(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function x(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function R(e){let t=Math.min(e.length,5),n=[];for(let o=0;o<t;o++){let r=e[o],s=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${s}`)}return n.join("|")}var it=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"]),D=class{constructor(t=20,n=x){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=new Map;for(let l of t){let u=l.tool_calls;if(Array.isArray(u))for(let c of u)c?.id&&c.function?.name&&o.set(c.id,c.function.name)}let r=t.length-this.preserveRecentCount,s=0,i=0;return{messages:t.map((l,u)=>{if(u>=r||l.role!=="tool"||typeof l.content!="string")return l;let c=l.name??o.get(l.tool_call_id??"");if(!c||!it.has(c)||l.content.length<=200)return l;let d=this.estimateTokens(l);return i+=d,s++,{...l,content:`[result cleared \u2014 ${l.content.length} chars]`}}),droppedCount:s,strategy:"micro-compact",metrics:s>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function at(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 s=r.function?.name??"";if(/read|edit|write|file/i.test(s)&&r.function?.arguments)try{let i=JSON.parse(r.function.arguments),a=i.path??i.filePath??i.file_path??i.file;a&&typeof a=="string"&&t.set(a,n)}catch{}}o.role==="tool"&&o.name&&/read|edit|write|file/i.test(o.name)}return[...t.entries()].sort((n,o)=>o[1]-n[1]).map(([n])=>n)}async function lt(e,t,n){let o=n.estimateTokens??(p=>Math.ceil(p.length/4)),r=at(t);if(r.length===0)return e;let s=e.map(p=>typeof p.content=="string"?p.content:"").join(`
17
- `),i=r.filter(p=>!s.includes(p));if(i.length===0)return e;let a=n.maxTokenBudget,l=[],u=0;for(let p of i){if(u>=n.maxFiles||a<=0)break;let f=await n.readFile(p);if(!f)continue;let C=o(f);C>a||(a-=C,u++,l.push({role:"system",content:`[Post-compact file recovery: ${p}]
16
+ ${k}`},_=[...l,A,...d],E=Date.now()-o,b=_.reduce((f,g)=>f+this.config.estimateTokens(g),0);return{messages:_,droppedCount:p.length,strategy:"incremental-compact",metrics:{tokensBefore:u,tokensAfter:b,compressionRatio:u>0?b/u:1,latencyMs:E,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),s=R(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}async compressAsync(t,n){let o=R(t),r=B(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),s=R(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}},ne={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function st(e={}){let t={...ne,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function it(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,s=0,i=0;for(let a of this.events)n+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,o+=a.latencyMs,r+=Math.max(0,a.tokensBefore-a.tokensAfter),a.usedLlm&&s++,a.cacheInvalidated&&i++;return{totalCompressions:t,totalLlmCalls:s,totalCacheInvalidations:i,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 oe(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],s=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${s}`)}return n.join("|")}var at=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=new Map;for(let l of t){let c=l.tool_calls;if(Array.isArray(c))for(let u of c)u?.id&&u.function?.name&&o.set(u.id,u.function.name)}let r=t.length-this.preserveRecentCount,s=0,i=0;return{messages:t.map((l,c)=>{if(c>=r||l.role!=="tool"||typeof l.content!="string")return l;let u=l.name??o.get(l.tool_call_id??"");if(!u||!at.has(u)||l.content.length<=200)return l;let p=this.estimateTokens(l);return i+=p,s++,{...l,content:`[result cleared \u2014 ${l.content.length} chars]`}}),droppedCount:s,strategy:"micro-compact",metrics:s>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function lt(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 s=r.function?.name??"";if(/read|edit|write|file/i.test(s)&&r.function?.arguments)try{let i=JSON.parse(r.function.arguments),a=i.path??i.filePath??i.file_path??i.file;a&&typeof a=="string"&&t.set(a,n)}catch{}}o.role==="tool"&&o.name&&/read|edit|write|file/i.test(o.name)}return[...t.entries()].sort((n,o)=>o[1]-n[1]).map(([n])=>n)}async function ct(e,t,n){let o=n.estimateTokens??(d=>Math.ceil(d.length/4)),r=lt(t);if(r.length===0)return e;let s=e.map(d=>typeof d.content=="string"?d.content:"").join(`
17
+ `),i=r.filter(d=>!s.includes(d));if(i.length===0)return e;let a=n.maxTokenBudget,l=[],c=0;for(let d of i){if(c>=n.maxFiles||a<=0)break;let m=await n.readFile(d);if(!m)continue;let C=o(m);C>a||(a-=C,c++,l.push({role:"system",content:`[Post-compact file recovery: ${d}]
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 ct(e,t,n=x){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of e){let l=a.tool_call_id??"";if(l&&t.has(l)){o+=n(a),r++,t.delete(l);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}function ut(){return{stages:[]}}function pt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=oe(e,t),i=mt(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=oe(e,t),{messages:s,stagedCount:i.length}}function dt(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:re(e,t),committed:n}}function oe(e,t){return t.stages.filter(o=>o.committed).length===0?e:re(e,t)}function re(e,t){let n=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),o=[...e];for(let r of n){let[s,i]=r.range;if(s>=o.length)continue;let a=Math.min(i,o.length),l={role:"system",content:r.summary};o.splice(s,a-s,l)}return o}function mt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,a=0;for(let l=0;l<o;l++){let u=e[l];if(u.role==="tool"||u.role==="assistant"&&typeof u.content=="string"&&u.content==="")i<0&&(i=l),a++;else{if(a>=3){let d=`${i}-${i+a}`;s.has(d)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let l=`${i}-${i+a}`;s.has(l)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{readFileSync as ft,writeFileSync as gt,mkdirSync as yt}from"node:fs";import{join as Tt,dirname as ht}from"node:path";var Ln=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Pn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var se=3,ie=2,ae=300*1e3,le=3,ce=720*60*60*1e3,G=4;var Nn=3600*1e3;var Fn=50*1024,Dn=500*1024,Bn=500*1024*1024,Un=50*1024*1024;var Gn=60*1024;var pe=0;var Ct="skill-patterns.json";function de(e){return Tt(e,".qlogicagent",Ct)}function me(e){let t=de(e);try{return JSON.parse(ft(t,"utf8"))}catch{return{version:1,patterns:{}}}}function ue(e,t){let n=de(e);yt(ht(n),{recursive:!0}),gt(n,JSON.stringify(t,null,2),"utf8")}function _t(e){let t=Date.now()-ce;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function fe(e,t){if(t.length===0)return!1;let n=ge(t),o=me(e);_t(o);let r=new Date().toISOString(),s=o.patterns[n];if(s||(s={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=s),s.promoted)return ue(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=le;return i&&(s.promoted=!0),ue(e,o),i}function bt(e){let t=me(e);return Object.values(t.patterns)}function ge(e){return[...e].sort().join("+")}function Rt(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<se||e.distinctToolCount<ie||Date.now()-pe<ae||t?.projectRoot&&t.tools.length>0&&!fe(t.projectRoot,t.tools))}function xt(e){return e.existingSkillName?e.feedback==="negative":!1}function St(e,t){return xt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Rt(e,t)?(pe=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 kt(e){return[...new Set(e.map(S).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function ye(e){let t=kt(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not invent or attempt any tool outside this list. If the request needs a capability none of these tools cover, do not silently refuse: consider exec-based scripts/OS commands, use community_seek (when listed) to find an installable capability, and otherwise state plainly which capability is missing.`}function At(e){let t=[...new Set(e.map(S).filter(Boolean))].sort((i,a)=>i.localeCompare(a)),n=new Set(t),o=ye(e),r=n.has("exec"),s=["read","search","write","edit","patch"].some(i=>n.has(i));return!r||!s?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function S(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 Mt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Et(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function It(e){if(!e.eligibility?.length)return[...e.tools];let t=Et(e.eligibility);return e.tools.filter(n=>{let o=S(n);if(!o)return!1;let r=t.get(o);return!r||Mt(r.status)})}function vt(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 wt(e){let t=vt({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=It({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:ye(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:At(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(l=>S(l)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Ot=["stop","aborted","timeout","cancelled","interrupted","error"],Lt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Te(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Pt(e,t){return{...e,content:[...Te(e.content),...Te(t.content)]}}function Nt(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function Ft(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let s=Nt(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(n.push(a),t.add(i))}}return n}function Dt(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function Bt(e){return new Set((e??Ot).map(t=>t.trim().toLowerCase()))}function he(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 j(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(l=>{if(l.role==="assistant"&&Array.isArray(l.tool_calls)){let u=l.tool_calls.filter(c=>Dt(c));return{...l,...u.length>0?{tool_calls:u}:{tool_calls:void 0}}}return{...l}}),n=new Set;for(let l of t)if(!(l.role!=="assistant"||!Array.isArray(l.tool_calls)))for(let u of l.tool_calls)typeof u.id=="string"&&u.id&&n.add(u.id);let o=t.filter(l=>l.role!=="tool"?!0:!!(l.tool_call_id&&n.has(l.tool_call_id))),r=new Set;for(let l of o)l.role==="tool"&&typeof l.tool_call_id=="string"&&l.tool_call_id&&r.add(l.tool_call_id);let s=[];for(let l of o){if(l.role==="assistant"&&Array.isArray(l.tool_calls)&&l.tool_calls.length>0){let u=l.tool_calls.filter(c=>typeof c.id=="string"&&r.has(c.id));if(u.length===0){let{tool_calls:c,...d}=l;d.content!=null&&d.content!==""&&s.push(d);continue}if(u.length<l.tool_calls.length){s.push({...l,tool_calls:u});continue}}s.push(l)}let i=Ft(s),a=[];for(let l of i){let u=a.length>0?a[a.length-1]:void 0;if(l.role==="user"&&u?.role==="user"){a[a.length-1]=Pt(u,l);continue}a.push(l)}return a}function $(e,t){return he(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Lt)delete o[r];return o}):[...e]}function H(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function Gt(e,t){let n=j(e),o=$(n,t);return H(o,t)}function Ce(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=he(t?.stopReason,t?.forcedStopReasons),r=[];for(let 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 s=new Set,i=new Map;for(let u of r){if(u.type!=="function_call")continue;let c=typeof u.call_id=="string"&&u.call_id?u.call_id:typeof u.id=="string"?u.id:void 0;c&&(s.add(c),i.set(c,u))}let a=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||!s.has(c))continue;a.add(c)}l.push(u)}for(let[u]of i)a.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function jt(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 $t(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 Ht(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 _e(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 Yt(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=j(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=$(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=H(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:_e({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:jt(r),completedToolCallIds:$t(r)}),recoveryActions:t}}function Kt(e){let t=Ce(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:_e({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:Ht(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 Zn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Qt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var z=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var q="<fork-child-context>",be="Fork started \u2014 processing in background";function en(e){return JSON.stringify(e).includes(q)}function tn(e){return e<G}function nn(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
19
+ ${m}`}))}if(l.length===0)return e;let u=[...e],p=-1;for(let d=0;d<u.length;d++)u[d].role==="system"&&(p=d);return u.splice(p+1,0,...l),u}function ut(e,t,n=S){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of e){let l=a.tool_call_id??"";if(l&&t.has(l)){o+=n(a),r++,t.delete(l);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}function pt(){return{stages:[]}}function dt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=re(e,t),i=ft(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=re(e,t),{messages:s,stagedCount:i.length}}function mt(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:se(e,t),committed:n}}function re(e,t){return t.stages.filter(o=>o.committed).length===0?e:se(e,t)}function se(e,t){let n=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),o=[...e];for(let r of n){let[s,i]=r.range;if(s>=o.length)continue;let a=Math.min(i,o.length),l={role:"system",content:r.summary};o.splice(s,a-s,l)}return o}function ft(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,a=0;for(let l=0;l<o;l++){let c=e[l];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")i<0&&(i=l),a++;else{if(a>=3){let p=`${i}-${i+a}`;s.has(p)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let l=`${i}-${i+a}`;s.has(l)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{readFileSync as gt,writeFileSync as yt,mkdirSync as Tt}from"node:fs";import{join as ht,dirname as Ct}from"node:path";var Ln=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Pn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var ie=3,ae=2,le=300*1e3,ce=3,ue=720*60*60*1e3,G=4;var Nn=3600*1e3;var Dn=50*1024,Fn=500*1024,Bn=500*1024*1024,Un=50*1024*1024;var Gn=60*1024;var de=0;var _t="skill-patterns.json";function me(e){return ht(e,".qlogicagent",_t)}function fe(e){let t=me(e);try{return JSON.parse(gt(t,"utf8"))}catch{return{version:1,patterns:{}}}}function pe(e,t){let n=me(e);Tt(Ct(n),{recursive:!0}),yt(n,JSON.stringify(t,null,2),"utf8")}function bt(e){let t=Date.now()-ue;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function ge(e,t){if(t.length===0)return!1;let n=ye(t),o=fe(e);bt(o);let r=new Date().toISOString(),s=o.patterns[n];if(s||(s={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=s),s.promoted)return pe(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=ce;return i&&(s.promoted=!0),pe(e,o),i}function Rt(e){let t=fe(e);return Object.values(t.patterns)}function ye(e){return[...e].sort().join("+")}function St(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<ie||e.distinctToolCount<ae||Date.now()-de<le||t?.projectRoot&&t.tools.length>0&&!ge(t.projectRoot,t.tools))}function xt(e){return e.existingSkillName?e.feedback==="negative":!1}function kt(e,t){return xt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:St(e,t)?(de=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 At(e){return[...new Set(e.map(x).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function Te(e){let t=At(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not invent or attempt any tool outside this list. If the request needs a capability none of these tools cover, do not silently refuse: consider exec-based scripts/OS commands, and otherwise state plainly which capability is missing.`}function Et(e){let t=[...new Set(e.map(x).filter(Boolean))].sort((i,a)=>i.localeCompare(a)),n=new Set(t),o=Te(e),r=n.has("exec"),s=["read","search","write","edit","patch"].some(i=>n.has(i));return!r||!s?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function x(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 Mt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function vt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function It(e){if(!e.eligibility?.length)return[...e.tools];let t=vt(e.eligibility);return e.tools.filter(n=>{let o=x(n);if(!o)return!1;let r=t.get(o);return!r||Mt(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=It({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:Te(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:Et(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(l=>x(l)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Lt=["stop","aborted","timeout","cancelled","interrupted","error"],Pt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function he(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Nt(e,t){return{...e,content:[...he(e.content),...he(t.content)]}}function Dt(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function Ft(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let s=Dt(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(n.push(a),t.add(i))}}return n}function Bt(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 Ut(e){return new Set((e??Lt).map(t=>t.trim().toLowerCase()))}function Ce(e,t){return e?Ut(t).has(e.trim().toLowerCase()):!1}function Gt(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function j(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(l=>{if(l.role==="assistant"&&Array.isArray(l.tool_calls)){let c=l.tool_calls.filter(u=>Bt(u));return{...l,...c.length>0?{tool_calls:c}:{tool_calls:void 0}}}return{...l}}),n=new Set;for(let l of t)if(!(l.role!=="assistant"||!Array.isArray(l.tool_calls)))for(let c of l.tool_calls)typeof c.id=="string"&&c.id&&n.add(c.id);let o=t.filter(l=>l.role!=="tool"?!0:!!(l.tool_call_id&&n.has(l.tool_call_id))),r=new Set;for(let l of o)l.role==="tool"&&typeof l.tool_call_id=="string"&&l.tool_call_id&&r.add(l.tool_call_id);let s=[];for(let l of o){if(l.role==="assistant"&&Array.isArray(l.tool_calls)&&l.tool_calls.length>0){let c=l.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(c.length===0){let{tool_calls:u,...p}=l;p.content!=null&&p.content!==""&&s.push(p);continue}if(c.length<l.tool_calls.length){s.push({...l,tool_calls:c});continue}}s.push(l)}let i=Ft(s),a=[];for(let l of i){let c=a.length>0?a[a.length-1]:void 0;if(l.role==="user"&&c?.role==="user"){a[a.length-1]=Nt(c,l);continue}a.push(l)}return a}function $(e,t){return Ce(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Pt)delete o[r];return o}):[...e]}function H(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function jt(e,t){let n=j(e),o=$(n,t);return H(o,t)}function _e(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=Ce(t?.stopReason,t?.forcedStopReasons),r=[];for(let c=0;c<e.length;c+=1){let u=e[c];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(c+1).some(m=>m&&typeof m=="object"&&m.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let p={...u};if(typeof p.id=="string"){let d=Gt(p.id);d.itemId?.startsWith("fc_")&&(p.id=d.callId)}r.push(p)}let s=new Set,i=new Map;for(let c of r){if(c.type!=="function_call")continue;let u=typeof c.call_id=="string"&&c.call_id?c.call_id:typeof c.id=="string"?c.id:void 0;u&&(s.add(u),i.set(u,c))}let a=new Set,l=[];for(let c of r)if(!(o&&c.type==="function_call")){if(c.type==="function_call_output"){let u=typeof c.call_id=="string"?c.call_id:"";if(!u||!s.has(u))continue;a.add(u)}l.push(c)}for(let[c]of i)a.has(c)||o||l.push({type:"function_call_output",call_id:c,output:n});return l}function $t(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 zt(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 qt(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 be(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Yt(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=j(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=$(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=H(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:be({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:$t(r),completedToolCallIds:Ht(r)}),recoveryActions:t}}function Wt(e){let t=_e(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:be({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:zt(t),completedToolCallIds:qt(t)}),recoveryActions:n}}var Vt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Jt(e){return e?Vt.has(e):!0}function Zt(e){return e===429||e===529}function Qt(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var Zn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function en(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var z=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var q="<fork-child-context>",Re="Fork started \u2014 processing in background";function tn(e){return JSON.stringify(e).includes(q)}function nn(e){return e<G}function on(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
20
20
 
21
21
  Your working directory is: ${e.worktreePath}
22
22
  All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${q}
23
23
 
24
24
  You are the "${t.agent.name}" agent.${o}
25
25
 
26
- ${t.taskPrompt}`}]};return n.push(r),n}function on(e){return e.map(t=>({role:"tool",tool_call_id:t,content:be}))}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")}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"],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"],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")}function Tn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function hn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Cn(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 _n(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 bn(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 Rn(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var xn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Sn(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
26
+ ${t.taskPrompt}`}]};return n.push(r),n}function rn(e){return e.map(t=>({role:"tool",tool_call_id:t,content:Re}))}function sn(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolCapabilityProfile==="no_tools")return[];if(t.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent")}function an(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var ln={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},cn={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"],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."},un={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"],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."},pn={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."},dn={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."},mn={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=[ln,cn,un,pn,dn,mn];function fn(){return[...Y]}function gn(e){return Y.find(t=>t.name===e)}function yn(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")}function hn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function Cn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function _n(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 bn(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 Rn(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 Sn(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}function xn(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
27
27
  ${n.join(`
28
28
  `)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
29
29
  Step ${e.activeSkillContext.step}:
@@ -34,4 +34,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
34
34
 
35
35
  ${t.join(`
36
36
 
37
- `)}`}function kn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function An(e,t=xn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{P as CacheAwareCompressionStrategy,N as CompressionMetricsCollector,F as ContextEngineRegistry,te as DEFAULT_ADAPTIVE_BUDGET_CONFIG,be as FORK_PLACEHOLDER_RESULT,q as FORK_SENTINEL_TAG,z as FallbackTriggeredError,O as HeadTailProtectedStrategy,L as IncrementalCompactStrategy,G as MAX_FORK_DEPTH,D as MicroCompactStrategy,I as SlidingWindowStrategy,v as SummarizeOldStrategy,w as ToolResultTrimStrategy,qt as advanceToolLoopState,pt as applyContextCollapsesIfNeeded,wt as applyToolChoicePolicy,Re as buildAssistantToolCallMessage,on as buildForkPlaceholderResults,nn as buildForkedMessages,Sn as buildPostCompactRestorationMessage,St as buildSkillInstruction,U as buildStructuredSummaryPrompt,xe as buildToolResultMessage,ge as buildToolSignature,Cn as calculateTokenWarningState,tn as canForkAtDepth,Qe as classifyError,ot as composeAsyncStrategies,nt as composeStrategies,rt as computeAdaptiveBudget,Zt as computeRetryBackoff,ut as createCollapseStore,kn as createReactiveCompactState,Tn as createTaskState,hn as createTurnLoopGuardState,sn as generateForkChildAgentId,fn as getBuiltInAgent,mn as getBuiltInAgents,bt as getPatternStats,B as isAsyncCompressionStrategy,gn as isBuiltInAgent,Vt as isForegroundSource,en as isInForkChild,Qt as isPersistentRetryEnabled,et as isRetryableCategory,Jt as isTransientCapacityError,lt as postCompactFileRecovery,fe as recordPatternAndCheckThreshold,dt as recoverContextCollapseFromOverflow,Xt as recoverToolLoopStateFromChatConversation,Kt as recoverToolLoopStateFromResponsesItems,Gt as repairOpenAiChatConversation,yn as resolveAgentToolSet,_n as resolveApiErrorRecovery,rn as resolveForkChildTools,bn as resolveOutputTokenEscalation,st as selectCompressionTier,Yt as settleToolLoopState,Rn as shouldAbortTurn,An as shouldAttemptReactiveCompact,ct as snipCompactIfNeeded};
37
+ `)}`}function kn(){return{attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function An(e){return!e.attemptedThisTurn}export{P as CacheAwareCompressionStrategy,N as CompressionMetricsCollector,D as ContextEngineRegistry,ne as DEFAULT_ADAPTIVE_BUDGET_CONFIG,Re as FORK_PLACEHOLDER_RESULT,q as FORK_SENTINEL_TAG,z as FallbackTriggeredError,O as HeadTailProtectedStrategy,L as IncrementalCompactStrategy,G as MAX_FORK_DEPTH,F as MicroCompactStrategy,v as SlidingWindowStrategy,I as SummarizeOldStrategy,w as ToolResultTrimStrategy,Yt as advanceToolLoopState,dt as applyContextCollapsesIfNeeded,Ot as applyToolChoicePolicy,Se as buildAssistantToolCallMessage,rn as buildForkPlaceholderResults,on as buildForkedMessages,xn as buildPostCompactRestorationMessage,kt as buildSkillInstruction,U as buildStructuredSummaryPrompt,xe as buildToolResultMessage,ye as buildToolSignature,_n as calculateTokenWarningState,nn as canForkAtDepth,et as classifyError,rt as composeAsyncStrategies,ot as composeStrategies,st as computeAdaptiveBudget,Qt as computeRetryBackoff,pt as createCollapseStore,kn as createReactiveCompactState,hn as createTaskState,Cn as createTurnLoopGuardState,an as generateForkChildAgentId,gn as getBuiltInAgent,fn as getBuiltInAgents,Rt as getPatternStats,B as isAsyncCompressionStrategy,yn as isBuiltInAgent,Jt as isForegroundSource,tn as isInForkChild,en as isPersistentRetryEnabled,tt as isRetryableCategory,Zt as isTransientCapacityError,ct as postCompactFileRecovery,ge as recordPatternAndCheckThreshold,mt as recoverContextCollapseFromOverflow,Kt as recoverToolLoopStateFromChatConversation,Wt as recoverToolLoopStateFromResponsesItems,jt as repairOpenAiChatConversation,Tn as resolveAgentToolSet,bn as resolveApiErrorRecovery,sn as resolveForkChildTools,Rn as resolveOutputTokenEscalation,it as selectCompressionTier,Xt as settleToolLoopState,Sn as shouldAbortTurn,An as shouldAttemptReactiveCompact,ut 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","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),i=t.timeoutMs??n.defaultTimeoutMs;return{requestId:t.requestId??z(),createdAt:r,deadlineAt:r+i,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 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 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 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: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.purgeAll","instructions.list","instructions.read","instructions.write","instructions.delete","files.list","files.read","files.create","files.rename","files.move","files.copy","files.delete","files.search","files.undoOperation","files.gitStatus","turnBaseline.getSummary","turnBaseline.getFileDiff","turnBaseline.listRecent","turnBaseline.getFileBaseline","workingMaterials.get","workingMaterials.replace","workingMaterials.upsert","workingMaterials.remove","workingMaterials.reorder","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.file_changes","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.media_capability_check","turn.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_started","turn.subagent_delta","turn.subagent_ended","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.progress","turn.tool_use_summary","turn.tool_selection_policy","turn.lifecycle","turn.document_maintenance","turn.artifact_contract","turn.usage_update","team.member.notification","session.info","session.recovery_pending","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","workflow.triggerDropped","workflow.alert","workflow.approvalRequested","workflow.approvalTimedOut"],k=["solo.progress","solo.specProgress","solo.agentDelta","solo.agentActivity","solo.agentUsage","solo.evaluation","product.taskStarted","product.taskOutput","product.members","product.agentActivity","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.budgetWarning","product.checkpointed","product.completed","product.dagTopology","plan.interrupted","goal.run_state_changed","goal.phase_boundary","goal.goal_edited","goal.message_queued","goal.acceptance_updated"],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"},oe={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_REPLAY:"x/product.replay",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",WORKFLOW_MATCH_INTENT:"x/workflow.matchIntent",PRODUCT_SUBSCRIBE:"x/product.subscribe",GOAL_START:"x/goal.start",GOAL_STATUS:"x/goal.status",GOAL_PAUSE:"x/goal.pause",GOAL_RESUME:"x/goal.resume",GOAL_UPDATE_GOAL:"x/goal.updateGoal",GOAL_STOP:"x/goal.stop",GOAL_MESSAGE:"x/goal.message",GOAL_SUBSCRIBE:"x/goal.subscribe",GOAL_EVENTS:"x/goal.events",MENTION_DELEGATE:"x/mention.delegate",MENTION_CANCEL:"x/mention.cancel",MENTION_LIST:"x/mention.list"},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 _(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:_(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:_(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 i={snapshotVersion:r.snapshotVersion,updatedAt:r.updatedAt,syncMode:"diff",baseSnapshotVersion:t.snapshotVersion,changedSections:n,toolNamespaces:[...r.toolNamespaces],workspaceIds:[...r.workspaceIds]},c=i;for(let s of n){let o=r[s];if(o!==void 0)switch(s){case"toolNamespaces":case"workspaceIds":case"installedCapabilities":case"enabledCapabilities":case"features":c[s]=ce(o);break;case"approvalPolicy":c[s]={...o};break;case"workspaceSummaries":c[s]=_(o);break;case"toolManifests":case"skillManifests":case"pluginManifests":case"mcpManifests":c[s]=g(o);break;default:c[s]=o;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"],_e=["browser-read","browser-authenticated-read","browser-state-changing"];var Se=["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 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(n=>W(e,n)).filter(n=>!!n):[]}function xe(e,t){return e.assets[t.id]=U(t),F(e)}function S(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=S(e.assets[a.gatewayImage]),r=S(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[o,p]of Object.entries(n)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.artifacts)||(r[o]=U(u))}if(!r[a.gatewayImage]&&t.gateway&&typeof t.gateway=="object"){let o=L(t.gateway,{id:a.gatewayImage,title:"XiaoZhiClaw Gateway Image (Desktop Slim)",kind:"container-image",delivery:"remote",platform:"any",description:"Desktop Docker mode gateway image."});o&&(r[o.id]=o)}if(!r[a.whisperModelTiny]&&t.whisperModel&&typeof t.whisperModel=="object"){let o=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."});o&&(r[o.id]=o)}let c={...K()},s=t.profiles&&typeof t.profiles=="object"?t.profiles:{};for(let[o,p]of Object.entries(s)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.assetIds)||(c[o]=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(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??[]),i=o=>{let p=r[o]?.trim();if(!p)return null;let u=n.has(o)?`shell env: ${o}`:`env: ${o}`;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 o of s){let p=i(o);if(p)return p}return null}export{oe as ACP_EXTENDED_METHODS,ie 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,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,Se 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,_e 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,S as getManifestShortcutEntry,W 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,We 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 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","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),i=t.timeoutMs??n.defaultTimeoutMs;return{requestId:t.requestId??z(),createdAt:r,deadlineAt:r+i,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 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 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 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: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.purgeAll","instructions.list","instructions.read","instructions.write","instructions.delete","files.list","files.read","files.create","files.rename","files.move","files.copy","files.delete","files.search","files.undoOperation","files.gitStatus","turnBaseline.getSummary","turnBaseline.getFileDiff","turnBaseline.listRecent","turnBaseline.getFileBaseline","workingMaterials.get","workingMaterials.replace","workingMaterials.upsert","workingMaterials.remove","workingMaterials.reorder","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.file_changes","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.media_capability_check","turn.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_started","turn.subagent_delta","turn.subagent_ended","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.progress","turn.tool_use_summary","turn.tool_selection_policy","turn.lifecycle","turn.document_maintenance","turn.artifact_contract","turn.usage_update","team.member.notification","session.info","session.recovery_pending","memory.updated","skills.updated","turn.memory_recall","turn.memory_written","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","workflow.triggerDropped","workflow.alert","workflow.approvalRequested","workflow.approvalTimedOut"],k=["solo.progress","solo.specProgress","solo.agentDelta","solo.agentActivity","solo.agentUsage","solo.evaluation","product.taskStarted","product.taskOutput","product.members","product.agentActivity","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.budgetWarning","product.checkpointed","product.completed","product.dagTopology","plan.interrupted","goal.run_state_changed","goal.phase_boundary","goal.goal_edited","goal.message_queued","goal.acceptance_updated"],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"},oe={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_REPLAY:"x/product.replay",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",WORKFLOW_MATCH_INTENT:"x/workflow.matchIntent",PRODUCT_SUBSCRIBE:"x/product.subscribe",GOAL_START:"x/goal.start",GOAL_STATUS:"x/goal.status",GOAL_PAUSE:"x/goal.pause",GOAL_RESUME:"x/goal.resume",GOAL_UPDATE_GOAL:"x/goal.updateGoal",GOAL_STOP:"x/goal.stop",GOAL_MESSAGE:"x/goal.message",GOAL_SUBSCRIBE:"x/goal.subscribe",GOAL_EVENTS:"x/goal.events",MENTION_DELEGATE:"x/mention.delegate",MENTION_CANCEL:"x/mention.cancel",MENTION_LIST:"x/mention.list"},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 _(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:_(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:_(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 i={snapshotVersion:r.snapshotVersion,updatedAt:r.updatedAt,syncMode:"diff",baseSnapshotVersion:t.snapshotVersion,changedSections:n,toolNamespaces:[...r.toolNamespaces],workspaceIds:[...r.workspaceIds]},c=i;for(let s of n){let o=r[s];if(o!==void 0)switch(s){case"toolNamespaces":case"workspaceIds":case"installedCapabilities":case"enabledCapabilities":case"features":c[s]=ce(o);break;case"approvalPolicy":c[s]={...o};break;case"workspaceSummaries":c[s]=_(o);break;case"toolManifests":case"skillManifests":case"pluginManifests":case"mcpManifests":c[s]=g(o);break;default:c[s]=o;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"],_e=["browser-read","browser-authenticated-read","browser-state-changing"];var Se=["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 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(n=>W(e,n)).filter(n=>!!n):[]}function xe(e,t){return e.assets[t.id]=U(t),F(e)}function S(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=S(e.assets[a.gatewayImage]),r=S(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[o,p]of Object.entries(n)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.artifacts)||(r[o]=U(u))}if(!r[a.gatewayImage]&&t.gateway&&typeof t.gateway=="object"){let o=L(t.gateway,{id:a.gatewayImage,title:"XiaoZhiClaw Gateway Image (Desktop Slim)",kind:"container-image",delivery:"remote",platform:"any",description:"Desktop Docker mode gateway image."});o&&(r[o.id]=o)}if(!r[a.whisperModelTiny]&&t.whisperModel&&typeof t.whisperModel=="object"){let o=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."});o&&(r[o.id]=o)}let c={...K()},s=t.profiles&&typeof t.profiles=="object"?t.profiles:{};for(let[o,p]of Object.entries(s)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.assetIds)||(c[o]=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(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??[]),i=o=>{let p=r[o]?.trim();if(!p)return null;let u=n.has(o)?`shell env: ${o}`:`env: ${o}`;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 o of s){let p=i(o);if(p)return p}return null}export{oe as ACP_EXTENDED_METHODS,ie 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,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,Se 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,_e 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,S as getManifestShortcutEntry,W 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,We 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,10 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import{createInterface as Ye}from"node:readline";import{existsSync as Ze,readFileSync as Xe}from"node:fs";import{readFileSync as ve}from"node:fs";import{randomUUID as we}from"node:crypto";import{readdirSync as Pt,readFileSync as _t,statSync as ne,writeFileSync as Ct}from"node:fs";import{readdir as se,readFile as ie,stat as ae,writeFile as le}from"node:fs/promises";import{join as u}from"node:path";import{homedir as Q}from"node:os";import{join as c,resolve as ct}from"node:path";import{existsSync as dt}from"node:fs";import{createHash as mt}from"node:crypto";var k=".qlogicagent";function Y(){return process.env.QLOGICAGENT_HOME||c(Q(),k)}function Z(){let t=process.env.QLOGIC_LLMROUTER_USER_ID?.trim();if(t)return t;let e=process.env.QLOGIC_IMPLICIT_OWNER_ID?.trim();if(e)return e;let o=process.env.QLOGIC_DEVICE_ID?.trim();return o?`oc_${o}`:"oc_local"}function X(t){let e=t.trim();if(!e)throw new Error("ownerUserId is required for profile-scoped storage");return encodeURIComponent(e).replace(/\./g,"%2E")}function m(t=Z()){return c(Y(),"profiles",X(t))}function h(){return c(m(),"skills")}function P(){return c(m(),"mcp.json")}function ee(t){if(!t)throw new Error("getProjectAgentDir: cwd is required (must not fall back to process.cwd())");return c(t,k)}function _(t){return c(ee(t),"skills-disabled.json")}import{readFileSync as te,writeFileSync as ht,mkdirSync as yt,renameSync as bt}from"node:fs";import{dirname as wt,join as oe}from"node:path";function C(){return{version:1,disabled:[]}}function x(t){try{let e=JSON.parse(te(t,"utf8"));return!e||typeof e!="object"||!Array.isArray(e.disabled)?C():{version:1,disabled:[...new Set(e.disabled.filter(r=>typeof r=="string"&&r.trim().length>0))]}}catch{return C()}}function re(){return oe(m(),"skills-disabled.json")}function A(){return new Set(x(re()).disabled)}function R(t){return new Set(x(_(t)).disabled)}var ce=["auto-skill-","test-skill-"],ue=".skills_prompt_snapshot.json";function de(t){return ce.some(e=>t.startsWith(e))}function pe(t){let e=t.replace(/\r\n/g,`
3
- `),o=e.match(/^---\n[\s\S]*?^version:\s*(\S+)/m),r=e.match(/^---\n[\s\S]*?^category:\s*(.+)/m),n=e.match(/^---\n[\s\S]*?^author:\s*(.+)/m),i=e.match(/^---\n[\s\S]*?^requires:\s*(.+)/m),s=e.match(/^---\n[\s\S]*?^environments:\s*(.+)/m),a=e.match(/^---\n([\s\S]*?)\n---/)?.[1]??"";return{version:o?.[1],description:me(a),category:r?.[1]?.trim()||void 0,author:n?.[1]?.trim()||void 0,requiredTools:D(i?.[1]),environments:D(s?.[1])}}function me(t){let e=t.split(`
4
- `),o=e.findIndex(s=>/^description:/.test(s));if(o===-1)return;let r=e[o].replace(/^description:[ \t]*/,"").trim(),n=/^[>|][+-]?$/.test(r),i=[];!n&&r&&i.push(r);for(let s=o+1;s<e.length;s++){let a=e[s];if(!/^[ \t]/.test(a))break;let l=a.trim();l&&i.push(l)}if(i.length!==0)return i.join(" ").replace(/^["']|["']$/g,"").trim()||void 0}var M=new Map,y=new Map;function fe(t,e,o,r){let n=e.has(t.name),i=o.has(t.name),s=!ye(t.meta,r);return{name:t.name,filePath:t.filePath,baseDir:t.baseDir,globallyDisabled:n,projectDisabled:i,active:!n&&!i&&!s,systemGenerated:t.systemGenerated,description:t.meta.description,version:t.meta.version,category:t.meta.category,author:t.meta.author,requiredTools:t.meta.requiredTools,environments:t.meta.environments}}async function ge(t){let e;try{e=await se(t,{withFileTypes:!0})}catch{e=[]}let o=[];for(let s of e){if(!s.isDirectory()||s.name.startsWith("."))continue;let a=u(t,s.name),l=u(a,"SKILL.md");try{let g=await ae(l);if(!g.isFile())continue;o.push({name:s.name,filePath:l,baseDir:a,mtimeMs:g.mtimeMs,size:g.size})}catch{continue}}o.sort((s,a)=>s.name.localeCompare(a.name));let r=o.map(s=>`${s.name}:${s.mtimeMs}:${s.size}`).join("|"),n=M.get(t);if(n&&n.fingerprint===r)return n.raw;let i=[];for(let s of o){let a;try{a=await ie(s.filePath,"utf8")}catch{continue}i.push({name:s.name,filePath:s.filePath,baseDir:s.baseDir,systemGenerated:de(s.name),mtimeMs:s.mtimeMs,size:s.size,meta:pe(a)})}return M.set(t,{fingerprint:r,raw:i}),be(t,i),i}async function he(t,e){let o=h(),r=A(),n=t?R(t):new Set,i=y.get(o);return i||(i=ge(o).finally(()=>y.delete(o)),y.set(o,i)),(await i).map(a=>fe(a,r,n,e))}async function E(t,e){return(await he(t,e)).filter(o=>o.active)}function I(t){let e=h(),o=u(e,t),r=u(o,"SKILL.md");try{if(ne(r).isFile())return{baseDir:o,filePath:r}}catch{}return null}function D(t){if(!t)return;let e=t.replace(/^\[|\]$/g,"").split(/[,\s]+/).map(o=>o.replace(/^["']|["']$/g,"").trim()).filter(Boolean);return e.length>0?e:void 0}function ye(t,e){if(t.environments&&e?.currentEnvironment&&!t.environments.includes(e.currentEnvironment))return!1;if(t.requiredTools){if(!e?.availableToolNames)return!1;let o=new Set(e.availableToolNames);return t.requiredTools.every(r=>o.has(r))}return!0}async function be(t,e){try{let r={version:1,entries:e.map(n=>({name:n.name,size:n.size,mtimeMs:n.mtimeMs,description:n.meta.description,version:n.meta.version,requiredTools:n.meta.requiredTools,environments:n.meta.environments}))};await le(u(t,ue),JSON.stringify(r,null,2),"utf8")}catch{}}var j="astraclaw_capabilities";async function L(t){if(t.tool==="skills_list")return{handled:!0,result:{skills:(await E(t.projectRoot,{availableToolNames:t.availableToolNames,currentEnvironment:t.currentEnvironment??process.platform})).map(Te)}};if(t.tool==="skill_view"){let e=typeof t.args.name=="string"?t.args.name.trim():"";if(!e)throw new Error("skill_view requires a skill name");let o=I(e);if(!o)throw new Error(`Skill not found: ${e}`);return{handled:!0,result:{name:e,content:ve(o.filePath,"utf8")}}}if(t.tool==="mcp_connectors_list"){if(!t.toolCatalog)return{handled:!0,result:{tools:[],note:"AstraClaw MCP connector catalog is not attached to this capability server instance."}};let e=t.toolCatalog.getToolManifest().filter(o=>o.function.name.startsWith("mcp__")).map(o=>({toolName:o.function.name,server:ke(o.function.name),name:Pe(o.function.name),description:o.function.description,inputSchema:o.function.parameters}));return{handled:!0,result:{tools:e,count:e.length}}}if(t.tool==="mcp_tool_call"){if(!t.toolCatalog)throw new Error("AstraClaw MCP connector catalog is not attached");let e=typeof t.args.toolName=="string"?t.args.toolName.trim():"";if(!e.startsWith("mcp__"))throw new Error("mcp_tool_call requires a connector toolName returned by mcp_connectors_list");let o=t.toolCatalog.findTool(e);if(!o?.execute)throw new Error(`MCP connector tool not found or not executable: ${e}`);let r=Se(t.args.args),n=`astraclaw_mcp_${we().slice(0,8)}`,i=await o.execute(n,r);return{handled:!0,result:{toolName:e,content:i.content,details:i.details,imageUrls:i.imageUrls}}}return{handled:!1}}function Te(t){return{name:t.name,description:t.description,version:t.version,category:t.category,requiredTools:t.requiredTools,environments:t.environments}}function Se(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function ke(t){let e=t.split("__");return e.length>=3?e[1]??"":""}function Pe(t){let e=t.split("__");return e.length>=3?e.slice(2).join("__"):t}import d from"node:path";import{fileURLToPath as Re}from"node:url";import{createRuntime as Me}from"mcporter";var O=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),_e=new Set([...O,"agent"]);function N(t){return t?.riskLevel?t.riskLevel:t?.isDangerous?"system":t?.isReadOnly?"read":t?.isEgress?"external_egress":"write"}var b=class{toolPool=new Map;setTools(e){this.toolPool.clear();for(let o of e)this.toolPool.set(o.name,o)}addTool(e){this.toolPool.set(e.name,e)}addTools(e){for(let o of e)this.addTool(o)}removeTool(e){return this.toolPool.delete(e)}findTool(e){return this.toolPool.get(e)}hasTool(e){return this.toolPool.has(e)}getToolNames(){return Array.from(this.toolPool.keys())}getToolCount(){return this.toolPool.size}async executeTool(e,o,r,n){let i=this.toolPool.get(e);if(!i)throw new Error(`Tool not found: ${e}`);return i.execute(o,r,n)}getTools(){return Array.from(this.toolPool.values()).filter(e=>e.isEnabled?.()!==!1)}getToolManifest(){let e=[];for(let o of this.toolPool.values()){if(o.isEnabled?.()===!1)continue;let r=N(o);e.push({type:"function",function:{name:o.name,description:o.description,parameters:o.parameters},meta:{category:o.category??"other",displayName:o.displayName??{key:`capability.tool.${o.name}.name`,fallback:o.label},displayDescription:o.displayDescription??{key:`capability.tool.${o.name}.description`,fallback:""},parallelSafe:o.isConcurrencySafe??!1,riskLevel:r,isReadOnly:r==="read",isDangerous:r==="system",isDelete:o.isDelete??!1,isEgress:o.isEgress??r==="external_egress",egressCarriesData:o.egressCarriesData??!1}})}return e}},$=new b;function q(t){$.addTools(t)}function U(t){return $.removeTool(t)}var Ce=new Set(["describe","fetch","find","get","inspect","list","query","read","search","stat"]),xe=new Set(["append","copy","create","delete","edit","move","patch","remove","rename","set","update","upload","write"]);function F(t){let e=t.annotations,o=Ae(t.name),r=o.some(l=>xe.has(l)),n=o.some(l=>Ce.has(l)),i=e?.destructiveHint===!0||r,s=e?.readOnlyHint===!0||!i&&n,a=s||e?.idempotentHint===!0&&!i;return{isReadOnly:s,isConcurrencySafe:a,isDestructive:i}}function Ae(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}var De=12e4,v=3,Ee=1e3;async function Ie(t,e){let o=e.sleep??(i=>new Promise(s=>setTimeout(s,i))),r=Math.max(1,e.attempts),n;for(let i=1;i<=r;i++)try{return await t()}catch(s){n=s,i<r&&(e.onRetry?.(i,s),await o(e.baseDelayMs*i))}throw n}var f=class{runtime=null;definitions=[];toolsByServer=new Map;injectedNames=new Set;log;workspaceRoot;toolCatalog;serverToolFilters=new Map;serverOAuth=new Map;constructor(e){this.log=e.log??{info:()=>{},warn:()=>{}},this.workspaceRoot=e.workspaceRoot?d.resolve(e.workspaceRoot):void 0,this.toolCatalog=e.toolCatalog,this.definitions=e.servers.filter(o=>!o.disabled).filter(o=>{let r=Je(o);for(let n of r)this.log.warn(`[mcp] rejected server "${o.name}": ${n.message}`);return o.tools&&this.serverToolFilters.set(o.name,o.tools),o.oauth===!0&&this.serverOAuth.set(o.name,!0),r.length===0}).map(o=>this.toServerDefinition(o)).filter(o=>o!==null)}toServerDefinition(e){if((e.type??(e.url?"http":"stdio"))==="http"){if(!e.url)return this.log.warn(`[mcp] server "${e.name}" is type "http" but has no url, skipping`),null;let r;try{r=new URL(e.url)}catch{return this.log.warn(`[mcp] server "${e.name}" has an invalid url "${e.url}", skipping`),null}return{name:e.name,command:{kind:"http",url:r,headers:e.headers}}}return e.command?{name:e.name,command:{kind:"stdio",command:e.command,args:e.args??[],cwd:e.cwd??this.workspaceRoot??process.cwd()},env:e.env}:(this.log.warn(`[mcp] server "${e.name}" is type "stdio" but has no command, skipping`),null)}async connectAll(){this.definitions.length!==0&&(this.runtime=await Me({servers:this.definitions,clientInfo:{name:"qlogicagent",version:"1.0.0"},logger:{info:e=>this.log.info(`[mcp] ${e}`),warn:e=>this.log.warn(`[mcp] ${e}`),error:(e,o)=>this.log.warn(`[mcp] ${e}${o?` (${o instanceof Error?o.message:String(o)})`:""}`),debug:()=>{}}}),await Promise.allSettled(this.definitions.map(async e=>{try{let o=await Ie(()=>this.runtime.listTools(e.name,{includeSchema:!0,disableOAuth:this.serverOAuth.get(e.name)!==!0}),{attempts:v,baseDelayMs:Ee,onRetry:(n,i)=>this.log.warn(`[mcp] connect attempt ${n}/${v} for ${e.name} failed, retrying: ${i instanceof Error?i.message:i}`)}),r=z(o,this.serverToolFilters.get(e.name));this.toolsByServer.set(e.name,r),this.log.info(`[mcp] connected to ${e.name} (${r.length}/${o.length} tools)`)}catch(o){this.log.warn(`[mcp] failed to connect to ${e.name} after ${v} attempts: ${o instanceof Error?o.message:o}`)}})))}injectTools(){for(let[e,o]of this.toolsByServer){let r=this.injectPortableTools(e,o);this.log.info(`[mcp] injected ${r.length} tools from ${e}`)}}async refreshServerTools(e){if(!this.runtime)throw new Error("MCP runtime is not connected");let o=await this.runtime.listTools(e,{includeSchema:!0,disableOAuth:this.serverOAuth.get(e)!==!0}),r=z(o,this.serverToolFilters.get(e));return this.toolsByServer.set(e,r),this.retractServerTools(e),this.injectPortableTools(e,r),r.length}getConnectedServers(){return Array.from(this.toolsByServer.keys())}getToolCount(){let e=0;for(let o of this.toolsByServer.values())e+=o.length;return e}async disconnectAll(){for(let o of this.injectedNames)this.removeRegisteredTool(o);this.injectedNames.clear(),this.toolsByServer.clear();let e=this.runtime;if(this.runtime=null,e)try{await e.close()}catch{}}toPortableTool(e,o){let r=F({name:o.name,description:o.description});return{name:`mcp__${G(e)}__${o.name}`,label:`[${e}] ${o.name}`,category:"mcp",description:o.description??`MCP tool from ${e}`,parameters:o.inputSchema??{type:"object",properties:{}},isConcurrencySafe:r.isConcurrencySafe,isReadOnly:r.isReadOnly,isDestructive:r.isDestructive,searchHint:`mcp ${e} ${o.name.replace(/[_-]+/g," ")}`,execute:async(n,i)=>{let s=this.runtime;if(!s)return{content:[{type:"text",text:`MCP server "${e}" is not connected.`}],details:{error:"mcp_not_connected"}};try{let a=await s.callTool(e,o.name,{args:i,timeoutMs:De});return je(a)}catch(a){let l=a instanceof Error?a.message:String(a);return{content:[{type:"text",text:`MCP tool error: ${l}`}],details:{error:l}}}}}}wrapToolsForWorkspaceBoundary(e){return this.workspaceRoot?e.map(o=>{if(!o.execute)return o;let r=o.execute;return{...o,execute:async(n,i,s)=>{let a=Oe(o.name,i,this.workspaceRoot);return a?{content:[{type:"text",text:a}],details:{type:"mcp",error:"workspace_boundary"}}:r(n,i,s)}}}):e}injectPortableTools(e,o){let r=this.wrapToolsForWorkspaceBoundary(o.map(n=>this.toPortableTool(e,n)));this.registerTools(r);for(let n of r)this.injectedNames.add(n.name);return r}retractServerTools(e){let o=`mcp__${G(e)}__`;for(let r of[...this.injectedNames])r.startsWith(o)&&(this.removeRegisteredTool(r),this.injectedNames.delete(r))}registerTools(e){this.toolCatalog?this.toolCatalog.addTools(e):q(e)}removeRegisteredTool(e){return this.toolCatalog?.removeTool(e)??U(e)}};function je(t){let e=t&&typeof t=="object"?t:{};return{content:[{type:"text",text:(Array.isArray(e.content)?e.content:[]).filter(i=>!!i&&typeof i=="object").filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(`
5
- `)||"(no text output)"}],...e.isError?{details:{error:"mcp_tool_error"}}:{}}}function G(t){return t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var Le=/(?:^|_)(path|paths|file|files|filename|filenames|dir|dirs|directory|directories|folder|folders|cwd|root|uri)(?:$|_)/i;function Oe(t,e,o){if(!o)return null;for(let r of T(e)){let n=qe(r.value,o);if(n&&!Ue(n.candidate,n.root,n.pathApi))return`Blocked: MCP tool "${t}" path "${r.value}" is outside the workspace boundary "${n.root}"`}return null}function T(t,e="",o=0){if(o>8)return[];if(typeof t=="string")return Ne(e,t)?[{key:e,value:t}]:[];if(Array.isArray(t))return t.flatMap(n=>T(n,e,o+1));if(!t||typeof t!="object")return[];let r=[];for(let[n,i]of Object.entries(t))r.push(...T(i,n,o+1));return r}function Ne(t,e){if(!Le.test(t))return!1;let o=e.trim();return!o||/^https?:\/\//i.test(o)?!1:$e(o)}function $e(t){return d.isAbsolute(t)||/^[A-Za-z]:[\\/]/.test(t)||/^\\\\/.test(t)||/^file:\/\//i.test(t)||t.includes("../")||t.includes("..\\")||t.startsWith(".\\")||t.startsWith("./")||t.includes("/")||t.includes("\\")}function qe(t,e){let o=t.trim();if(/^file:\/\//i.test(o))try{o=Re(o)}catch{return null}let r=W(o)||W(e)?d.win32:d,n=r.resolve(e);return{candidate:r.isAbsolute(o)?r.resolve(o):r.resolve(n,o),root:n,pathApi:r}}function Ue(t,e,o){let r=o.relative(e,t);return r===""||!r.startsWith("..")&&!o.isAbsolute(r)}function W(t){return/^[A-Za-z]:[\\/]/.test(t)||/^\\\\/.test(t)}function J(t){if(!t||typeof t!="object")return[];let e=t,o=[],r=e.mcpServers??e.servers??e;for(let[n,i]of Object.entries(r)){if(!i||typeof i!="object")continue;let s=i;if(typeof s.url=="string"){o.push({name:n,type:"http",url:s.url,headers:s.headers&&typeof s.headers=="object"?s.headers:void 0,disabled:s.disabled===!0,oauth:s.oauth===!0,tools:B(s.tools)});continue}typeof s.command=="string"&&o.push({name:n,type:"stdio",command:s.command,args:Array.isArray(s.args)?s.args:void 0,env:s.env&&typeof s.env=="object"?s.env:void 0,cwd:typeof s.cwd=="string"?s.cwd:void 0,disabled:s.disabled===!0,oauth:s.oauth===!0,tools:B(s.tools)})}return o}function z(t,e){let o=new Set(e?.include??[]),r=new Set(e?.exclude??[]);return t.filter(n=>o.size>0&&!o.has(n.name)?!1:!r.has(n.name))}function B(t){if(!t||typeof t!="object")return;let e=t,o=H(e.include),r=H(e.exclude);if(!(!o&&!r))return{...o?{include:o}:{},...r?{exclude:r}:{}}}function H(t){if(!Array.isArray(t))return;let e=t.filter(o=>typeof o=="string"&&o.trim().length>0);return e.length>0?e:void 0}var Fe=new Set(["bash","sh","zsh","fish","cmd","cmd.exe","powershell","powershell.exe","pwsh","pwsh.exe"]),Ge=new Set(["-c","/c","-command","-encodedcommand","-e"]),We=["curl","wget","invokewebrequest","invoke-restmethod","iwr","irm","nc","netcat"],ze=["env","processenv","apikey","api_key","token","secret","credential","credentials","awsaccesskey","awssecret"],Be=["authorizedkeys","sshknownhosts","crontab","launchctl","schtasks","startup","runkey","runonce","bashrc","profile"],He=/\bssh-(?:rsa|ed25519|ecdsa-[^\s]+)\s+[A-Za-z0-9+/=]{40,}/i;function Je(t){let e=[],o=[t.command??"",...t.args??[],...Object.keys(t.env??{}),...Object.values(t.env??{})].join(`
6
- `);if(He.test(o)&&e.push({code:"ioc_public_key",message:"configuration contains an inline SSH public key IOC"}),(t.type??(t.url?"http":"stdio"))!=="stdio"||!Ve(t.command))return e;let r=Ke(t.args??[]);if(!r)return e;let n=Qe(r);return w(n,Be)&&e.push({code:"persistence",message:"stdio shell command attempts a persistence write"}),w(n,We)&&w(n,ze)&&e.push({code:"dangerous_egress",message:"stdio shell command combines network egress with likely secret access"}),e}function Ve(t){if(!t)return!1;let e=d.basename(t).toLowerCase();return Fe.has(e)}function Ke(t){for(let e=0;e<t.length;e++){let o=t[e]?.toLowerCase();if(o&&Ge.has(o))return t.slice(e+1).join(" ")}return""}function Qe(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"")}function w(t,e){return e.some(o=>t.includes(o))}var et=[{name:"skills_list",description:"List AstraClaw skills active for the current workspace.",inputSchema:{type:"object",properties:{},additionalProperties:!1}},{name:"skill_view",description:"Read the full SKILL.md instructions for one AstraClaw skill.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Skill name from skills_list."}},required:["name"],additionalProperties:!1}},{name:"mcp_connectors_list",description:"List MCP connector tools installed in AstraClaw's Plugins page and shared with this external agent.",inputSchema:{type:"object",properties:{},additionalProperties:!1}},{name:"mcp_tool_call",description:"Call one AstraClaw shared MCP connector tool by toolName from mcp_connectors_list.",inputSchema:{type:"object",properties:{toolName:{type:"string",description:"Connector tool name, for example mcp__filesystem__read_text_file."},args:{type:"object",description:"Arguments for the connector tool."}},required:["toolName"],additionalProperties:!1}}],S=class{tools=new Map;findTool(e){return this.tools.get(e)}getToolManifest(){return Array.from(this.tools.values()).map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}}))}getToolNames(){return Array.from(this.tools.keys())}setTools(e){this.tools.clear(),this.addTools(e)}addTool(e){this.tools.set(e.name,e)}addTools(e){for(let o of e)this.addTool(o)}removeTool(e){return this.tools.delete(e)}},p=null,tt=Ye({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});tt.on("line",t=>{ot(t)});async function ot(t){let e=t.trim();if(!e)return;let o;try{o=JSON.parse(e)}catch{return}if(o.id===void 0||o.id===null)return o.method==="notifications/initialized",void 0;try{let r=await rt(o);K({jsonrpc:"2.0",id:o.id,result:r})}catch(r){K({jsonrpc:"2.0",id:o.id,error:{code:-32603,message:r instanceof Error?r.message:String(r)}})}}async function rt(t){switch(t.method){case"initialize":return{protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:j,version:"1.0.0"}};case"tools/list":return{tools:et};case"tools/call":{let e=V(t.params),o=typeof e.name=="string"?e.name:"",r=V(e.arguments),n=nt(),i=o==="mcp_connectors_list"||o==="mcp_tool_call"?await st(n):void 0,s=await L({tool:o,args:r,projectRoot:n,toolCatalog:i});if(!s.handled)throw new Error(`Unknown tool: ${o}`);return{content:[{type:"text",text:JSON.stringify(s.result)}]}}default:throw new Error(`Unknown method: ${t.method}`)}}function nt(){return process.env.ASTRACLAW_PROJECT_ROOT||process.env.QLOGICAGENT_PROJECT_ROOT||process.cwd()}async function st(t){if(p?.projectRoot===t)return await p.ready,p.catalog;p?.manager?.disconnectAll().catch(()=>{});let e=new S,o=new f({servers:it(),workspaceRoot:t,toolCatalog:e,log:{info:n=>process.stderr.write(`${n}
2
+ import{createInterface as Ke}from"node:readline";import{existsSync as Qe,readFileSync as Ye}from"node:fs";import{readFileSync as ye}from"node:fs";import{randomUUID as ve}from"node:crypto";import{readdirSync as Tt,readFileSync as kt,statSync as re,writeFileSync as Pt}from"node:fs";import{readdir as oe,readFile as ne,stat as se,writeFile as ie}from"node:fs/promises";import{join as d}from"node:path";import{homedir as Q}from"node:os";import{join as u,resolve as at}from"node:path";import{existsSync as ct}from"node:fs";import{createHash as dt}from"node:crypto";var P=".qlogicagent";function p(){return process.env.QLOGICAGENT_HOME||u(Q(),P)}function v(){return u(p(),"skills")}function _(){return u(p(),"mcp.json")}function Y(t){if(!t)throw new Error("getProjectAgentDir: cwd is required (must not fall back to process.cwd())");return u(t,P)}function C(t){return u(Y(t),"skills-disabled.json")}import{readFileSync as Z,writeFileSync as ft,mkdirSync as gt,renameSync as ht}from"node:fs";import{dirname as vt,join as X}from"node:path";function f(){return{version:1,disabled:[]}}function ee(t){let e;try{e=Z(t,"utf8")}catch(n){return n.code==="ENOENT"?{list:f(),corrupt:!1}:(console.error(`[project-skill-manifest] Cannot read skill mute list at ${t} (${n instanceof Error?n.message:String(n)}); treating it as empty for reads \u2014 muted skills may reactivate.`),{list:f(),corrupt:!0})}let r;try{r=JSON.parse(e)}catch(n){return console.error(`[project-skill-manifest] Skill mute list at ${t} is corrupted (${n instanceof Error?n.message:String(n)}); treating it as empty for reads \u2014 muted skills may reactivate.`),{list:f(),corrupt:!0}}return!r||typeof r!="object"||!Array.isArray(r.disabled)?(console.error(`[project-skill-manifest] Skill mute list at ${t} has an unexpected shape; treating it as empty for reads \u2014 muted skills may reactivate.`),{list:f(),corrupt:!0}):{list:{version:1,disabled:[...new Set(r.disabled.filter(n=>typeof n=="string"&&n.trim().length>0))]},corrupt:!1}}function x(t){return ee(t).list}function te(){return X(p(),"skills-disabled.json")}function A(){return new Set(x(te()).disabled)}function R(t){return new Set(x(C(t)).disabled)}var ae=["auto-skill-","test-skill-"],le=".skills_prompt_snapshot.json";function ce(t){return ae.some(e=>t.startsWith(e))}function ue(t){let e=t.replace(/\r\n/g,`
3
+ `),r=e.match(/^---\n[\s\S]*?^version:\s*(\S+)/m),o=e.match(/^---\n[\s\S]*?^category:\s*(.+)/m),n=e.match(/^---\n[\s\S]*?^author:\s*(.+)/m),i=e.match(/^---\n[\s\S]*?^requires:\s*(.+)/m),s=e.match(/^---\n[\s\S]*?^environments:\s*(.+)/m),a=e.match(/^---\n([\s\S]*?)\n---/)?.[1]??"";return{version:r?.[1],description:de(a),category:o?.[1]?.trim()||void 0,author:n?.[1]?.trim()||void 0,requiredTools:M(i?.[1]),environments:M(s?.[1])}}function de(t){let e=t.split(`
4
+ `),r=e.findIndex(s=>/^description:/.test(s));if(r===-1)return;let o=e[r].replace(/^description:[ \t]*/,"").trim(),n=/^[>|][+-]?$/.test(o),i=[];!n&&o&&i.push(o);for(let s=r+1;s<e.length;s++){let a=e[s];if(!/^[ \t]/.test(a))break;let l=a.trim();l&&i.push(l)}if(i.length!==0)return i.join(" ").replace(/^["']|["']$/g,"").trim()||void 0}var E=new Map,S=new Map;function me(t,e,r,o){let n=e.has(t.name),i=r.has(t.name),s=!ge(t.meta,o);return{name:t.name,filePath:t.filePath,baseDir:t.baseDir,globallyDisabled:n,projectDisabled:i,active:!n&&!i&&!s,systemGenerated:t.systemGenerated,description:t.meta.description,version:t.meta.version,category:t.meta.category,author:t.meta.author,requiredTools:t.meta.requiredTools,environments:t.meta.environments}}async function pe(t){let e;try{e=await oe(t,{withFileTypes:!0})}catch{e=[]}let r=[];for(let s of e){if(!s.isDirectory()||s.name.startsWith("."))continue;let a=d(t,s.name),l=d(a,"SKILL.md");try{let y=await se(l);if(!y.isFile())continue;r.push({name:s.name,filePath:l,baseDir:a,mtimeMs:y.mtimeMs,size:y.size})}catch{continue}}r.sort((s,a)=>s.name.localeCompare(a.name));let o=r.map(s=>`${s.name}:${s.mtimeMs}:${s.size}`).join("|"),n=E.get(t);if(n&&n.fingerprint===o)return n.raw;let i=[];for(let s of r){let a;try{a=await ne(s.filePath,"utf8")}catch{continue}i.push({name:s.name,filePath:s.filePath,baseDir:s.baseDir,systemGenerated:ce(s.name),mtimeMs:s.mtimeMs,size:s.size,meta:ue(a)})}return E.set(t,{fingerprint:o,raw:i}),he(t,i),i}async function fe(t,e){let r=v(),o=A(),n=t?R(t):new Set,i=S.get(r);return i||(i=pe(r).finally(()=>S.delete(r)),S.set(r,i)),(await i).map(a=>me(a,o,n,e))}async function D(t,e){return(await fe(t,e)).filter(r=>r.active)}function j(t){let e=v(),r=d(e,t),o=d(r,"SKILL.md");try{if(re(o).isFile())return{baseDir:r,filePath:o}}catch{}return null}function M(t){if(!t)return;let e=t.replace(/^\[|\]$/g,"").split(/[,\s]+/).map(r=>r.replace(/^["']|["']$/g,"").trim()).filter(Boolean);return e.length>0?e:void 0}function ge(t,e){if(t.environments&&e?.currentEnvironment&&!t.environments.includes(e.currentEnvironment))return!1;if(t.requiredTools){if(!e?.availableToolNames)return!1;let r=new Set(e.availableToolNames);return t.requiredTools.every(o=>r.has(o))}return!0}async function he(t,e){try{let o={version:1,entries:e.map(n=>({name:n.name,size:n.size,mtimeMs:n.mtimeMs,description:n.meta.description,version:n.meta.version,requiredTools:n.meta.requiredTools,environments:n.meta.environments}))};await ie(d(t,le),JSON.stringify(o,null,2),"utf8")}catch{}}var I="astraclaw_capabilities";async function L(t){if(t.tool==="skills_list")return{handled:!0,result:{skills:(await D(t.projectRoot,{availableToolNames:t.availableToolNames,currentEnvironment:t.currentEnvironment??process.platform})).map(Se)}};if(t.tool==="skill_view"){let e=typeof t.args.name=="string"?t.args.name.trim():"";if(!e)throw new Error("skill_view requires a skill name");let r=j(e);if(!r)throw new Error(`Skill not found: ${e}`);return{handled:!0,result:{name:e,content:ye(r.filePath,"utf8")}}}if(t.tool==="mcp_connectors_list"){let e=t.mcpServerFailures??[],r=e.length>0?{failedServers:e,note:`${e.length} configured MCP server(s) are unavailable this session; their tools are missing from this list.`}:{};if(!t.toolCatalog)return{handled:!0,result:{tools:[],note:"AstraClaw MCP connector catalog is not attached to this capability server instance.",...e.length>0?{failedServers:e}:{}}};let o=t.toolCatalog.getToolManifest().filter(n=>n.function.name.startsWith("mcp__")).map(n=>({toolName:n.function.name,server:we(n.function.name),name:Te(n.function.name),description:n.function.description,inputSchema:n.function.parameters}));return{handled:!0,result:{tools:o,count:o.length,...r}}}if(t.tool==="mcp_tool_call"){if(!t.toolCatalog)throw new Error("AstraClaw MCP connector catalog is not attached");let e=typeof t.args.toolName=="string"?t.args.toolName.trim():"";if(!e.startsWith("mcp__"))throw new Error("mcp_tool_call requires a connector toolName returned by mcp_connectors_list");let r=t.toolCatalog.findTool(e);if(!r?.execute)throw new Error(`MCP connector tool not found or not executable: ${e}`);let o=be(t.args.args),n=`astraclaw_mcp_${ve().slice(0,8)}`,i=await r.execute(n,o);return{handled:!0,result:{toolName:e,content:i.content,details:i.details,imageUrls:i.imageUrls}}}return{handled:!1}}function Se(t){return{name:t.name,description:t.description,version:t.version,category:t.category,requiredTools:t.requiredTools,environments:t.environments}}function be(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function we(t){let e=t.split("__");return e.length>=3?e[1]??"":""}function Te(t){let e=t.split("__");return e.length>=3?e.slice(2).join("__"):t}import m from"node:path";import{fileURLToPath as xe}from"node:url";import{createRuntime as Ae}from"mcporter";var O=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),ke=new Set([...O,"agent"]);function $(t){return t?.riskLevel?t.riskLevel:t?.isDangerous?"system":t?.isReadOnly?"read":t?.isEgress?"external_egress":"write"}var b=class{toolPool=new Map;setTools(e){this.toolPool.clear();for(let r of e)this.toolPool.set(r.name,r)}addTool(e){this.toolPool.set(e.name,e)}addTools(e){for(let r of e)this.addTool(r)}removeTool(e){return this.toolPool.delete(e)}findTool(e){return this.toolPool.get(e)}hasTool(e){return this.toolPool.has(e)}getToolNames(){return Array.from(this.toolPool.keys())}getToolCount(){return this.toolPool.size}async executeTool(e,r,o,n){let i=this.toolPool.get(e);if(!i)throw new Error(`Tool not found: ${e}`);return i.execute(r,o,n)}getTools(){return Array.from(this.toolPool.values()).filter(e=>e.isEnabled?.()!==!1)}getToolManifest(){let e=[];for(let r of this.toolPool.values()){if(r.isEnabled?.()===!1)continue;let o=$(r);e.push({type:"function",function:{name:r.name,description:r.description,parameters:r.parameters},meta:{category:r.category??"other",displayName:r.displayName??{key:`capability.tool.${r.name}.name`,fallback:r.label},displayDescription:r.displayDescription??{key:`capability.tool.${r.name}.description`,fallback:""},parallelSafe:r.isConcurrencySafe??!1,riskLevel:o,isReadOnly:o==="read",isDangerous:o==="system",isDelete:r.isDelete??!1,isEgress:r.isEgress??o==="external_egress",egressCarriesData:r.egressCarriesData??!1}})}return e}},N=new b;function F(t){N.addTools(t)}function U(t){return N.removeTool(t)}var Pe=new Set(["describe","fetch","find","get","inspect","list","query","read","search","stat"]),_e=new Set(["append","copy","create","delete","edit","move","patch","remove","rename","set","update","upload","write"]);function q(t){let e=t.annotations,r=Ce(t.name),o=r.some(l=>_e.has(l)),n=r.some(l=>Pe.has(l)),i=e?.destructiveHint===!0||o,s=e?.readOnlyHint===!0||!i&&n,a=s||e?.idempotentHint===!0&&!i;return{isReadOnly:s,isConcurrencySafe:a,isDestructive:i}}function Ce(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}var Re=12e4,g=3,Ee=1e3;async function Me(t,e){let r=e.sleep??(i=>new Promise(s=>setTimeout(s,i))),o=Math.max(1,e.attempts),n;for(let i=1;i<=o;i++)try{return await t()}catch(s){n=s,i<o&&(e.onRetry?.(i,s),await r(e.baseDelayMs*i))}throw n}var h=class{runtime=null;definitions=[];toolsByServer=new Map;injectedNames=new Set;log;workspaceRoot;toolCatalog;serverToolFilters=new Map;serverOAuth=new Map;failedServers=new Map;constructor(e){this.log=e.log??{info:()=>{},warn:()=>{}},this.workspaceRoot=e.workspaceRoot?m.resolve(e.workspaceRoot):void 0,this.toolCatalog=e.toolCatalog,this.definitions=e.servers.filter(r=>!r.disabled).filter(r=>{let o=Be(r);for(let n of o)this.log.warn(`[mcp] rejected server "${r.name}": ${n.message}`);return r.tools&&this.serverToolFilters.set(r.name,r.tools),r.oauth===!0&&this.serverOAuth.set(r.name,!0),o.length===0}).map(r=>this.toServerDefinition(r)).filter(r=>r!==null)}markServerFailed(e,r,o){this.failedServers.set(e,{name:e,phase:r,error:o}),console.error(`[mcp] server "${e}" unavailable this session (${r}): ${o}`)}toServerDefinition(e){if((e.type??(e.url?"http":"stdio"))==="http"){if(!e.url)return this.log.warn(`[mcp] server "${e.name}" is type "http" but has no url, skipping`),this.markServerFailed(e.name,"config",'type "http" but no url'),null;let o;try{o=new URL(e.url)}catch{return this.log.warn(`[mcp] server "${e.name}" has an invalid url "${e.url}", skipping`),this.markServerFailed(e.name,"config",`invalid url "${e.url}"`),null}return{name:e.name,command:{kind:"http",url:o,headers:e.headers}}}return e.command?{name:e.name,command:{kind:"stdio",command:e.command,args:e.args??[],cwd:e.cwd??this.workspaceRoot??process.cwd()},env:e.env}:(this.log.warn(`[mcp] server "${e.name}" is type "stdio" but has no command, skipping`),this.markServerFailed(e.name,"config",'type "stdio" but no command'),null)}async connectAll(){this.definitions.length!==0&&(this.runtime=await Ae({servers:this.definitions,clientInfo:{name:"qlogicagent",version:"1.0.0"},logger:{info:e=>this.log.info(`[mcp] ${e}`),warn:e=>this.log.warn(`[mcp] ${e}`),error:(e,r)=>this.log.warn(`[mcp] ${e}${r?` (${r instanceof Error?r.message:String(r)})`:""}`),debug:()=>{}}}),await Promise.allSettled(this.definitions.map(async e=>{try{let r=await Me(()=>this.runtime.listTools(e.name,{includeSchema:!0,disableOAuth:this.serverOAuth.get(e.name)!==!0}),{attempts:g,baseDelayMs:Ee,onRetry:(n,i)=>this.log.warn(`[mcp] connect attempt ${n}/${g} for ${e.name} failed, retrying: ${i instanceof Error?i.message:i}`)}),o=z(r,this.serverToolFilters.get(e.name));this.toolsByServer.set(e.name,o),this.failedServers.delete(e.name),this.log.info(`[mcp] connected to ${e.name} (${o.length}/${r.length} tools)`)}catch(r){this.log.warn(`[mcp] failed to connect to ${e.name} after ${g} attempts: ${r instanceof Error?r.message:r}`),this.markServerFailed(e.name,"connect",`${r instanceof Error?r.message:String(r)} (after ${g} attempts)`)}})))}injectTools(){for(let[e,r]of this.toolsByServer){let o=this.injectPortableTools(e,r);this.log.info(`[mcp] injected ${o.length} tools from ${e}`)}}async refreshServerTools(e){if(!this.runtime)throw new Error("MCP runtime is not connected");let r=await this.runtime.listTools(e,{includeSchema:!0,disableOAuth:this.serverOAuth.get(e)!==!0}),o=z(r,this.serverToolFilters.get(e));return this.toolsByServer.set(e,o),this.failedServers.delete(e),this.retractServerTools(e),this.injectPortableTools(e,o),o.length}getConnectedServers(){return Array.from(this.toolsByServer.keys())}getFailedServers(){return Array.from(this.failedServers.values())}getToolCount(){let e=0;for(let r of this.toolsByServer.values())e+=r.length;return e}async disconnectAll(){for(let r of this.injectedNames)this.removeRegisteredTool(r);this.injectedNames.clear(),this.toolsByServer.clear(),this.failedServers.clear();let e=this.runtime;if(this.runtime=null,e)try{await e.close()}catch{}}toPortableTool(e,r){let o=q({name:r.name,description:r.description});return{name:`mcp__${G(e)}__${r.name}`,label:`[${e}] ${r.name}`,category:"mcp",description:r.description??`MCP tool from ${e}`,parameters:r.inputSchema??{type:"object",properties:{}},isConcurrencySafe:o.isConcurrencySafe,isReadOnly:o.isReadOnly,isDestructive:o.isDestructive,searchHint:`mcp ${e} ${r.name.replace(/[_-]+/g," ")}`,execute:async(n,i)=>{let s=this.runtime;if(!s)return{content:[{type:"text",text:`MCP server "${e}" is not connected.`}],details:{error:"mcp_not_connected"}};try{let a=await s.callTool(e,r.name,{args:i,timeoutMs:Re});return De(a)}catch(a){let l=a instanceof Error?a.message:String(a);return{content:[{type:"text",text:`MCP tool error: ${l}`}],details:{error:l}}}}}}wrapToolsForWorkspaceBoundary(e){return this.workspaceRoot?e.map(r=>{if(!r.execute)return r;let o=r.execute;return{...r,execute:async(n,i,s)=>{let a=Ie(r.name,i,this.workspaceRoot);return a?{content:[{type:"text",text:a}],details:{type:"mcp",error:"workspace_boundary"}}:o(n,i,s)}}}):e}injectPortableTools(e,r){let o=this.wrapToolsForWorkspaceBoundary(r.map(n=>this.toPortableTool(e,n)));this.registerTools(o);for(let n of o)this.injectedNames.add(n.name);return o}retractServerTools(e){let r=`mcp__${G(e)}__`;for(let o of[...this.injectedNames])o.startsWith(r)&&(this.removeRegisteredTool(o),this.injectedNames.delete(o))}registerTools(e){this.toolCatalog?this.toolCatalog.addTools(e):F(e)}removeRegisteredTool(e){return this.toolCatalog?.removeTool(e)??U(e)}};function De(t){let e=t&&typeof t=="object"?t:{},o=(Array.isArray(e.content)?e.content:[]).filter(a=>!!a&&typeof a=="object"),n=o.filter(a=>a.type==="text"&&typeof a.text=="string").map(a=>a.text),i=o.filter(a=>!(a.type==="text"&&typeof a.text=="string")).map(a=>typeof a.type=="string"&&a.type?a.type:"unknown"),s=n.join(`
5
+ `);if(i.length>0){let a=[...new Set(i)].join(", ");s=s?`${s}
6
+
7
+ [${i.length} non-text blocks omitted: ${a}]`:`[output contains only non-text blocks: ${a}]`}return{content:[{type:"text",text:s||"(no text output)"}],...e.isError?{details:{error:"mcp_tool_error"}}:{}}}function G(t){return t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var je=/(?:^|_)(path|paths|file|files|filename|filenames|dir|dirs|directory|directories|folder|folders|cwd|root|uri)(?:$|_)/i;function Ie(t,e,r){if(!r)return null;for(let o of T(e)){let n=$e(o.value,r);if(n&&!Ne(n.candidate,n.root,n.pathApi))return`Blocked: MCP tool "${t}" path "${o.value}" is outside the workspace boundary "${n.root}"`}return null}function T(t,e="",r=0){if(r>8)return[];if(typeof t=="string")return Le(e,t)?[{key:e,value:t}]:[];if(Array.isArray(t))return t.flatMap(n=>T(n,e,r+1));if(!t||typeof t!="object")return[];let o=[];for(let[n,i]of Object.entries(t))o.push(...T(i,n,r+1));return o}function Le(t,e){if(!je.test(t))return!1;let r=e.trim();return!r||/^https?:\/\//i.test(r)?!1:Oe(r)}function Oe(t){return m.isAbsolute(t)||/^[A-Za-z]:[\\/]/.test(t)||/^\\\\/.test(t)||/^file:\/\//i.test(t)||t.includes("../")||t.includes("..\\")||t.startsWith(".\\")||t.startsWith("./")||t.includes("/")||t.includes("\\")}function $e(t,e){let r=t.trim();if(/^file:\/\//i.test(r))try{r=xe(r)}catch{return null}let o=W(r)||W(e)?m.win32:m,n=o.resolve(e);return{candidate:o.isAbsolute(r)?o.resolve(r):o.resolve(n,r),root:n,pathApi:o}}function Ne(t,e,r){let o=r.relative(e,t);return o===""||!o.startsWith("..")&&!r.isAbsolute(o)}function W(t){return/^[A-Za-z]:[\\/]/.test(t)||/^\\\\/.test(t)}function J(t){if(!t||typeof t!="object")return[];let e=t,r=[],o=e.mcpServers??e.servers??e;for(let[n,i]of Object.entries(o)){if(!i||typeof i!="object")continue;let s=i;if(typeof s.url=="string"){r.push({name:n,type:"http",url:s.url,headers:s.headers&&typeof s.headers=="object"?s.headers:void 0,disabled:s.disabled===!0,oauth:s.oauth===!0,tools:B(s.tools)});continue}typeof s.command=="string"&&r.push({name:n,type:"stdio",command:s.command,args:Array.isArray(s.args)?s.args:void 0,env:s.env&&typeof s.env=="object"?s.env:void 0,cwd:typeof s.cwd=="string"?s.cwd:void 0,disabled:s.disabled===!0,oauth:s.oauth===!0,tools:B(s.tools)})}return r}function z(t,e){let r=new Set(e?.include??[]),o=new Set(e?.exclude??[]);return t.filter(n=>r.size>0&&!r.has(n.name)?!1:!o.has(n.name))}function B(t){if(!t||typeof t!="object")return;let e=t,r=H(e.include),o=H(e.exclude);if(!(!r&&!o))return{...r?{include:r}:{},...o?{exclude:o}:{}}}function H(t){if(!Array.isArray(t))return;let e=t.filter(r=>typeof r=="string"&&r.trim().length>0);return e.length>0?e:void 0}var Fe=new Set(["bash","sh","zsh","fish","cmd","cmd.exe","powershell","powershell.exe","pwsh","pwsh.exe"]),Ue=new Set(["-c","/c","-command","-encodedcommand","-e"]),qe=["curl","wget","invokewebrequest","invoke-restmethod","iwr","irm","nc","netcat"],Ge=["env","processenv","apikey","api_key","token","secret","credential","credentials","awsaccesskey","awssecret"],We=["authorizedkeys","sshknownhosts","crontab","launchctl","schtasks","startup","runkey","runonce","bashrc","profile"],ze=/\bssh-(?:rsa|ed25519|ecdsa-[^\s]+)\s+[A-Za-z0-9+/=]{40,}/i;function Be(t){let e=[],r=[t.command??"",...t.args??[],...Object.keys(t.env??{}),...Object.values(t.env??{})].join(`
8
+ `);if(ze.test(r)&&e.push({code:"ioc_public_key",message:"configuration contains an inline SSH public key IOC"}),(t.type??(t.url?"http":"stdio"))!=="stdio"||!He(t.command))return e;let o=Je(t.args??[]);if(!o)return e;let n=Ve(o);return w(n,We)&&e.push({code:"persistence",message:"stdio shell command attempts a persistence write"}),w(n,qe)&&w(n,Ge)&&e.push({code:"dangerous_egress",message:"stdio shell command combines network egress with likely secret access"}),e}function He(t){if(!t)return!1;let e=m.basename(t).toLowerCase();return Fe.has(e)}function Je(t){for(let e=0;e<t.length;e++){let r=t[e]?.toLowerCase();if(r&&Ue.has(r))return t.slice(e+1).join(" ")}return""}function Ve(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"")}function w(t,e){return e.some(r=>t.includes(r))}var Ze=[{name:"skills_list",description:"List AstraClaw skills active for the current workspace.",inputSchema:{type:"object",properties:{},additionalProperties:!1}},{name:"skill_view",description:"Read the full SKILL.md instructions for one AstraClaw skill.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Skill name from skills_list."}},required:["name"],additionalProperties:!1}},{name:"mcp_connectors_list",description:"List MCP connector tools installed in AstraClaw's Plugins page and shared with this external agent.",inputSchema:{type:"object",properties:{},additionalProperties:!1}},{name:"mcp_tool_call",description:"Call one AstraClaw shared MCP connector tool by toolName from mcp_connectors_list.",inputSchema:{type:"object",properties:{toolName:{type:"string",description:"Connector tool name, for example mcp__filesystem__read_text_file."},args:{type:"object",description:"Arguments for the connector tool."}},required:["toolName"],additionalProperties:!1}}],k=class{tools=new Map;findTool(e){return this.tools.get(e)}getToolManifest(){return Array.from(this.tools.values()).map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}}))}getToolNames(){return Array.from(this.tools.keys())}setTools(e){this.tools.clear(),this.addTools(e)}addTool(e){this.tools.set(e.name,e)}addTools(e){for(let r of e)this.addTool(r)}removeTool(e){return this.tools.delete(e)}},c=null,Xe=Ke({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});Xe.on("line",t=>{et(t)});async function et(t){let e=t.trim();if(!e)return;let r;try{r=JSON.parse(e)}catch{return}if(r.id===void 0||r.id===null)return r.method==="notifications/initialized",void 0;try{let o=await tt(r);K({jsonrpc:"2.0",id:r.id,result:o})}catch(o){K({jsonrpc:"2.0",id:r.id,error:{code:-32603,message:o instanceof Error?o.message:String(o)}})}}async function tt(t){switch(t.method){case"initialize":return{protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:I,version:"1.0.0"}};case"tools/list":return{tools:Ze};case"tools/call":{let e=V(t.params),r=typeof e.name=="string"?e.name:"",o=V(e.arguments),n=rt(),i=r==="mcp_connectors_list"||r==="mcp_tool_call"?await ot(n):void 0,s=await L({tool:r,args:o,projectRoot:n,toolCatalog:i,mcpServerFailures:i?c?.manager?.getFailedServers():void 0});if(!s.handled)throw new Error(`Unknown tool: ${r}`);return{content:[{type:"text",text:JSON.stringify(s.result)}]}}default:throw new Error(`Unknown method: ${t.method}`)}}function rt(){return process.env.ASTRACLAW_PROJECT_ROOT||process.env.QLOGICAGENT_PROJECT_ROOT||process.cwd()}async function ot(t){if(c?.projectRoot===t)return await c.ready,c.catalog;c?.manager?.disconnectAll().catch(()=>{});let e=new k,r=new h({servers:nt(),workspaceRoot:t,toolCatalog:e,log:{info:n=>process.stderr.write(`${n}
7
9
  `),warn:n=>process.stderr.write(`${n}
8
- `)}}),r=o.connectAll().then(()=>o.injectTools());return p={projectRoot:t,catalog:e,manager:o,ready:r},await r,e}function it(){let t=process.env.ASTRACLAW_MCP_CONFIG_PATH||P();if(!Ze(t))return[];try{let e=Xe(t,"utf8").replace(/^\uFEFF/,"");return J(JSON.parse(e))}catch(e){return process.stderr.write(`[astraclaw-native-mcp] failed to read MCP config: ${e instanceof Error?e.message:String(e)}
10
+ `)}}),o=r.connectAll().then(()=>r.injectTools());return c={projectRoot:t,catalog:e,manager:r,ready:o},await o,e}function nt(){let t=process.env.ASTRACLAW_MCP_CONFIG_PATH||_();if(!Qe(t))return[];try{let e=Ye(t,"utf8").replace(/^\uFEFF/,"");return J(JSON.parse(e))}catch(e){return process.stderr.write(`[astraclaw-native-mcp] failed to read MCP config: ${e instanceof Error?e.message:String(e)}
9
11
  `),[]}}function V(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function K(t){process.stdout.write(`${JSON.stringify(t)}
10
12
  `)}
@@ -28,7 +28,8 @@ export interface RecallMemoriesDeps {
28
28
  }
29
29
  /**
30
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
31
+ * to inject. Always fires `memory.after_recall` (with the real injected/dropped
32
+ * split — a pre-cap count would misreport what the model actually sees) when the
32
33
  * recall hook runs. Returns null when there is nothing worth injecting.
33
34
  */
34
35
  export declare function recallMemoriesForTurn(deps: RecallMemoriesDeps): Promise<string | null>;