qlogicagent 2.15.10 → 2.16.1

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 (56) hide show
  1. package/dist/agent.js +24 -20
  2. package/dist/cli.js +572 -515
  3. package/dist/index.js +571 -514
  4. package/dist/orchestration.js +9 -9
  5. package/dist/protocol.js +1 -1
  6. package/dist/types/agent/tool-loop/artifact-final-contract.d.ts +21 -0
  7. package/dist/types/agent/tool-loop/tool-failure-policy.d.ts +1 -0
  8. package/dist/types/agent/tool-loop.d.ts +2 -0
  9. package/dist/types/agent/types.d.ts +7 -202
  10. package/dist/types/cli/acp-extended-handlers.d.ts +1 -0
  11. package/dist/types/cli/core-tools/agent-tool-service.d.ts +1 -0
  12. package/dist/types/cli/handlers/agents-handler.d.ts +8 -0
  13. package/dist/types/cli/handlers/product-handler.d.ts +21 -2
  14. package/dist/types/cli/handlers/workflow-handler.d.ts +5 -0
  15. package/dist/types/cli/tool-bootstrap-core-registration.d.ts +5 -0
  16. package/dist/types/cli/turn-core.d.ts +2 -0
  17. package/dist/types/contracts/index.d.ts +1 -0
  18. package/dist/types/contracts/turn-event.d.ts +235 -0
  19. package/dist/types/orchestration/agent-instance.d.ts +45 -2
  20. package/dist/types/orchestration/agent-roster.d.ts +17 -0
  21. package/dist/types/orchestration/dag-scheduler.d.ts +27 -0
  22. package/dist/types/orchestration/product-budget.d.ts +7 -1
  23. package/dist/types/orchestration/product-persistence.d.ts +31 -0
  24. package/dist/types/orchestration/product-planner.d.ts +123 -0
  25. package/dist/types/orchestration/product-run-coordinator.d.ts +17 -1
  26. package/dist/types/orchestration/product-worktree.d.ts +3 -0
  27. package/dist/types/orchestration/skill-improvement.d.ts +2 -19
  28. package/dist/types/orchestration/solo-evaluator.d.ts +10 -0
  29. package/dist/types/orchestration/solo-spec-builder.d.ts +4 -0
  30. package/dist/types/orchestration/workflow/n8n-import.d.ts +26 -32
  31. package/dist/types/orchestration/workflow/n8n-template-compat.d.ts +5 -0
  32. package/dist/types/orchestration/workflow/node-registry.d.ts +13 -0
  33. package/dist/types/orchestration/workflow/node-schema.d.ts +10 -0
  34. package/dist/types/orchestration/workflow/qla-executor-host.d.ts +7 -1
  35. package/dist/types/protocol/methods.d.ts +8 -1
  36. package/dist/types/protocol/notifications.d.ts +1 -1
  37. package/dist/types/protocol/wire/acp-agent-management.d.ts +38 -0
  38. package/dist/types/protocol/wire/acp-protocol.d.ts +1 -0
  39. package/dist/types/protocol/wire/agent-events.d.ts +3 -3
  40. package/dist/types/protocol/wire/agent-methods.d.ts +11 -1
  41. package/dist/types/protocol/wire/index.d.ts +1 -1
  42. package/dist/types/protocol/wire/notification-payloads.d.ts +39 -0
  43. package/dist/types/runtime/infra/acp-detector.d.ts +3 -0
  44. package/dist/types/runtime/infra/acp-protocol-adapter.d.ts +9 -0
  45. package/dist/types/runtime/ports/agent-execution-contracts.d.ts +2 -199
  46. package/dist/types/runtime/ports/tool-contracts.d.ts +6 -0
  47. package/dist/types/runtime/prompt/environment-context.d.ts +20 -1
  48. package/dist/types/skills/tools/ask-user-tool.d.ts +4 -2
  49. package/dist/types/skills/tools/shell/command-classification.d.ts +1 -0
  50. package/dist/types/skills/tools/tool-search-tool.d.ts +13 -0
  51. package/dist/types/skills/tools/tool-selection-eval.d.ts +49 -0
  52. package/dist/types/skills/tools/tool-selection-eval.dataset.d.ts +5 -0
  53. package/dist/types/skills/tools/write-tool.d.ts +2 -0
  54. package/dist/types/skills/tools.d.ts +21 -0
  55. package/dist/types/transport/acp-server.d.ts +1 -0
  56. package/package.json +2 -1
@@ -1,4 +1,4 @@
1
- function Ae(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Me(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var Ee=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,y={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Ie=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,ve=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Le=512,Oe=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var we=new Set([500,502,503,504,521,522,523,524,529]),Pe=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ne=["upgrade your plan","upgrade plan","current plan","subscription"],De=["daily","weekly","monthly"],Fe=["try again","retry","temporary","cooldown"],Be=["usage limit","rate limit","organization usage"],Ue=["organization","workspace"],je=["billing period","exceeded","reached","exhausted"],Ge=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,He=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function h(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function $e(e){return h(e,y.format)}function W(e){return h(e,y.rateLimit)}function ze(e){return h(e,y.timeout)}function qe(e){return Ee.test(e)}function E(e){let t=e.toLowerCase();return t?e.length>Le?ve.test(t):h(t,y.billing)?!0:Ie.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function V(e){return h(e,y.authPermanent)}function Ke(e){return h(e,y.auth)}function J(e){return h(e,y.overloaded)}function T(e,t){return t.some(n=>e.includes(n))}function Xe(e){return T(e,Pe)||T(e,Ne)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ye(e){let t=T(e,De),n=e.includes("spend limit")||e.includes("spending limit"),o=T(e,Ue);return T(e,Fe)&&T(e,Be)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||T(e,je))}function We(e){return e.trim().toLowerCase().replace(He,"").trim()}function Z(e){let t=We(e);return!t||Xe(t)?"billing":W(t)||Ye(t)?"rate_limit":"billing"}function Ve(e){return Ge.test(e)?Z(e):null}function Q(e){let t=e.match(Oe);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Je(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Ze(e){let t=e.trim();if(!t)return!1;let n=Q(t);return n?we.has(n.code):!1}function ee(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?Z(t):"billing":e===429?"rate_limit":e===401||e===403?t&&V(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&J(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&E(t)?"billing":"format":null}function Qe(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function et(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function te(e){if(et(e))return"session_expired";if(Qe(e))return"model_not_found";let t=Ve(e);return t||(qe(e)?E(e)?"billing":"rate_limit":W(e)?"rate_limit":J(e)?"overloaded":Ze(e)?Q(e.trim())?.code===529?"overloaded":"timeout":Je(e)?"timeout":$e(e)?"format":E(e)?"billing":ze(e)?"timeout":V(e)?"auth_permanent":Ke(e)?"auth":null)}var tt={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"},nt=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ot(e,t){let n=ee(e,t)??(t?te(t):null);return n?tt[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function rt(e){return nt.has(e)}function B(e){return typeof e.compressAsync=="function"}var ne=4,I=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let u of t)u.role==="system"?o.push(u):r.push(u);let s=n;for(let u of o)s-=this.estimateTokens(u);let i;for(let u of r)if(u.role==="user"){i=u;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 u=r.length-1;u>=0;u--){let d=r[u];if(d===i)continue;let p=this.estimateTokens(d);if(s-p<0&&l>=ne)break;if(s-p<0&&l<ne){a.unshift(d),l++;continue}s-=p,a.unshift(d),l++}let c=[...o];return i&&!a.includes(i)&&c.push(i),c.push(...a),{messages:c,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]
1
+ function Ae(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Me(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var Ee=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,y={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Ie=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,ve=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Le=512,Oe=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var we=new Set([500,502,503,504,521,522,523,524,529]),Pe=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ne=["upgrade your plan","upgrade plan","current plan","subscription"],De=["daily","weekly","monthly"],Fe=["try again","retry","temporary","cooldown"],Be=["usage limit","rate limit","organization usage"],Ue=["organization","workspace"],je=["billing period","exceeded","reached","exhausted"],Ge=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,He=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function h(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function $e(e){return h(e,y.format)}function V(e){return h(e,y.rateLimit)}function ze(e){return h(e,y.timeout)}function qe(e){return Ee.test(e)}function E(e){let t=e.toLowerCase();return t?e.length>Le?ve.test(t):h(t,y.billing)?!0:Ie.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function J(e){return h(e,y.authPermanent)}function Ke(e){return h(e,y.auth)}function Z(e){return h(e,y.overloaded)}function T(e,t){return t.some(n=>e.includes(n))}function Xe(e){return T(e,Pe)||T(e,Ne)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ye(e){let t=T(e,De),n=e.includes("spend limit")||e.includes("spending limit"),o=T(e,Ue);return T(e,Fe)&&T(e,Be)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||T(e,je))}function We(e){return e.trim().toLowerCase().replace(He,"").trim()}function Q(e){let t=We(e);return!t||Xe(t)?"billing":V(t)||Ye(t)?"rate_limit":"billing"}function Ve(e){return Ge.test(e)?Q(e):null}function ee(e){let t=e.match(Oe);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Je(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Ze(e){let t=e.trim();if(!t)return!1;let n=ee(t);return n?we.has(n.code):!1}function te(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?Q(t):"billing":e===429?"rate_limit":e===401||e===403?t&&J(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&Z(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&E(t)?"billing":"format":null}function Qe(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function et(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function ne(e){if(et(e))return"session_expired";if(Qe(e))return"model_not_found";let t=Ve(e);return t||(qe(e)?E(e)?"billing":"rate_limit":V(e)?"rate_limit":Z(e)?"overloaded":Ze(e)?ee(e.trim())?.code===529?"overloaded":"timeout":Je(e)?"timeout":$e(e)?"format":E(e)?"billing":ze(e)?"timeout":J(e)?"auth_permanent":Ke(e)?"auth":null)}var tt={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"},nt=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ot(e,t){let n=te(e,t)??(t?ne(t):null);return n?tt[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function rt(e){return nt.has(e)}function B(e){return typeof e.compressAsync=="function"}var oe=4,I=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let u of t)u.role==="system"?o.push(u):r.push(u);let s=n;for(let u of o)s-=this.estimateTokens(u);let i;for(let u of r)if(u.role==="user"){i=u;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 u=r.length-1;u>=0;u--){let d=r[u];if(d===i)continue;let p=this.estimateTokens(d);if(s-p<0&&l>=oe)break;if(s-p<0&&l<oe){a.unshift(d),l++;continue}s-=p,a.unshift(d),l++}let c=[...o];return i&&!a.includes(i)&&c.push(i),c.push(...a),{messages:c,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
2
  ${a}`},...i],droppedCount:s.length,strategy:"summarize-old"}}},L=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:st(s.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function st(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let 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)+`
@@ -6,25 +6,25 @@ ${a}`},...i],droppedCount:s.length,strategy:"summarize-old"}}},L=class{construct
6
6
  `);return r>t*.7?n.slice(0,r)+`
7
7
  [...truncated: ${e.length-r} chars omitted]`:n+`
8
8
  [...truncated: ${e.length-t} chars omitted]`}function it(...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 at(...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}=re(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 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 d=s.slice(0,a),p=s.slice(a,u),f=s.slice(u),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]
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}=se(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 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 d=s.slice(0,a),p=s.slice(a,u),f=s.slice(u),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]
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}}}},w=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}=re(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,c=Math.max(0,s.length-this.config.preserveRecentCount);if(c<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let u=t.reduce((m,g)=>m+this.config.estimateTokens(g),0);if(u<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=s.slice(0,c),p=s.slice(c),f=a&&typeof a.content=="string"?`Previous summary:
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}}}},w=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}=se(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,c=Math.max(0,s.length-this.config.preserveRecentCount);if(c<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let u=t.reduce((m,g)=>m+this.config.estimateTokens(g),0);if(u<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=s.slice(0,c),p=s.slice(c),f=a&&typeof a.content=="string"?`Previous summary:
12
12
  ${a.content}
13
13
 
14
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]
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:u,tokensAfter:b,compressionRatio:u>0?b/u: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}}}},oe={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function lt(e={}){let t={...oe,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function ct(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var N=class{events=[];maxEvents;constructor(t=100){this.maxEvents=t}record(t){this.events.push(t),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let t=this.events.length;if(t===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let n=0,o=0,r=0,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 re(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function S(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function R(e){let t=Math.min(e.length,5),n=[];for(let o=0;o<t;o++){let r=e[o],s=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${s}`)}return n.join("|")}var ut=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),F=class{constructor(t=20,n=S){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=t.length-this.preserveRecentCount,r=0,s=0;return{messages:t.map((a,l)=>{if(l>=o||a.role!=="tool"||typeof a.content!="string"||!a.name||!ut.has(a.name)||a.content.length<=200)return a;let c=this.estimateTokens(a);return s+=c,r++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function pt(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let 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 dt(e,t,n){let o=n.estimateTokens??(p=>Math.ceil(p.length/4)),r=pt(t);if(r.length===0)return e;let s=e.map(p=>typeof p.content=="string"?p.content:"").join(`
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:u,tokensAfter:b,compressionRatio:u>0?b/u: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}}}},re={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function lt(e={}){let t={...re,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function ct(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var N=class{events=[];maxEvents;constructor(t=100){this.maxEvents=t}record(t){this.events.push(t),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let t=this.events.length;if(t===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let n=0,o=0,r=0,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 se(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 ut=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),F=class{constructor(t=20,n=S){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=t.length-this.preserveRecentCount,r=0,s=0;return{messages:t.map((a,l)=>{if(l>=o||a.role!=="tool"||typeof a.content!="string"||!a.name||!ut.has(a.name)||a.content.length<=200)return a;let c=this.estimateTokens(a);return s+=c,r++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function pt(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let 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 dt(e,t,n){let o=n.estimateTokens??(p=>Math.ceil(p.length/4)),r=pt(t);if(r.length===0)return e;let s=e.map(p=>typeof p.content=="string"?p.content:"").join(`
17
17
  `),i=r.filter(p=>!s.includes(p));if(i.length===0)return e;let a=n.maxTokenBudget,l=[],c=0;for(let p of i){if(c>=n.maxFiles||a<=0)break;let f=await n.readFile(p);if(!f)continue;let C=o(f);C>a||(a-=C,c++,l.push({role:"system",content:`[Post-compact file recovery: ${p}]
18
18
 
19
- ${f}`}))}if(l.length===0)return e;let u=[...e],d=-1;for(let p=0;p<u.length;p++)u[p].role==="system"&&(d=p);return u.splice(d+1,0,...l),u}function mt(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 ft(){return{stages:[]}}function gt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=se(e,t),i=yt(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=se(e,t),{messages:s,stagedCount:i.length}}function Tt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:ie(e,t),committed:n}}function se(e,t){return t.stages.filter(o=>o.committed).length===0?e:ie(e,t)}function ie(e,t){let n=t.stages.filter(r=>r.committed).sort((r,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 yt(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 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{existsSync as G,readFileSync as fe,writeFileSync as ht,readdirSync as ge,mkdirSync as Ct}from"node:fs";import{join as H,dirname as _t}from"node:path";var Fn=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Bn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var ae=20;var le=3,ce=2,ue=300*1e3,pe=3,de=720*60*60*1e3;var Un=300*1e3,j=4;var jn=3600*1e3;var Gn=50*1024,Hn=500*1024,$n=500*1024*1024,zn=50*1024*1024;var qn=60*1024;var Te=0;var bt="skill-patterns.json";function ye(e){return H(e,".qlogicagent",bt)}function he(e){let t=ye(e);try{return JSON.parse(fe(t,"utf8"))}catch{return{version:1,patterns:{}}}}function me(e,t){let n=ye(e);Ct(_t(n),{recursive:!0}),ht(n,JSON.stringify(t,null,2),"utf8")}function Rt(e){let t=Date.now()-de;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function Ce(e,t){if(t.length===0)return!1;let n=x(t),o=he(e);Rt(o);let r=new Date().toISOString(),s=o.patterns[n];if(s||(s={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=s),s.promoted)return me(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=pe;return i&&(s.promoted=!0),me(e,o),i}function St(e){let t=he(e);return Object.values(t.patterns)}function x(e){return[...e].sort().join("+")}function xt(e,t){if(!G(t))return null;let n=x(e);try{let o=ge(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let s=H(t,r.name,"SKILL.md");try{let a=fe(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let l=a[1].split(`
20
- `).map(c=>c.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(x(l)===n)return r.name}}catch{}}}catch{}return null}function kt(e){if(!G(e))return 0;try{return ge(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&G(H(e,t.name,"SKILL.md"))).length}catch{return 0}}function At(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<le||e.distinctToolCount<ce||Date.now()-Te<ue||t?.projectSkillsDir&&(kt(t.projectSkillsDir)>=ae||t.tools.length>0&&xt(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Ce(t.projectRoot,t.tools))}function Mt(e){return e.existingSkillName?e.feedback==="negative":!1}function Et(e,t){return Mt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:At(e,t)?(Te=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function _e(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function It(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function vt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Lt(e){if(!e.eligibility?.length)return[...e.tools];let t=vt(e.eligibility);return e.tools.filter(n=>{let o=_e(n);if(!o)return!1;let r=t.get(o);return!r||It(r.status)})}function Ot(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=Ot({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Lt({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let 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=>_e(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 Pt=["stop","aborted","timeout","cancelled","interrupted","error"],Nt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function be(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Dt(e,t){return{...e,content:[...be(e.content),...be(t.content)]}}function Ft(e){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 Bt(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=Ft(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 Ut(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 jt(e){return new Set((e??Pt).map(t=>t.trim().toLowerCase()))}function Re(e,t){return e?jt(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 $(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=>Ut(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,...d}=l;d.content!=null&&d.content!==""&&s.push(d);continue}if(c.length<l.tool_calls.length){s.push({...l,tool_calls:c});continue}}s.push(l)}let i=Bt(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]=Dt(c,l);continue}a.push(l)}return a}function z(e,t){return Re(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Nt)delete o[r];return o}):[...e]}function q(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let 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 Ht(e,t){let n=$(e),o=z(n,t);return q(o,t)}function Se(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=Re(t?.stopReason,t?.forcedStopReasons),r=[];for(let 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(f=>f&&typeof f=="object"&&f.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let d={...u};if(typeof d.id=="string"){let p=Gt(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}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 zt(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 qt(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 Kt(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function xe(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Xt(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 Wt(e){let t=[],n=$(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=z(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=q(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:$t(r),completedToolCallIds:zt(r)}),recoveryActions:t}}function Vt(e){let t=Se(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:qt(t),completedToolCallIds:Kt(t)}),recoveryActions:n}}var Jt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Zt(e){return e?Jt.has(e):!0}function Qt(e){return e===429||e===529}function en(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 no={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function tn(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var K=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var X="<fork-child-context>",ke="Fork started \u2014 processing in background";function nn(e){return JSON.stringify(e).includes(X)}function on(e){return e<j}function rn(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
19
+ ${f}`}))}if(l.length===0)return e;let u=[...e],d=-1;for(let p=0;p<u.length;p++)u[p].role==="system"&&(d=p);return u.splice(d+1,0,...l),u}function mt(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 ft(){return{stages:[]}}function gt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=ie(e,t),i=yt(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=ie(e,t),{messages:s,stagedCount:i.length}}function Tt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:ae(e,t),committed:n}}function ie(e,t){return t.stages.filter(o=>o.committed).length===0?e:ae(e,t)}function ae(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 yt(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 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{existsSync as G,readFileSync as ge,writeFileSync as ht,readdirSync as Te,mkdirSync as Ct}from"node:fs";import{join as H,dirname as _t}from"node:path";var Bn=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Un=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var le=20;var ce=3,ue=2,pe=300*1e3,de=3,me=720*60*60*1e3;var jn=300*1e3,j=4;var Gn=3600*1e3;var Hn=50*1024,$n=500*1024,zn=500*1024*1024,qn=50*1024*1024;var Kn=60*1024;var ye=0;var bt="skill-patterns.json";function he(e){return H(e,".qlogicagent",bt)}function Ce(e){let t=he(e);try{return JSON.parse(ge(t,"utf8"))}catch{return{version:1,patterns:{}}}}function fe(e,t){let n=he(e);Ct(_t(n),{recursive:!0}),ht(n,JSON.stringify(t,null,2),"utf8")}function Rt(e){let t=Date.now()-me;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function _e(e,t){if(t.length===0)return!1;let n=x(t),o=Ce(e);Rt(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 fe(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=de;return i&&(s.promoted=!0),fe(e,o),i}function St(e){let t=Ce(e);return Object.values(t.patterns)}function x(e){return[...e].sort().join("+")}function xt(e,t){if(!G(t))return null;let n=x(e);try{let o=Te(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let s=H(t,r.name,"SKILL.md");try{let a=ge(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let l=a[1].split(`
20
+ `).map(c=>c.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(x(l)===n)return r.name}}catch{}}}catch{}return null}function kt(e){if(!G(e))return 0;try{return Te(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&G(H(e,t.name,"SKILL.md"))).length}catch{return 0}}function At(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<ce||e.distinctToolCount<ue||Date.now()-ye<pe||t?.projectSkillsDir&&(kt(t.projectSkillsDir)>=le||t.tools.length>0&&xt(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!_e(t.projectRoot,t.tools))}function Mt(e){return e.existingSkillName?e.feedback==="negative":!1}function Et(e,t){return Mt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:At(e,t)?(ye=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function It(e){let t=new Set(e.map($).filter(Boolean)),n=t.has("exec"),o=["read","search","write","edit","patch"].some(r=>t.has(r));return!n||!o?"You must call one of the available tools before responding.":'You must call one of the available tools before responding. 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 $(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 vt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Lt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Ot(e){if(!e.eligibility?.length)return[...e.tools];let t=Lt(e.eligibility);return e.tools.filter(n=>{let o=$(n);if(!o)return!1;let r=t.get(o);return!r||vt(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 Pt(e){let t=wt({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Ot({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:It(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=>$(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 Nt=["stop","aborted","timeout","cancelled","interrupted","error"],Dt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function be(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Ft(e,t){return{...e,content:[...be(e.content),...be(t.content)]}}function Bt(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 Ut(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=Bt(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 jt(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 Gt(e){return new Set((e??Nt).map(t=>t.trim().toLowerCase()))}function Re(e,t){return e?Gt(t).has(e.trim().toLowerCase()):!1}function Ht(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 z(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=>jt(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,...d}=l;d.content!=null&&d.content!==""&&s.push(d);continue}if(c.length<l.tool_calls.length){s.push({...l,tool_calls:c});continue}}s.push(l)}let i=Ut(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]=Ft(c,l);continue}a.push(l)}return a}function q(e,t){return Re(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Dt)delete o[r];return o}):[...e]}function K(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 $t(e,t){let n=z(e),o=q(n,t);return K(o,t)}function Se(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=Re(t?.stopReason,t?.forcedStopReasons),r=[];for(let 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(f=>f&&typeof f=="object"&&f.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let d={...u};if(typeof d.id=="string"){let p=Ht(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}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 zt(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 qt(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 Kt(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 Xt(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function xe(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function 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 Wt(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 Vt(e){let t=[],n=z(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=q(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=K(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:zt(r),completedToolCallIds:qt(r)}),recoveryActions:t}}function Jt(e){let t=Se(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:Kt(t),completedToolCallIds:Xt(t)}),recoveryActions:n}}var Zt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Qt(e){return e?Zt.has(e):!0}function en(e){return e===429||e===529}function tn(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 oo={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function nn(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var X=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var Y="<fork-child-context>",ke="Fork started \u2014 processing in background";function on(e){return JSON.stringify(e).includes(Y)}function rn(e){return e<j}function sn(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
21
21
 
22
22
  Your working directory is: ${e.worktreePath}
23
- All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${X}
23
+ All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${Y}
24
24
 
25
25
  You are the "${t.agent.name}" agent.${o}
26
26
 
27
- ${t.taskPrompt}`}]};return n.push(r),n}function sn(e){return e.map(t=>({role:"tool",tool_call_id:t,content:ke}))}function an(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolCapabilityProfile==="no_tools")return[];if(t.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent"&&n!=="team")}function ln(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var cn={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},un={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolCapabilityProfile:"read_tools",allowedTools:["read_file","search","web_search","web_fetch","memory","tool_search"],canFork:!1,systemPromptSuffix:"You are READ-ONLY: never attempt to modify files or run mutating commands. Locate and understand code, then report concrete findings with file:line references. Read excerpts rather than whole files; surface conclusions, not raw dumps."},pn={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolCapabilityProfile:"read_tools",allowedTools:["read_file","search","web_search","web_fetch","memory","task","tool_search"],canFork:!1,systemPromptSuffix:"You PLAN but do not execute: never write files or run commands. Investigate enough to ground the plan in the real code, then return a concrete, step-by-step implementation plan naming the specific files and changes involved."},dn={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."},mn={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."},fn={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=[cn,un,pn,dn,mn,fn];function gn(){return[...Y]}function Tn(e){return Y.find(t=>t.name===e)}function yn(e){return Y.some(t=>t.name===e)}function hn(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolCapabilityProfile==="no_tools")return[];if(e.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(o=>!n.has(o))}return e.canFork?[...t]:t.filter(n=>n!=="agent"&&n!=="team")}var Cn=new Set(["agent_tool","team","fork_agent"]);function _n(e,t){switch(e){case"worker":return t.filter(n=>!Cn.has(n));case"coordinator":return[...t];default:return[...t]}}function bn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function Rn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Sn(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 xn(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 kn(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 An(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Mn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function En(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
27
+ ${t.taskPrompt}`}]};return n.push(r),n}function an(e){return e.map(t=>({role:"tool",tool_call_id:t,content:ke}))}function ln(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolCapabilityProfile==="no_tools")return[];if(t.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent"&&n!=="team")}function cn(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var un={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},pn={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolCapabilityProfile:"read_tools",allowedTools:["read_file","search","web_search","web_fetch","memory","tool_search"],canFork:!1,systemPromptSuffix:"You are READ-ONLY: never attempt to modify files or run mutating commands. Locate and understand code, then report concrete findings with file:line references. Read excerpts rather than whole files; surface conclusions, not raw dumps."},dn={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolCapabilityProfile:"read_tools",allowedTools:["read_file","search","web_search","web_fetch","memory","task","tool_search"],canFork:!1,systemPromptSuffix:"You PLAN but do not execute: never write files or run commands. Investigate enough to ground the plan in the real code, then return a concrete, step-by-step implementation plan naming the specific files and changes involved."},mn={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."},fn={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."},gn={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."},W=[un,pn,dn,mn,fn,gn];function Tn(){return[...W]}function yn(e){return W.find(t=>t.name===e)}function hn(e){return W.some(t=>t.name===e)}function Cn(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolCapabilityProfile==="no_tools")return[];if(e.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(o=>!n.has(o))}return e.canFork?[...t]:t.filter(n=>n!=="agent"&&n!=="team")}var _n=new Set(["agent_tool","team","fork_agent"]);function bn(e,t){switch(e){case"worker":return t.filter(n=>!_n.has(n));case"coordinator":return[...t];default:return[...t]}}function Rn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function Sn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function xn(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 kn(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 An(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 Mn(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var En={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function In(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
28
28
  ${n.join(`
29
29
  `)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
30
30
  Step ${e.activeSkillContext.step}:
@@ -35,4 +35,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
35
35
 
36
36
  ${t.join(`
37
37
 
38
- `)}`}function In(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function vn(e,t=Mn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{P as CacheAwareCompressionStrategy,N as CompressionMetricsCollector,D as ContextEngineRegistry,oe as DEFAULT_ADAPTIVE_BUDGET_CONFIG,ke as FORK_PLACEHOLDER_RESULT,X as FORK_SENTINEL_TAG,K as FallbackTriggeredError,O as HeadTailProtectedStrategy,w as IncrementalCompactStrategy,j as MAX_FORK_DEPTH,F as MicroCompactStrategy,I as SlidingWindowStrategy,v as SummarizeOldStrategy,L as ToolResultTrimStrategy,Xt as advanceToolLoopState,gt as applyContextCollapsesIfNeeded,wt as applyToolChoicePolicy,Ae as buildAssistantToolCallMessage,sn as buildForkPlaceholderResults,rn as buildForkedMessages,En as buildPostCompactRestorationMessage,Et as buildSkillInstruction,U as buildStructuredSummaryPrompt,Me as buildToolResultMessage,x as buildToolSignature,Sn as calculateTokenWarningState,on as canForkAtDepth,ot as classifyError,at as composeAsyncStrategies,it as composeStrategies,lt as computeAdaptiveBudget,en as computeRetryBackoff,ft as createCollapseStore,In as createReactiveCompactState,bn as createTaskState,Rn as createTurnLoopGuardState,_n as filterToolsByRole,ln as generateForkChildAgentId,Tn as getBuiltInAgent,gn as getBuiltInAgents,St as getPatternStats,B as isAsyncCompressionStrategy,yn as isBuiltInAgent,Zt as isForegroundSource,nn as isInForkChild,tn as isPersistentRetryEnabled,rt as isRetryableCategory,Qt as isTransientCapacityError,dt as postCompactFileRecovery,Ce as recordPatternAndCheckThreshold,Tt as recoverContextCollapseFromOverflow,Wt as recoverToolLoopStateFromChatConversation,Vt as recoverToolLoopStateFromResponsesItems,Ht as repairOpenAiChatConversation,hn as resolveAgentToolSet,xn as resolveApiErrorRecovery,an as resolveForkChildTools,kn as resolveOutputTokenEscalation,ct as selectCompressionTier,Yt as settleToolLoopState,An as shouldAbortTurn,vn as shouldAttemptReactiveCompact,mt as snipCompactIfNeeded};
38
+ `)}`}function vn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Ln(e,t=En){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{P as CacheAwareCompressionStrategy,N as CompressionMetricsCollector,D as ContextEngineRegistry,re as DEFAULT_ADAPTIVE_BUDGET_CONFIG,ke as FORK_PLACEHOLDER_RESULT,Y as FORK_SENTINEL_TAG,X as FallbackTriggeredError,O as HeadTailProtectedStrategy,w as IncrementalCompactStrategy,j as MAX_FORK_DEPTH,F as MicroCompactStrategy,I as SlidingWindowStrategy,v as SummarizeOldStrategy,L as ToolResultTrimStrategy,Yt as advanceToolLoopState,gt as applyContextCollapsesIfNeeded,Pt as applyToolChoicePolicy,Ae as buildAssistantToolCallMessage,an as buildForkPlaceholderResults,sn as buildForkedMessages,In as buildPostCompactRestorationMessage,Et as buildSkillInstruction,U as buildStructuredSummaryPrompt,Me as buildToolResultMessage,x as buildToolSignature,xn as calculateTokenWarningState,rn as canForkAtDepth,ot as classifyError,at as composeAsyncStrategies,it as composeStrategies,lt as computeAdaptiveBudget,tn as computeRetryBackoff,ft as createCollapseStore,vn as createReactiveCompactState,Rn as createTaskState,Sn as createTurnLoopGuardState,bn as filterToolsByRole,cn as generateForkChildAgentId,yn as getBuiltInAgent,Tn as getBuiltInAgents,St as getPatternStats,B as isAsyncCompressionStrategy,hn as isBuiltInAgent,Qt as isForegroundSource,on as isInForkChild,nn as isPersistentRetryEnabled,rt as isRetryableCategory,en as isTransientCapacityError,dt as postCompactFileRecovery,_e as recordPatternAndCheckThreshold,Tt as recoverContextCollapseFromOverflow,Vt as recoverToolLoopStateFromChatConversation,Jt as recoverToolLoopStateFromResponsesItems,$t as repairOpenAiChatConversation,Cn as resolveAgentToolSet,kn as resolveApiErrorRecovery,ln as resolveForkChildTools,An as resolveOutputTokenEscalation,ct as selectCompressionTier,Wt as settleToolLoopState,Mn as shouldAbortTurn,Ln as shouldAttemptReactiveCompact,mt as snipCompactIfNeeded};
package/dist/protocol.js CHANGED
@@ -1 +1 @@
1
- var q=["idle","running-right","running-left","waving","jumping","failed","waiting","running","review"];var Y="1.0.0",d={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TURN_ABORTED:-32e3,TURN_TIMEOUT:-32001,LLM_ERROR:-32010,LLM_AUTH_ERROR:-32011,LLM_RATE_LIMIT:-32012,LLM_QUOTA_EXHAUSTED:-32013,LLM_MODEL_NOT_FOUND:-32014,TOOL_INVOKE_FAILED:-32020,TOOL_TIMEOUT:-32021,PROTOCOL_MISMATCH:-32030,REQUEST_DEADLINE_EXCEEDED:-32040,REQUEST_CANCELLED:-32041,REQUEST_DEDUPED:-32042,REQUEST_IDEMPOTENCY_REQUIRED:-32043},H={REQUEST:"tool.approval.request"};function P(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&t.method.length>0}function C(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&(typeof t.id=="string"||typeof t.id=="number")&&!("method"in t)}function I(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function G(e){let t;try{t=JSON.parse(e)}catch{return null}return C(t)||P(t)||I(t)?t:null}import{randomUUID as z}from"node:crypto";var X=["settings.list","settings.get","settings.validate","provider.list","config.get","config.tunables","tools.list","todos.list","tasks.list","agents.list","agents.get","agents.processes","agents.scan","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(),o=f(e),i=t.timeoutMs??o.defaultTimeoutMs;return{requestId:t.requestId??z(),createdAt:r,deadlineAt:r+i,channel:t.channel??o.channel,idempotencyKey:t.idempotencyKey,traceId:t.traceId}}function v(e,t=Date.now()){let r=e.meta;if(!r||typeof r!="object")return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta is required."}};if(typeof r.requestId!="string"||r.requestId.length===0)return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.requestId is required."}};if(r.channel!=="query"&&r.channel!=="task")return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.channel must be query or task."}};if(typeof r.createdAt!="number"||!Number.isFinite(r.createdAt))return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.createdAt is required."}};if(typeof r.deadlineAt!="number"||!Number.isFinite(r.deadlineAt))return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.deadlineAt is required."}};if(r.deadlineAt<=t)return{ok:!1,error:{code:d.REQUEST_DEADLINE_EXCEEDED,message:"RPC request deadline has already expired."}};let o=f(e.method).channel;return r.channel!==o?{ok:!1,error:{code:d.INVALID_REQUEST,message:`RPC request channel mismatch: expected ${o}, got ${r.channel}.`}}: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 o=v({method:t,meta:r},this.now());if(!o.ok)return this.counters.invalidRequests+=1,{status:"rejected",error:o.error};if(r.idempotencyKey){let i=this.idempotency.get(r.idempotencyKey);if(i)return this.counters.dedupedRequests+=1,i.error?{status:"deduped",error:i.error}:{status:"deduped",result:i.result}}return this.active.set(r.requestId,{method:t,meta:r,cancelled:!1,startedAt:this.now()}),{status:"started"}}cancel(t,r="cancelled"){let o=this.active.get(t);return!o||o.cancelled?!1:(o.cancelled=!0,o.cancelReason=r,this.counters.cancelledRequests+=1,!0)}expire(t){return this.active.get(t)?(this.active.delete(t),this.counters.deadlineExceededRequests+=1,!0):!1}settle(t,r,o){let i=this.active.get(t);return i?(this.active.delete(t),i.cancelled?(this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"cancelled"}):i.meta.deadlineAt<=this.now()?(this.counters.deadlineExceededRequests+=1,this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"deadline_exceeded"}):(this.counters.completedRequests+=1,i.meta.idempotencyKey&&this.idempotency.set(i.meta.idempotencyKey,{result:r,error:o,settledAt:this.now()}),{accepted:!0})):{accepted:!1,reason:"unknown"}}metrics(){return{activeRequests:this.active.size,...this.counters}}};var ee=["agent.health","agent.metrics","agent.cancel","session.list","session.get","session.create","session.update","session.delete","session.deleteAll","session.archive","session.moveToProject","session.getState","session.switchProject","session.getMessages","project.list","project.create","project.delete","project.rename","project.archive","project.unarchive","project.update","project.purgeAll","instructions.list","instructions.read","instructions.write","instructions.delete","files.list","files.read","files.create","files.rename","files.delete","files.gitStatus","skills.list","memory.list-files","memory.atlas","memory.activity","memory.observe","memory.propose","memory.consolidate","memory.update","memory.attachment.adopt","memory.attachment.locate"];var M=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.approval_request","turn.skill_instruction","turn.ask_user","turn.media_result","turn.media_progress","turn.media_usage","turn.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.tool_use_summary","turn.lifecycle","turn.document_maintenance","turn.artifact_contract","turn.usage_update","team.member.notification","session.info","memory.updated","skills.updated","pet.soul_ready","pet.reaction","pet.growth","pet.state","pet.confirm","pet.asset.updated","system.activity","workflow.created","workflow.updated","workflow.deleted","workflow.runStarted","workflow.runCompleted","workflow.runFailed","workflow.nodeStatus","workflow.triggerDropped","workflow.alert","workflow.approvalRequested"],k=["solo.progress","solo.agentDelta","solo.agentActivity","solo.agentUsage","solo.evaluation","product.taskStarted","product.taskOutput","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.budgetWarning","product.checkpointed","product.completed","product.dagTopology","plan.interrupted"],te=[...M,...k];var re=1,oe={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_CLOSE:"session/close",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",SESSION_LOAD:"session/load",SESSION_CANCEL:"session/cancel",SESSION_UPDATE:"session/update",SESSION_REQUEST_PERMISSION:"session/request_permission",FS_READ_TEXT_FILE:"fs/read_text_file",FS_WRITE_TEXT_FILE:"fs/write_text_file"},ne={ABORT:"x/abort",DREAM:"x/dream",AGENTS_LIST:"x/agents.list",SOLO_START:"x/solo.start",SOLO_STATUS:"x/solo.status",SOLO_SELECT:"x/solo.select",SOLO_CANCEL:"x/solo.cancel",PRODUCT_CREATE:"x/product.create",PRODUCT_PLAN:"x/product.plan",PRODUCT_CONFIRM:"x/product.confirm",PRODUCT_MESSAGE:"x/product.message",PRODUCT_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_STATUS:"x/product.status",SOLO_SUBSCRIBE:"x/solo.subscribe",SOLO_MESSAGE:"x/solo.message",SOLO_EVALUATE:"x/solo.evaluate",SOLO_SPEC_CHAT:"x/solo.specChat",SOLO_SPEC_JUDGE:"x/solo.specJudge",WORKFLOW_CHAT:"x/workflow.chat",WORKFLOW_MATCH_INTENT:"x/workflow.matchIntent",PRODUCT_SUBSCRIBE:"x/product.subscribe"},x={USER_MESSAGE_CHUNK:"user_message_chunk",AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",USAGE_UPDATE:"usage_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",AVAILABLE_COMMANDS_UPDATE:"available_commands_update",CURRENT_MODE_UPDATE:"current_mode_update"},ie={X_SKILL_INSTRUCTION:"x_skill_instruction",X_SESSION_INFO:"x_session_info",X_RELAY:"x_relay"};function O(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&"id"in t}function N(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function w(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&"id"in t&&!("method"in t)}function se(e){let t;try{t=JSON.parse(e)}catch{return null}return w(t)||O(t)||N(t)?t:null}function ae(e){return Object.values(x).includes(e)}function pe(e){return e.startsWith("x_")}var E=["gatewayVersion","toolNamespaces","workspaceIds","installedCapabilities","enabledCapabilities","features","approvalMode","toolManifests","skillManifests","pluginManifests","mcpManifests","approvalPolicy","workspaceSummaries"];function g(e){return e?e.map(t=>({...t})):void 0}function _(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 o=E.filter(s=>JSON.stringify(t[s])!==JSON.stringify(r[s]));if(o.length===E.length)return{...m(r),syncMode:"full"};let i={snapshotVersion:r.snapshotVersion,updatedAt:r.updatedAt,syncMode:"diff",baseSnapshotVersion:t.snapshotVersion,changedSections:o,toolNamespaces:[...r.toolNamespaces],workspaceIds:[...r.workspaceIds]},c=i;for(let s of o){let n=r[s];if(n!==void 0)switch(s){case"toolNamespaces":case"workspaceIds":case"installedCapabilities":case"enabledCapabilities":case"features":c[s]=ce(n);break;case"approvalPolicy":c[s]={...n};break;case"workspaceSummaries":c[s]=_(n);break;case"toolManifests":case"skillManifests":case"pluginManifests":case"mcpManifests":c[s]=g(n);break;default:c[s]=n;break}}return i}var me=["web_search","web_fetch","deep_research","browser_execution"],ye=["web-intelligence","browser-execution"],fe=["discovery","read-url","multi-source-research","interactive-browser"],Ae=["stateless","render-backend","interactive-session"],Re=["stateless","stateless-single-step","stateful-session-required"],Ee=["required","conditional","none"],_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(o=>W(e,o)).filter(o=>!!o):[]}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={},o=t.assets&&typeof t.assets=="object"?t.assets:{};for(let[n,p]of Object.entries(o)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.artifacts)||(r[n]=U(u))}if(!r[a.gatewayImage]&&t.gateway&&typeof t.gateway=="object"){let n=L(t.gateway,{id:a.gatewayImage,title:"OpenClaw Gateway Image (Desktop Slim)",kind:"container-image",delivery:"remote",platform:"any",description:"Desktop Docker mode gateway image."});n&&(r[n.id]=n)}if(!r[a.whisperModelTiny]&&t.whisperModel&&typeof t.whisperModel=="object"){let n=L(t.whisperModel,{id:a.whisperModelTiny,title:"Whisper Tiny Model",kind:"model",delivery:"remote",platform:"any",description:"Shared whisper.cpp tiny model asset for embedded desktop speech recognition."});n&&(r[n.id]=n)}let c={...K()},s=t.profiles&&typeof t.profiles=="object"?t.profiles:{};for(let[n,p]of Object.entries(s)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.assetIds)||(c[n]=Me(u))}return F({schemaVersion:typeof t.schemaVersion=="number"?t.schemaVersion:2,channel:typeof t.channel=="string"?t.channel:void 0,publishedAt:typeof t.publishedAt=="string"?t.publishedAt:void 0,minElectronVersion:typeof t.minElectronVersion=="string"?t.minElectronVersion:void 0,releaseNotes:typeof t.releaseNotes=="string"?t.releaseNotes:void 0,assets:r,profiles:c})}var Ne=["pending","captured","failed","restored"],we=["file","directory","missing"],De=["metadata-only","workspace-copy","shadow-git"];var Le=["api-key","oauth","token","aws-sdk"],Ue=["rate_limit","auth","server_error","timeout","network","unknown"],Ke=["requiresOpenAiAnthropicToolPayload"];function We(e,t){return!e||typeof e!="object"||Array.isArray(e)?!1:e[t]===!0}var j="openai-codex";function A(e){let t=e.trim().toLowerCase();return t==="z.ai"||t==="z-ai"?"zai":t==="opencode-zen"?"opencode":t==="kimi-code"?"kimi-coding":t==="bedrock"||t==="aws-bedrock"?"amazon-bedrock":t==="bytedance"||t==="doubao"?"volcengine":t}function B(e){let t=A(e);return t==="volcengine-plan"?"volcengine":t==="qwen-coding"?"qwen":t==="byteplus-plan"?"byteplus":t}var Ve=B,Fe={anthropicToolSchemaMode:"native",anthropicToolChoiceMode:"native",providerFamily:"default",preserveAnthropicThinkingSignatures:!0,openAiCompatTurnValidation:!0,providerThoughtSignatureSanitization:!1,transcriptToolCallIdMode:"default",transcriptToolCallIdModelHints:[],providerThoughtSignatureModelHints:[],dropThinkingBlockModelHints:[]},je={anthropic:{providerFamily:"anthropic"},"amazon-bedrock":{providerFamily:"anthropic"},"kimi-coding":{anthropicToolSchemaMode:"openai-functions",anthropicToolChoiceMode:"openai-string-modes",preserveAnthropicThinkingSignatures:!1},mistral:{transcriptToolCallIdMode:"strict9",transcriptToolCallIdModelHints:["mistral","mixtral","codestral","pixtral","devstral","ministral","mistralai"]},openai:{providerFamily:"openai"},[j]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};function b(e,t){let r=(e??"").toLowerCase();return!!r&&t.some(o=>r.includes(o))}function l(e){let t=A(e??"");return{...Fe,...je[t]}}function Be(e){return l(e).preserveAnthropicThinkingSignatures}function qe(e){let t=l(e);return t.anthropicToolSchemaMode!=="native"||t.anthropicToolChoiceMode!=="native"}function Ye(e){return l(e).anthropicToolSchemaMode==="openai-functions"}function He(e){return l(e).anthropicToolChoiceMode==="openai-string-modes"}function Ge(e){return l(e).openAiCompatTurnValidation}function ze(e){return l(e).providerFamily==="openai"}function Xe(e){return l(e).providerFamily==="anthropic"}function Je(e){return b(e.modelId,l(e.provider).dropThinkingBlockModelHints)}function Qe(e){let t=l(e.provider);return t.providerThoughtSignatureSanitization&&b(e.modelId,t.providerThoughtSignatureModelHints)}function $e(e,t){let r=l(e),o=r.transcriptToolCallIdMode;if(o==="strict9")return o;if(b(t,r.transcriptToolCallIdModelHints))return"strict9"}var T={anthropic:["ANTHROPIC_OAUTH_TOKEN","ANTHROPIC_API_KEY"],chutes:["CHUTES_OAUTH_TOKEN","CHUTES_API_KEY"],zai:["ZAI_API_KEY","Z_AI_API_KEY"],opencode:["OPENCODE_API_KEY","OPENCODE_ZEN_API_KEY"],qwen:["DASHSCOPE_API_KEY","QWEN_API_KEY"],"qwen-coding":["DASHSCOPE_API_KEY","QWEN_API_KEY"],volcengine:["VOLCANO_ENGINE_API_KEY","ARK_API_KEY","DOUBAO_API_KEY"],"volcengine-plan":["VOLCANO_ENGINE_API_KEY","ARK_API_KEY","DOUBAO_API_KEY"],byteplus:["BYTEPLUS_API_KEY"],"byteplus-plan":["BYTEPLUS_API_KEY"],"kimi-coding":["KIMI_API_KEY","KIMICODE_API_KEY"],huggingface:["HUGGINGFACE_HUB_TOKEN","HF_TOKEN"],openai:["OPENAI_API_KEY"],voyage:["VOYAGE_API_KEY"],groq:["GROQ_API_KEY"],deepgram:["DEEPGRAM_API_KEY"],cerebras:["CEREBRAS_API_KEY"],xai:["XAI_API_KEY"],openrouter:["OPENROUTER_API_KEY"],litellm:["LITELLM_API_KEY"],"vercel-ai-gateway":["AI_GATEWAY_API_KEY"],"cloudflare-ai-gateway":["CLOUDFLARE_AI_GATEWAY_API_KEY"],moonshot:["MOONSHOT_API_KEY"],minimax:["MINIMAX_API_KEY"],"minimax-cn":["MINIMAX_CN_API_KEY","MINIMAX_API_KEY"],nvidia:["NVIDIA_API_KEY"],xiaomi:["XIAOMI_API_KEY"],synthetic:["SYNTHETIC_API_KEY"],venice:["VENICE_API_KEY"],mistral:["MISTRAL_API_KEY"],together:["TOGETHER_API_KEY"],qianfan:["QIANFAN_API_KEY"],ollama:["OLLAMA_API_KEY"],vllm:["VLLM_API_KEY"],kilocode:["KILOCODE_API_KEY"]};function Ze(){return[...new Set(Object.values(T).flat())]}function et(e){let t=A(e.provider),r=e.env??process.env,o=new Set(e.appliedEnvKeys??[]),i=n=>{let p=r[n]?.trim();if(!p)return null;let u=o.has(n)?`shell env: ${n}`:`env: ${n}`;return{apiKey:p,source:u}},c=e.resolveSpecialApiKey?.(t,r,o);if(c)return c;let s=T[t];if(!s||s.length===0)return null;for(let n of s){let p=i(n);if(p)return p}return null}export{ne as ACP_EXTENDED_METHODS,ie as ACP_EXTENDED_SESSION_UPDATE_TYPES,oe as ACP_METHODS,re as ACP_PROTOCOL_VERSION,x as ACP_SESSION_UPDATE_TYPES,H as AGENT_RPC_APPROVAL_METHODS,d as AGENT_RPC_ERROR_CODES,Y as AGENT_RPC_PROTOCOL_VERSION,k as AGENT_TEAM_WS_EVENT_NAMES,M as AGENT_WS_EVENT_NAMES,te as ALL_AGENT_WS_EVENT_NAMES,E as CAPABILITY_MANIFEST_DIFF_SECTIONS,ee as GATEWAY_RPC_METHODS,R as GatewayRpcContract,Ce as MEMORY_OBSERVATION_HOOK_VALUES,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(),o=f(e),i=t.timeoutMs??o.defaultTimeoutMs;return{requestId:t.requestId??z(),createdAt:r,deadlineAt:r+i,channel:t.channel??o.channel,idempotencyKey:t.idempotencyKey,traceId:t.traceId}}function v(e,t=Date.now()){let r=e.meta;if(!r||typeof r!="object")return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta is required."}};if(typeof r.requestId!="string"||r.requestId.length===0)return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.requestId is required."}};if(r.channel!=="query"&&r.channel!=="task")return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.channel must be query or task."}};if(typeof r.createdAt!="number"||!Number.isFinite(r.createdAt))return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.createdAt is required."}};if(typeof r.deadlineAt!="number"||!Number.isFinite(r.deadlineAt))return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.deadlineAt is required."}};if(r.deadlineAt<=t)return{ok:!1,error:{code:d.REQUEST_DEADLINE_EXCEEDED,message:"RPC request deadline has already expired."}};let o=f(e.method).channel;return r.channel!==o?{ok:!1,error:{code:d.INVALID_REQUEST,message:`RPC request channel mismatch: expected ${o}, got ${r.channel}.`}}: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 o=v({method:t,meta:r},this.now());if(!o.ok)return this.counters.invalidRequests+=1,{status:"rejected",error:o.error};if(r.idempotencyKey){let i=this.idempotency.get(r.idempotencyKey);if(i)return this.counters.dedupedRequests+=1,i.error?{status:"deduped",error:i.error}:{status:"deduped",result:i.result}}return this.active.set(r.requestId,{method:t,meta:r,cancelled:!1,startedAt:this.now()}),{status:"started"}}cancel(t,r="cancelled"){let o=this.active.get(t);return!o||o.cancelled?!1:(o.cancelled=!0,o.cancelReason=r,this.counters.cancelledRequests+=1,!0)}expire(t){return this.active.get(t)?(this.active.delete(t),this.counters.deadlineExceededRequests+=1,!0):!1}settle(t,r,o){let i=this.active.get(t);return i?(this.active.delete(t),i.cancelled?(this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"cancelled"}):i.meta.deadlineAt<=this.now()?(this.counters.deadlineExceededRequests+=1,this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"deadline_exceeded"}):(this.counters.completedRequests+=1,i.meta.idempotencyKey&&this.idempotency.set(i.meta.idempotencyKey,{result:r,error:o,settledAt:this.now()}),{accepted:!0})):{accepted:!1,reason:"unknown"}}metrics(){return{activeRequests:this.active.size,...this.counters}}};var ee=["agent.health","agent.metrics","agent.cancel","session.list","session.get","session.create","session.update","session.delete","session.deleteAll","session.archive","session.moveToProject","session.getState","session.switchProject","session.getMessages","project.list","project.create","project.delete","project.rename","project.archive","project.unarchive","project.update","project.purgeAll","instructions.list","instructions.read","instructions.write","instructions.delete","files.list","files.read","files.create","files.rename","files.delete","files.gitStatus","skills.list","memory.list-files","memory.atlas","memory.activity","memory.observe","memory.propose","memory.consolidate","memory.update","memory.attachment.adopt","memory.attachment.locate"];var M=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.approval_request","turn.skill_instruction","turn.ask_user","turn.media_result","turn.media_progress","turn.media_usage","turn.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.tool_use_summary","turn.tool_selection_policy","turn.lifecycle","turn.document_maintenance","turn.artifact_contract","turn.usage_update","team.member.notification","session.info","memory.updated","skills.updated","pet.soul_ready","pet.reaction","pet.growth","pet.state","pet.confirm","pet.asset.updated","system.activity","workflow.created","workflow.updated","workflow.deleted","workflow.runStarted","workflow.runCompleted","workflow.runFailed","workflow.nodeStatus","workflow.triggerDropped","workflow.alert","workflow.approvalRequested"],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"],te=[...M,...k];var re=1,oe={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_CLOSE:"session/close",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",SESSION_LOAD:"session/load",SESSION_CANCEL:"session/cancel",SESSION_UPDATE:"session/update",SESSION_REQUEST_PERMISSION:"session/request_permission",FS_READ_TEXT_FILE:"fs/read_text_file",FS_WRITE_TEXT_FILE:"fs/write_text_file"},ne={ABORT:"x/abort",DREAM:"x/dream",AGENTS_LIST:"x/agents.list",SOLO_START:"x/solo.start",SOLO_STATUS:"x/solo.status",SOLO_SELECT:"x/solo.select",SOLO_CANCEL:"x/solo.cancel",PRODUCT_CREATE:"x/product.create",PRODUCT_PLAN:"x/product.plan",PRODUCT_CONFIRM:"x/product.confirm",PRODUCT_MESSAGE:"x/product.message",PRODUCT_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_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"},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 o=E.filter(s=>JSON.stringify(t[s])!==JSON.stringify(r[s]));if(o.length===E.length)return{...m(r),syncMode:"full"};let i={snapshotVersion:r.snapshotVersion,updatedAt:r.updatedAt,syncMode:"diff",baseSnapshotVersion:t.snapshotVersion,changedSections:o,toolNamespaces:[...r.toolNamespaces],workspaceIds:[...r.workspaceIds]},c=i;for(let s of o){let n=r[s];if(n!==void 0)switch(s){case"toolNamespaces":case"workspaceIds":case"installedCapabilities":case"enabledCapabilities":case"features":c[s]=ce(n);break;case"approvalPolicy":c[s]={...n};break;case"workspaceSummaries":c[s]=_(n);break;case"toolManifests":case"skillManifests":case"pluginManifests":case"mcpManifests":c[s]=g(n);break;default:c[s]=n;break}}return i}var me=["web_search","web_fetch","deep_research","browser_execution"],ye=["web-intelligence","browser-execution"],fe=["discovery","read-url","multi-source-research","interactive-browser"],Ae=["stateless","render-backend","interactive-session"],Re=["stateless","stateless-single-step","stateful-session-required"],Ee=["required","conditional","none"],_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(o=>W(e,o)).filter(o=>!!o):[]}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={},o=t.assets&&typeof t.assets=="object"?t.assets:{};for(let[n,p]of Object.entries(o)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.artifacts)||(r[n]=U(u))}if(!r[a.gatewayImage]&&t.gateway&&typeof t.gateway=="object"){let n=L(t.gateway,{id:a.gatewayImage,title:"OpenClaw Gateway Image (Desktop Slim)",kind:"container-image",delivery:"remote",platform:"any",description:"Desktop Docker mode gateway image."});n&&(r[n.id]=n)}if(!r[a.whisperModelTiny]&&t.whisperModel&&typeof t.whisperModel=="object"){let n=L(t.whisperModel,{id:a.whisperModelTiny,title:"Whisper Tiny Model",kind:"model",delivery:"remote",platform:"any",description:"Shared whisper.cpp tiny model asset for embedded desktop speech recognition."});n&&(r[n.id]=n)}let c={...K()},s=t.profiles&&typeof t.profiles=="object"?t.profiles:{};for(let[n,p]of Object.entries(s)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.assetIds)||(c[n]=Me(u))}return F({schemaVersion:typeof t.schemaVersion=="number"?t.schemaVersion:2,channel:typeof t.channel=="string"?t.channel:void 0,publishedAt:typeof t.publishedAt=="string"?t.publishedAt:void 0,minElectronVersion:typeof t.minElectronVersion=="string"?t.minElectronVersion:void 0,releaseNotes:typeof t.releaseNotes=="string"?t.releaseNotes:void 0,assets:r,profiles:c})}var Ne=["pending","captured","failed","restored"],we=["file","directory","missing"],De=["metadata-only","workspace-copy","shadow-git"];var Le=["api-key","oauth","token","aws-sdk"],Ue=["rate_limit","auth","server_error","timeout","network","unknown"],Ke=["requiresOpenAiAnthropicToolPayload"];function We(e,t){return!e||typeof e!="object"||Array.isArray(e)?!1:e[t]===!0}var j="openai-codex";function A(e){let t=e.trim().toLowerCase();return t==="z.ai"||t==="z-ai"?"zai":t==="opencode-zen"?"opencode":t==="kimi-code"?"kimi-coding":t==="bedrock"||t==="aws-bedrock"?"amazon-bedrock":t==="bytedance"||t==="doubao"?"volcengine":t}function B(e){let t=A(e);return t==="volcengine-plan"?"volcengine":t==="qwen-coding"?"qwen":t==="byteplus-plan"?"byteplus":t}var Ve=B,Fe={anthropicToolSchemaMode:"native",anthropicToolChoiceMode:"native",providerFamily:"default",preserveAnthropicThinkingSignatures:!0,openAiCompatTurnValidation:!0,providerThoughtSignatureSanitization:!1,transcriptToolCallIdMode:"default",transcriptToolCallIdModelHints:[],providerThoughtSignatureModelHints:[],dropThinkingBlockModelHints:[]},je={anthropic:{providerFamily:"anthropic"},"amazon-bedrock":{providerFamily:"anthropic"},"kimi-coding":{anthropicToolSchemaMode:"openai-functions",anthropicToolChoiceMode:"openai-string-modes",preserveAnthropicThinkingSignatures:!1},mistral:{transcriptToolCallIdMode:"strict9",transcriptToolCallIdModelHints:["mistral","mixtral","codestral","pixtral","devstral","ministral","mistralai"]},openai:{providerFamily:"openai"},[j]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};function b(e,t){let r=(e??"").toLowerCase();return!!r&&t.some(o=>r.includes(o))}function l(e){let t=A(e??"");return{...Fe,...je[t]}}function Be(e){return l(e).preserveAnthropicThinkingSignatures}function qe(e){let t=l(e);return t.anthropicToolSchemaMode!=="native"||t.anthropicToolChoiceMode!=="native"}function Ye(e){return l(e).anthropicToolSchemaMode==="openai-functions"}function He(e){return l(e).anthropicToolChoiceMode==="openai-string-modes"}function Ge(e){return l(e).openAiCompatTurnValidation}function ze(e){return l(e).providerFamily==="openai"}function Xe(e){return l(e).providerFamily==="anthropic"}function Je(e){return b(e.modelId,l(e.provider).dropThinkingBlockModelHints)}function Qe(e){let t=l(e.provider);return t.providerThoughtSignatureSanitization&&b(e.modelId,t.providerThoughtSignatureModelHints)}function $e(e,t){let r=l(e),o=r.transcriptToolCallIdMode;if(o==="strict9")return o;if(b(t,r.transcriptToolCallIdModelHints))return"strict9"}var T={anthropic:["ANTHROPIC_OAUTH_TOKEN","ANTHROPIC_API_KEY"],chutes:["CHUTES_OAUTH_TOKEN","CHUTES_API_KEY"],zai:["ZAI_API_KEY","Z_AI_API_KEY"],opencode:["OPENCODE_API_KEY","OPENCODE_ZEN_API_KEY"],qwen:["DASHSCOPE_API_KEY","QWEN_API_KEY"],"qwen-coding":["DASHSCOPE_API_KEY","QWEN_API_KEY"],volcengine:["VOLCANO_ENGINE_API_KEY","ARK_API_KEY","DOUBAO_API_KEY"],"volcengine-plan":["VOLCANO_ENGINE_API_KEY","ARK_API_KEY","DOUBAO_API_KEY"],byteplus:["BYTEPLUS_API_KEY"],"byteplus-plan":["BYTEPLUS_API_KEY"],"kimi-coding":["KIMI_API_KEY","KIMICODE_API_KEY"],huggingface:["HUGGINGFACE_HUB_TOKEN","HF_TOKEN"],openai:["OPENAI_API_KEY"],voyage:["VOYAGE_API_KEY"],groq:["GROQ_API_KEY"],deepgram:["DEEPGRAM_API_KEY"],cerebras:["CEREBRAS_API_KEY"],xai:["XAI_API_KEY"],openrouter:["OPENROUTER_API_KEY"],litellm:["LITELLM_API_KEY"],"vercel-ai-gateway":["AI_GATEWAY_API_KEY"],"cloudflare-ai-gateway":["CLOUDFLARE_AI_GATEWAY_API_KEY"],moonshot:["MOONSHOT_API_KEY"],minimax:["MINIMAX_API_KEY"],"minimax-cn":["MINIMAX_CN_API_KEY","MINIMAX_API_KEY"],nvidia:["NVIDIA_API_KEY"],xiaomi:["XIAOMI_API_KEY"],synthetic:["SYNTHETIC_API_KEY"],venice:["VENICE_API_KEY"],mistral:["MISTRAL_API_KEY"],together:["TOGETHER_API_KEY"],qianfan:["QIANFAN_API_KEY"],ollama:["OLLAMA_API_KEY"],vllm:["VLLM_API_KEY"],kilocode:["KILOCODE_API_KEY"]};function Ze(){return[...new Set(Object.values(T).flat())]}function et(e){let t=A(e.provider),r=e.env??process.env,o=new Set(e.appliedEnvKeys??[]),i=n=>{let p=r[n]?.trim();if(!p)return null;let u=o.has(n)?`shell env: ${n}`:`env: ${n}`;return{apiKey:p,source:u}},c=e.resolveSpecialApiKey?.(t,r,o);if(c)return c;let s=T[t];if(!s||s.length===0)return null;for(let n of s){let p=i(n);if(p)return p}return null}export{ne as ACP_EXTENDED_METHODS,ie as ACP_EXTENDED_SESSION_UPDATE_TYPES,oe as ACP_METHODS,re as ACP_PROTOCOL_VERSION,x as ACP_SESSION_UPDATE_TYPES,H as AGENT_RPC_APPROVAL_METHODS,d as AGENT_RPC_ERROR_CODES,Y as AGENT_RPC_PROTOCOL_VERSION,k as AGENT_TEAM_WS_EVENT_NAMES,M as AGENT_WS_EVENT_NAMES,te as ALL_AGENT_WS_EVENT_NAMES,E as CAPABILITY_MANIFEST_DIFF_SECTIONS,ee as GATEWAY_RPC_METHODS,R as GatewayRpcContract,Ce as MEMORY_OBSERVATION_HOOK_VALUES,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};
@@ -11,6 +11,7 @@ export interface ArtifactContractState {
11
11
  devServerUrls: string[];
12
12
  browserVerified: boolean;
13
13
  browserEvidence: string[];
14
+ browserFailureEvidence: string[];
14
15
  }
15
16
  export interface ArtifactContractEventPayload {
16
17
  artifactRoot?: string;
@@ -23,8 +24,14 @@ export interface ArtifactContractEventPayload {
23
24
  devServerUrls: string[];
24
25
  browserVerified: boolean;
25
26
  browserEvidence: string[];
27
+ browserFailureEvidence: string[];
26
28
  requiresBrowserAcceptance: boolean;
27
29
  }
30
+ export interface TaskContractItem {
31
+ id: number;
32
+ title: string;
33
+ status: string;
34
+ }
28
35
  export declare function createArtifactContractState(inputMessages: readonly ChatMessage[]): ArtifactContractState;
29
36
  export declare function requiresBrowserAcceptance(inputMessages: readonly ChatMessage[]): boolean;
30
37
  export declare function requiresResearchQualityGate(inputMessages: readonly ChatMessage[]): boolean;
@@ -41,6 +48,13 @@ export declare function resolveArtifactRootWriteBlock(params: {
41
48
  artifactRoot: string;
42
49
  error: string;
43
50
  } | null;
51
+ export declare function resolveReadOnlyContextPackWriteBlock(params: {
52
+ toolName: string;
53
+ rawArguments: string;
54
+ }): {
55
+ path: string;
56
+ error: string;
57
+ } | null;
44
58
  export declare function recordArtifactRootBlock(state: ArtifactContractState, params: {
45
59
  path: string;
46
60
  artifactRoot: string;
@@ -55,6 +69,8 @@ export declare function updateArtifactContractFromToolResult(params: {
55
69
  content: string;
56
70
  }): void;
57
71
  export declare function artifactContractPayload(state: ArtifactContractState, inputMessages: readonly ChatMessage[]): ArtifactContractEventPayload;
72
+ export declare function recoverArtifactContractState(inputMessages: readonly ChatMessage[]): ArtifactContractState;
73
+ export declare function updateArtifactContractFromFinalContent(state: ArtifactContractState, content: string): void;
58
74
  export declare function applyFinalStatusContract(params: {
59
75
  content: string;
60
76
  inputMessages: readonly ChatMessage[];
@@ -62,4 +78,9 @@ export declare function applyFinalStatusContract(params: {
62
78
  totalToolCallCount: number;
63
79
  distinctToolNames: Iterable<string>;
64
80
  artifactContract: ArtifactContractState;
81
+ blockedToolCalls?: ReadonlyArray<{
82
+ name: string;
83
+ reason: string;
84
+ }>;
85
+ activeTasks?: readonly TaskContractItem[];
65
86
  }): string;
@@ -13,6 +13,7 @@ export declare function variantBlockNudge(): ChatMessage;
13
13
  export declare function recordToolFailureResult(input: {
14
14
  toolFailureCounts: Map<string, number>;
15
15
  toolName: string;
16
+ toolArguments?: string;
16
17
  ok: boolean;
17
18
  softEmpty: boolean;
18
19
  }): void;
@@ -94,6 +94,8 @@ export interface ToolLoopParams {
94
94
  parallelToolCalls?: boolean;
95
95
  /** Text output verbosity hint. */
96
96
  textVerbosity?: "low" | "medium" | "high";
97
+ /** Per-round LLM stream idle timeout. A stream with no chunks beyond this window fails the turn. */
98
+ llmStreamIdleTimeoutMs?: number;
97
99
  /** Project root directory -used for skill pattern tracking at project level. */
98
100
  projectRoot?: string;
99
101
  runtimePorts: ToolLoopRuntimePorts;