qlogicagent 2.19.13 → 2.20.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 (92) hide show
  1. package/README.md +0 -1
  2. package/dist/agent-contract.js +1 -1
  3. package/dist/agent.js +31 -31
  4. package/dist/cli.js +1 -1
  5. package/dist/host-contract.js +1 -1
  6. package/dist/index.js +457 -453
  7. package/dist/orchestration.js +13 -13
  8. package/dist/project-memory-host.js +19 -18
  9. package/dist/protocol.js +1 -1
  10. package/dist/tunables.js +1 -1
  11. package/dist/types/cli/acp-extended-handlers.d.ts +5 -10
  12. package/dist/types/cli/acp-extended-host-adapter.d.ts +1 -1
  13. package/dist/types/cli/community-workflow-installer.d.ts +2 -2
  14. package/dist/types/cli/handlers/dream-handler.d.ts +6 -0
  15. package/dist/types/cli/handlers/goal-handler.d.ts +1 -13
  16. package/dist/types/cli/handlers/product-handler.d.ts +6 -9
  17. package/dist/types/cli/handlers/solo-handler.d.ts +3 -6
  18. package/dist/types/cli/handlers/workflow-compute-handler.d.ts +1 -1
  19. package/dist/types/cli/memory-coordinator.d.ts +0 -2
  20. package/dist/types/cli/multi-agent-handler-host.d.ts +1 -1
  21. package/dist/types/cli/orchestration-memory-context.d.ts +1 -0
  22. package/dist/types/cli/product-coordinator.d.ts +2 -5
  23. package/dist/types/cli/rpc-registry.d.ts +0 -3
  24. package/dist/types/cli/runtime-hook-bootstrap.d.ts +0 -2
  25. package/dist/types/cli/stdio-rpc-handler-hosts.d.ts +2 -1
  26. package/dist/types/cli/stdio-server.d.ts +2 -3
  27. package/dist/types/cli/task-distillation-coordinator.d.ts +0 -3
  28. package/dist/types/contracts/hooks.d.ts +2 -0
  29. package/dist/types/host-contract/index.d.ts +3 -13
  30. package/dist/types/index.d.ts +0 -1
  31. package/dist/types/orchestration/agent-instance.d.ts +30 -15
  32. package/dist/types/orchestration/agent-roster.d.ts +2 -2
  33. package/dist/types/orchestration/goal-loop-coordinator.d.ts +18 -8
  34. package/dist/types/orchestration/goal-mode-adapters.d.ts +6 -1
  35. package/dist/types/orchestration/goal-run-persistence.d.ts +12 -10
  36. package/dist/types/orchestration/goal-run-types.d.ts +3 -21
  37. package/dist/types/orchestration/index.d.ts +0 -1
  38. package/dist/types/orchestration/product-checkpoint.d.ts +10 -6
  39. package/dist/types/orchestration/product-persistence.d.ts +47 -20
  40. package/dist/types/orchestration/product-planner.d.ts +30 -10
  41. package/dist/types/orchestration/product-run-coordinator.d.ts +4 -3
  42. package/dist/types/orchestration/solo-evaluator.d.ts +10 -16
  43. package/dist/types/orchestration/solo-persistence.d.ts +10 -10
  44. package/dist/types/orchestration/workflow/budget-permission-gate.d.ts +1 -1
  45. package/dist/types/orchestration/workflow/capability-catalog.d.ts +11 -34
  46. package/dist/types/orchestration/workflow/host-executors.d.ts +3 -3
  47. package/dist/types/orchestration/workflow/n8n-import.d.ts +0 -1
  48. package/dist/types/orchestration/workflow/node-schema.d.ts +5 -18
  49. package/dist/types/orchestration/workflow/params-schema.d.ts +7 -16
  50. package/dist/types/orchestration/workflow/qla-executor-host.d.ts +4 -27
  51. package/dist/types/orchestration/workflow/workflow-bundle.d.ts +10 -28
  52. package/dist/types/orchestration/workflow/workflow-controller.d.ts +14 -8
  53. package/dist/types/orchestration/workflow/workflow-error.d.ts +1 -1
  54. package/dist/types/orchestration/workflow/workflow-render.d.ts +1 -1
  55. package/dist/types/orchestration/workflow/workflow-scheduler.d.ts +8 -8
  56. package/dist/types/orchestration/workflow/workflow-store.d.ts +7 -8
  57. package/dist/types/orchestration/workflow-chat-builder.d.ts +1 -1
  58. package/dist/types/protocol/agent-contract.d.ts +7 -7
  59. package/dist/types/protocol/methods.d.ts +1 -129
  60. package/dist/types/protocol/notifications.d.ts +1 -1
  61. package/dist/types/protocol/wire/acp-agent-management.d.ts +45 -24
  62. package/dist/types/protocol/wire/acp-protocol.d.ts +3 -8
  63. package/dist/types/protocol/wire/agent-methods.d.ts +2 -468
  64. package/dist/types/protocol/wire/index.d.ts +1 -1
  65. package/dist/types/protocol/wire/notification-payloads.d.ts +0 -6
  66. package/dist/types/protocol/wire/thread-protocol.d.ts +1 -1
  67. package/dist/types/runtime/config/tunable-defaults.d.ts +0 -9
  68. package/dist/types/runtime/hooks/memory-hooks.d.ts +11 -4
  69. package/dist/types/runtime/infra/acp-protocol-adapter.d.ts +1 -2
  70. package/dist/types/runtime/memory/implicit-extraction.d.ts +4 -1
  71. package/dist/types/runtime/memory/recall-category-filter.d.ts +0 -12
  72. package/dist/types/runtime/ports/memory-recall-source.d.ts +1 -0
  73. package/dist/types/runtime/ports/project-memory-store.d.ts +3 -0
  74. package/dist/types/skills/memory/host-memory-provider.d.ts +7 -0
  75. package/dist/types/skills/memory/memdir.d.ts +1 -2
  76. package/dist/types/skills/memory/task-distillation.d.ts +18 -4
  77. package/dist/types/skills/skill-system/skill-lifecycle.d.ts +0 -17
  78. package/dist/types/skills/skill-system/skill-validation.d.ts +1 -1
  79. package/dist/types/transport/acp-server.d.ts +1 -5
  80. package/dist/types/workflow-host.d.ts +2 -4
  81. package/dist/workflow-host.js +7 -9
  82. package/package.json +1 -1
  83. package/dist/types/cli/credential-vault.d.ts +0 -68
  84. package/dist/types/orchestration/skill-improvement.d.ts +0 -97
  85. package/dist/types/skills/memory/local-store-records.d.ts +0 -206
  86. package/dist/types/skills/memory/local-store.d.ts +0 -376
  87. package/dist/types/skills/memory/memory-attachment-store.d.ts +0 -62
  88. package/dist/types/skills/memory/memory-consolidation.d.ts +0 -64
  89. package/dist/types/skills/memory/memory-db-path.d.ts +0 -13
  90. package/dist/types/skills/memory/proposal-consumer.d.ts +0 -51
  91. package/dist/types/skills/memory/sqlite-memory-mappers.d.ts +0 -7
  92. package/dist/types/skills/memory/sqlite-memory-schema.d.ts +0 -11
@@ -1,29 +1,29 @@
1
- function xe(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function ke(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 Ae=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,T={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Ee=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Me=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Ie=512,ve=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var we=new Set([500,502,503,504,521,522,523,524,529]),Oe=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Le=["upgrade your plan","upgrade plan","current plan","subscription"],Pe=["daily","weekly","monthly"],Ne=["try again","retry","temporary","cooldown"],Fe=["usage limit","rate limit","organization usage"],De=["organization","workspace"],Be=["billing period","exceeded","reached","exhausted"],Ue=/["']?(?: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,Ge=/^(?: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 je(e){return h(e,T.format)}function X(e){return h(e,T.rateLimit)}function $e(e){return h(e,T.timeout)}function He(e){return Ae.test(e)}function M(e){let t=e.toLowerCase();return t?e.length>Ie?Me.test(t):h(t,T.billing)?!0:Ee.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function K(e){return h(e,T.authPermanent)}function ze(e){return h(e,T.auth)}function W(e){return h(e,T.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function qe(e){return y(e,Oe)||y(e,Le)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ye(e){let t=y(e,Pe),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,De);return y(e,Ne)&&y(e,Fe)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,Be))}function Xe(e){return e.trim().toLowerCase().replace(Ge,"").trim()}function V(e){let t=Xe(e);return!t||qe(t)?"billing":X(t)||Ye(t)?"rate_limit":"billing"}function Ke(e){return Ue.test(e)?V(e):null}function J(e){let t=e.match(ve);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function We(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Ve(e){let t=e.trim();if(!t)return!1;let n=J(t);return n?we.has(n.code):!1}function Z(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?V(t):"billing":e===429?"rate_limit":e===401||e===403?t&&K(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&W(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&M(t)?"billing":"format":null}function Je(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 Ze(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function Q(e){if(Ze(e))return"session_expired";if(Je(e))return"model_not_found";let t=Ke(e);return t||(He(e)?M(e)?"billing":"rate_limit":X(e)?"rate_limit":W(e)?"overloaded":Ve(e)?J(e.trim())?.code===529?"overloaded":"timeout":We(e)?"timeout":je(e)?"format":M(e)?"billing":$e(e)?"timeout":K(e)?"auth_permanent":ze(e)?"auth":null)}var Qe=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ee(e){return Qe.has(e)}var et={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"};function tt(e,t){let n=Z(e,t)??(t?Q(t):null);return n?et[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function B(e){return typeof e.compressAsync=="function"}var te=4;function ne(e){return{role:"system",content:`[${e} earlier messages removed to fit the context budget]`}}var I=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let p of t)p.role==="system"?o.push(p):r.push(p);let s=n;for(let p of o)s-=this.estimateTokens(p);let i;for(let p of r)if(p.role==="user"){i=p;break}if(i&&(s-=this.estimateTokens(i)),s<=0){let p=r.length-(i?1:0),d=i?[...o,i]:[...o];return p>0&&d.push(ne(p)),{messages:d,droppedCount:p,strategy:"sliding-window"}}let a=[],l=0;for(let p=r.length-1;p>=0;p--){let d=r[p];if(d===i)continue;let m=this.estimateTokens(d);if(s-m<0&&l>=te)break;if(s-m<0&&l<te){a.unshift(d),l++;continue}s-=m,a.unshift(d),l++}let c=r.length-(a.length+(i&&!a.includes(i)?1:0)),u=[...o];return i&&!a.includes(i)&&u.push(i),c>0&&u.push(ne(c)),u.push(...a),{messages:u,droppedCount:c,strategy:"sliding-window"}}},v=class{constructor(t,n){this.recentCount=t;this.summarize=n}recentCount;summarize;compress(t,n){let o=t.filter(l=>l.role==="system"),r=t.filter(l=>l.role!=="system");if(r.length<=this.recentCount)return{messages:t,droppedCount:0,strategy:"summarize-old"};let s=r.slice(0,r.length-this.recentCount),i=r.slice(r.length-this.recentCount),a=this.summarize(s);return{messages:[...o,{role:"system",content:`[Conversation summary]
2
- ${a}`},...i],droppedCount:s.length,strategy:"summarize-old"}}},w=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(s=>s.role!=="tool"||typeof s.content!="string"||s.content.length<=this.maxToolResultChars?s:(o++,{...s,content:nt(s.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function nt(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let s=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
1
+ function me(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function fe(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 ge=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,T={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},ye=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Te=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,he=512,Ce=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var _e=new Set([500,502,503,504,521,522,523,524,529]),be=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Re=["upgrade your plan","upgrade plan","current plan","subscription"],xe=["daily","weekly","monthly"],Se=["try again","retry","temporary","cooldown"],Ae=["usage limit","rate limit","organization usage"],ke=["organization","workspace"],Ee=["billing period","exceeded","reached","exhausted"],Me=/["']?(?: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,ve=/^(?: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 Ie(e){return h(e,T.format)}function X(e){return h(e,T.rateLimit)}function we(e){return h(e,T.timeout)}function Oe(e){return ge.test(e)}function M(e){let t=e.toLowerCase();return t?e.length>he?Te.test(t):h(t,T.billing)?!0:ye.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function W(e){return h(e,T.authPermanent)}function Le(e){return h(e,T.auth)}function K(e){return h(e,T.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function Pe(e){return y(e,be)||y(e,Re)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ne(e){let t=y(e,xe),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,ke);return y(e,Se)&&y(e,Ae)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,Ee))}function Fe(e){return e.trim().toLowerCase().replace(ve,"").trim()}function V(e){let t=Fe(e);return!t||Pe(t)?"billing":X(t)||Ne(t)?"rate_limit":"billing"}function De(e){return Me.test(e)?V(e):null}function J(e){let t=e.match(Ce);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Be(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Ue(e){let t=e.trim();if(!t)return!1;let n=J(t);return n?_e.has(n.code):!1}function Z(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?V(t):"billing":e===429?"rate_limit":e===401||e===403?t&&W(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&K(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&M(t)?"billing":"format":null}function Ge(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 $e(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function Q(e){if($e(e))return"session_expired";if(Ge(e))return"model_not_found";let t=De(e);return t||(Oe(e)?M(e)?"billing":"rate_limit":X(e)?"rate_limit":K(e)?"overloaded":Ue(e)?J(e.trim())?.code===529?"overloaded":"timeout":Be(e)?"timeout":Ie(e)?"format":M(e)?"billing":we(e)?"timeout":W(e)?"auth_permanent":Le(e)?"auth":null)}var je=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ee(e){return je.has(e)}var He={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"};function ze(e,t){let n=Z(e,t)??(t?Q(t):null);return n?He[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function B(e){return typeof e.compressAsync=="function"}var te=4;function ne(e){return{role:"system",content:`[${e} earlier messages removed to fit the context budget]`}}var v=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let p of t)p.role==="system"?o.push(p):r.push(p);let i=n;for(let p of o)i-=this.estimateTokens(p);let s;for(let p of r)if(p.role==="user"){s=p;break}if(s&&(i-=this.estimateTokens(s)),i<=0){let p=r.length-(s?1:0),d=s?[...o,s]:[...o];return p>0&&d.push(ne(p)),{messages:d,droppedCount:p,strategy:"sliding-window"}}let a=[],l=0;for(let p=r.length-1;p>=0;p--){let d=r[p];if(d===s)continue;let m=this.estimateTokens(d);if(i-m<0&&l>=te)break;if(i-m<0&&l<te){a.unshift(d),l++;continue}i-=m,a.unshift(d),l++}let c=r.length-(a.length+(s&&!a.includes(s)?1:0)),u=[...o];return s&&!a.includes(s)&&u.push(s),c>0&&u.push(ne(c)),u.push(...a),{messages:u,droppedCount:c,strategy:"sliding-window"}}},I=class{constructor(t,n){this.recentCount=t;this.summarize=n}recentCount;summarize;compress(t,n){let o=t.filter(l=>l.role==="system"),r=t.filter(l=>l.role!=="system");if(r.length<=this.recentCount)return{messages:t,droppedCount:0,strategy:"summarize-old"};let i=r.slice(0,r.length-this.recentCount),s=r.slice(r.length-this.recentCount),a=this.summarize(i);return{messages:[...o,{role:"system",content:`[Conversation summary]
2
+ ${a}`},...s],droppedCount:i.length,strategy:"summarize-old"}}},w=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(i=>i.role!=="tool"||typeof i.content!="string"||i.content.length<=this.maxToolResultChars?i:(o++,{...i,content:qe(i.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function qe(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let i=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
3
3
  `),n.lastIndexOf(`]
4
- `));if(s>t*.5)return n.slice(0,s+1)+`
5
- [...truncated: ${e.length-s-1} chars omitted]`}let r=n.lastIndexOf(`
4
+ `));if(i>t*.5)return n.slice(0,i+1)+`
5
+ [...truncated: ${e.length-i-1} chars omitted]`}let r=n.lastIndexOf(`
6
6
  `);return r>t*.7?n.slice(0,r)+`
7
7
  [...truncated: ${e.length-r} chars omitted]`:n+`
8
- [...truncated: ${e.length-t} chars omitted]`}function ot(...e){return{compress(t,n){let o=t,r=0,s=[];for(let i of e){let a=i.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}}}}function rt(...e){return{compress(t,n){let o=t,r=0,s=[];for(let i of e){let a=i.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}},async compressAsync(t,n){let o=t,r=0,s=[],i=0,a=!1,l=!1;for(let c of e){let u=B(c)?await c.compressAsync(o,n):c.compress(o,n);o=u.messages,r+=u.droppedCount,u.droppedCount>0&&s.push(u.strategy),u.metrics&&(i+=u.metrics.latencyMs,a=a||u.metrics.usedLlm,l=l||!!u.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none",metrics:i>0||a?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:i,usedLlm:a,cacheInvalidated:l}:void 0}}}}function U(e,t){let n=e.filter(i=>i.role==="user"),o=e.filter(i=>i.tool_calls!=null),r=e.filter(i=>i.role==="tool"),s=["You are a conversation summarizer. Produce a structured summary of the conversation history below.","","## Instructions","Analyze the conversation and produce a summary with these sections:","","### 1. Primary Objective","What is the user's main goal or task? State it in one sentence.","","### 2. Key Decisions Made","List the important decisions, choices, or conclusions reached during the conversation.","","### 3. Current Progress",`Describe the current state. ${o.length>0?`${o.length} tool calls and ${r.length} tool results were exchanged.`:"No tools were used."}`,"","### 4. Pending Tasks","List any tasks that are in-progress or planned but not yet completed.","","### 5. Important Context","MUST preserve verbatim: IP addresses, file paths, URLs, port numbers, credentials/tokens, specific numeric values, version numbers, proper nouns, identifiers, and any user-provided data points. These MUST appear exactly as stated in the original conversation.","","### 6. All User Messages",`List ALL ${n.length} user messages chronologically, each as 1-2 sentences capturing the core request. Include exact values, identifiers, keywords, or secrets the user mentioned or asked you to remember. Do NOT omit any user message \u2014 every user request must be traceable in this summary.`,"","### 7. Error & Recovery History","Summarize any errors encountered and how they were resolved.","","### 8. User Preferences Expressed","Note any stated preferences about style, approach, or constraints.","","### 9. Technical State","Note file paths, variable names, API endpoints, or configuration values that were discussed.","","### 10. Conversation Flow","Briefly describe the overall flow: what happened first, what changed, where we are now."];return t?.taskContext&&s.push("","## Additional Context",t.taskContext),s.push("","## Conversation to Summarize","",...e.map(i=>{let a=typeof i.content=="string"?i.content:JSON.stringify(i.content??""),l=i.role==="user"?a:a.length>2e3?a.slice(0,2e3)+"...":a;return`[${i.role}]: ${l}`}),"","## Output Format","Respond with a concise summary covering all 10 sections above. Use markdown headers.","Keep the total summary under 1000 words. Focus on actionable information and exact user requests."),s.join(`
9
- `)}var O=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??S,taskContext:t.taskContext}}compress(t,n){return{messages:t,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:s}=re(t),i=t.reduce((f,g)=>f+this.config.estimateTokens(g),0);if(i<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let a=0,l=0;for(let f=0;f<s.length&&(s[f].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));f++)a=f+1;let c=Math.max(this.config.protectedTailMessages,Math.floor(s.length*.4)),u=Math.max(a,s.length-c);if(u<=a)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let p=s.slice(0,a),d=s.slice(a,u),m=s.slice(u),C=U(d,{taskContext:this.config.taskContext}),k=await this.config.summarize(d,C),A={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
8
+ [...truncated: ${e.length-t} chars omitted]`}function Ye(...e){return{compress(t,n){let o=t,r=0,i=[];for(let s of e){let a=s.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&i.push(a.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}}}}function Xe(...e){return{compress(t,n){let o=t,r=0,i=[];for(let s of e){let a=s.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&i.push(a.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}},async compressAsync(t,n){let o=t,r=0,i=[],s=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&&i.push(u.strategy),u.metrics&&(s+=u.metrics.latencyMs,a=a||u.metrics.usedLlm,l=l||!!u.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none",metrics:s>0||a?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:s,usedLlm:a,cacheInvalidated:l}:void 0}}}}function U(e,t){let n=e.filter(s=>s.role==="user"),o=e.filter(s=>s.tool_calls!=null),r=e.filter(s=>s.role==="tool"),i=["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&&i.push("","## Additional Context",t.taskContext),i.push("","## Conversation to Summarize","",...e.map(s=>{let a=typeof s.content=="string"?s.content:JSON.stringify(s.content??""),l=s.role==="user"?a:a.length>2e3?a.slice(0,2e3)+"...":a;return`[${s.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."),i.join(`
9
+ `)}var O=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??x,taskContext:t.taskContext}}compress(t,n){return{messages:t,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=re(t),s=t.reduce((f,g)=>f+this.config.estimateTokens(g),0);if(s<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let a=0,l=0;for(let f=0;f<i.length&&(i[f].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));f++)a=f+1;let c=Math.max(this.config.protectedTailMessages,Math.floor(i.length*.4)),u=Math.max(a,i.length-c);if(u<=a)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let p=i.slice(0,a),d=i.slice(a,u),m=i.slice(u),C=U(d,{taskContext:this.config.taskContext}),A=await this.config.summarize(d,C),k={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
10
10
 
11
- ${k}`},_=[...r,...p,A,...m],E=Date.now()-o,b=_.reduce((f,g)=>f+this.config.estimateTokens(g),0);return{messages:_,droppedCount:d.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:b,compressionRatio:i>0?b/i:1,latencyMs:E,usedLlm:!0,cacheInvalidated:!0}}}},L=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??S}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:s}=re(t),i=r.findIndex(f=>typeof f.content=="string"&&f.content.startsWith("[Conversation summary")),a=i>=0?r[i]:void 0,l=i>=0?[...r.slice(0,i),...r.slice(i+1)]:r,c=Math.max(0,s.length-this.config.preserveRecentCount);if(c<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let u=t.reduce((f,g)=>f+this.config.estimateTokens(g),0);if(u<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let p=s.slice(0,c),d=s.slice(c),m=a&&typeof a.content=="string"?`Previous summary:
11
+ ${A}`},_=[...r,...p,k,...m],E=Date.now()-o,b=_.reduce((f,g)=>f+this.config.estimateTokens(g),0);return{messages:_,droppedCount:d.length,strategy:"head-tail-protected",metrics:{tokensBefore:s,tokensAfter:b,compressionRatio:s>0?b/s:1,latencyMs:E,usedLlm:!0,cacheInvalidated:!0}}}},L=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??x}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=re(t),s=r.findIndex(f=>typeof f.content=="string"&&f.content.startsWith("[Conversation summary")),a=s>=0?r[s]:void 0,l=s>=0?[...r.slice(0,s),...r.slice(s+1)]:r,c=Math.max(0,i.length-this.config.preserveRecentCount);if(c<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let u=t.reduce((f,g)=>f+this.config.estimateTokens(g),0);if(u<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let p=i.slice(0,c),d=i.slice(c),m=a&&typeof a.content=="string"?`Previous summary:
12
12
  ${a.content}
13
13
 
14
- New messages to integrate:`:void 0,C=U(p,{taskContext:m}),k=await this.config.summarize(p,C),A={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
14
+ New messages to integrate:`:void 0,C=U(p,{taskContext:m}),A=await this.config.summarize(p,C),k={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
15
15
 
16
- ${k}`},_=[...l,A,...d],E=Date.now()-o,b=_.reduce((f,g)=>f+this.config.estimateTokens(g),0);return{messages:_,droppedCount:p.length,strategy:"incremental-compact",metrics:{tokensBefore:u,tokensAfter:b,compressionRatio:u>0?b/u:1,latencyMs:E,usedLlm:!0,cacheInvalidated:!0}}}},P=class{config;constructor(t){this.config=t}compress(t,n){let o=R(t),r=this.config.inner.compress(t,n),s=R(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}async compressAsync(t,n){let o=R(t),r=B(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),s=R(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}},oe={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function st(e={}){let t={...oe,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function it(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var N=class{events=[];maxEvents;constructor(t=100){this.maxEvents=t}record(t){this.events.push(t),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let t=this.events.length;if(t===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let n=0,o=0,r=0,s=0,i=0;for(let a of this.events)n+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,o+=a.latencyMs,r+=Math.max(0,a.tokensBefore-a.tokensAfter),a.usedLlm&&s++,a.cacheInvalidated&&i++;return{totalCompressions:t,totalLlmCalls:s,totalCacheInvalidations:i,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},F=class{engines=new Map;activeId;register(t){this.engines.set(t.id,t)}activate(t){return this.engines.has(t)?(this.activeId=t,!0):!1}getActive(){return this.activeId?this.engines.get(this.activeId):void 0}listEngines(){return Array.from(this.engines.values()).map(t=>({id:t.id,label:t.label,active:t.id===this.activeId}))}};function 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 at=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),D=class{constructor(t=20,n=S){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=new Map;for(let l of t){let c=l.tool_calls;if(Array.isArray(c))for(let u of c)u?.id&&u.function?.name&&o.set(u.id,u.function.name)}let r=t.length-this.preserveRecentCount,s=0,i=0;return{messages:t.map((l,c)=>{if(c>=r||l.role!=="tool"||typeof l.content!="string")return l;let u=l.name??o.get(l.tool_call_id??"");if(!u||!at.has(u)||l.content.length<=200)return l;let p=this.estimateTokens(l);return i+=p,s++,{...l,content:`[result cleared \u2014 ${l.content.length} chars]`}}),droppedCount:s,strategy:"micro-compact",metrics:s>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function lt(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let s=r.function?.name??"";if(/read|edit|write|file/i.test(s)&&r.function?.arguments)try{let i=JSON.parse(r.function.arguments),a=i.path??i.filePath??i.file_path??i.file;a&&typeof a=="string"&&t.set(a,n)}catch{}}o.role==="tool"&&o.name&&/read|edit|write|file/i.test(o.name)}return[...t.entries()].sort((n,o)=>o[1]-n[1]).map(([n])=>n)}async function ct(e,t,n){let o=n.estimateTokens??(d=>Math.ceil(d.length/4)),r=lt(t);if(r.length===0)return e;let s=e.map(d=>typeof d.content=="string"?d.content:"").join(`
17
- `),i=r.filter(d=>!s.includes(d));if(i.length===0)return e;let a=n.maxTokenBudget,l=[],c=0;for(let d of i){if(c>=n.maxFiles||a<=0)break;let m=await n.readFile(d);if(!m)continue;let C=o(m);C>a||(a-=C,c++,l.push({role:"system",content:`[Post-compact file recovery: ${d}]
16
+ ${A}`},_=[...l,k,...d],E=Date.now()-o,b=_.reduce((f,g)=>f+this.config.estimateTokens(g),0);return{messages:_,droppedCount:p.length,strategy:"incremental-compact",metrics:{tokensBefore:u,tokensAfter:b,compressionRatio:u>0?b/u:1,latencyMs:E,usedLlm:!0,cacheInvalidated:!0}}}},P=class{config;constructor(t){this.config=t}compress(t,n){let o=R(t),r=this.config.inner.compress(t,n),i=R(r.messages),s=o!==i&&r.droppedCount>0;return s&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:s}}}async compressAsync(t,n){let o=R(t),r=B(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),i=R(r.messages),s=o!==i&&r.droppedCount>0;return s&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:s}}}},oe={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function We(e={}){let t={...oe,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function Ke(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var N=class{events=[];maxEvents;constructor(t=100){this.maxEvents=t}record(t){this.events.push(t),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let t=this.events.length;if(t===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let n=0,o=0,r=0,i=0,s=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&&i++,a.cacheInvalidated&&s++;return{totalCompressions:t,totalLlmCalls:i,totalCacheInvalidations:s,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},F=class{engines=new Map;activeId;register(t){this.engines.set(t.id,t)}activate(t){return this.engines.has(t)?(this.activeId=t,!0):!1}getActive(){return this.activeId?this.engines.get(this.activeId):void 0}listEngines(){return Array.from(this.engines.values()).map(t=>({id:t.id,label:t.label,active:t.id===this.activeId}))}};function 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 x(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function R(e){let t=Math.min(e.length,5),n=[];for(let o=0;o<t;o++){let r=e[o],i=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${i}`)}return n.join("|")}var Ve=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),D=class{constructor(t=20,n=x){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=new Map;for(let l of t){let c=l.tool_calls;if(Array.isArray(c))for(let u of c)u?.id&&u.function?.name&&o.set(u.id,u.function.name)}let r=t.length-this.preserveRecentCount,i=0,s=0;return{messages:t.map((l,c)=>{if(c>=r||l.role!=="tool"||typeof l.content!="string")return l;let u=l.name??o.get(l.tool_call_id??"");if(!u||!Ve.has(u)||l.content.length<=200)return l;let p=this.estimateTokens(l);return s+=p,i++,{...l,content:`[result cleared \u2014 ${l.content.length} chars]`}}),droppedCount:i,strategy:"micro-compact",metrics:i>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function Je(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let i=r.function?.name??"";if(/read|edit|write|file/i.test(i)&&r.function?.arguments)try{let s=JSON.parse(r.function.arguments),a=s.path??s.filePath??s.file_path??s.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 Ze(e,t,n){let o=n.estimateTokens??(d=>Math.ceil(d.length/4)),r=Je(t);if(r.length===0)return e;let i=e.map(d=>typeof d.content=="string"?d.content:"").join(`
17
+ `),s=r.filter(d=>!i.includes(d));if(s.length===0)return e;let a=n.maxTokenBudget,l=[],c=0;for(let d of s){if(c>=n.maxFiles||a<=0)break;let m=await n.readFile(d);if(!m)continue;let C=o(m);C>a||(a-=C,c++,l.push({role:"system",content:`[Post-compact file recovery: ${d}]
18
18
 
19
- ${m}`}))}if(l.length===0)return e;let u=[...e],p=-1;for(let d=0;d<u.length;d++)u[d].role==="system"&&(p=d);return u.splice(p+1,0,...l),u}function ut(e,t,n=S){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of e){let l=a.tool_call_id??"";if(l&&t.has(l)){o+=n(a),r++,t.delete(l);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}function pt(){return{stages:[]}}function dt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=se(e,t),i=ft(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=se(e,t),{messages:s,stagedCount:i.length}}function mt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages: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 ft(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,a=0;for(let l=0;l<o;l++){let c=e[l];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")i<0&&(i=l),a++;else{if(a>=3){let p=`${i}-${i+a}`;s.has(p)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let l=`${i}-${i+a}`;s.has(l)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{readFileSync as gt,writeFileSync as yt,mkdirSync as Tt}from"node:fs";import{join as ht,dirname as Ct}from"node:path";var Dn=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=3,le=2,ce=300*1e3,ue=3,pe=720*60*60*1e3,G=4;var Un=3600*1e3;var Gn=50*1024,jn=500*1024,$n=500*1024*1024,Hn=50*1024*1024;var zn=60*1024;var me=0;var _t="skill-patterns.json";function fe(e){return ht(e,".qlogicagent",_t)}function ge(e){let t=fe(e);try{return JSON.parse(gt(t,"utf8"))}catch{return{version:1,patterns:{}}}}function de(e,t){let n=fe(e);Tt(Ct(n),{recursive:!0}),yt(n,JSON.stringify(t,null,2),"utf8")}function bt(e){let t=Date.now()-pe;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function ye(e,t){if(t.length===0)return!1;let n=Te(t),o=ge(e);bt(o);let r=new Date().toISOString(),s=o.patterns[n];if(s||(s={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=s),s.promoted)return de(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=ue;return i&&(s.promoted=!0),de(e,o),i}function Rt(e){let t=ge(e);return Object.values(t.patterns)}function Te(e){return[...e].sort().join("+")}function St(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<ae||e.distinctToolCount<le||Date.now()-me<ce||t?.projectRoot&&t.tools.length>0&&!ye(t.projectRoot,t.tools))}function xt(e){return e.existingSkillName?e.feedback==="negative":!1}function kt(e,t){return xt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:St(e,t)?(me=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function At(e){return[...new Set(e.map(x).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function he(e){let t=At(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not invent or attempt any tool outside this list. If the request needs a capability none of these tools cover, do not silently refuse: consider exec-based scripts/OS commands, and otherwise state plainly which capability is missing.`}function Et(e){let t=[...new Set(e.map(x).filter(Boolean))].sort((i,a)=>i.localeCompare(a)),n=new Set(t),o=he(e),r=n.has("exec"),s=["read","search","write","edit","patch"].some(i=>n.has(i));return!r||!s?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function x(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function Mt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function It(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function vt(e){if(!e.eligibility?.length)return[...e.tools];let t=It(e.eligibility);return e.tools.filter(n=>{let o=x(n);if(!o)return!1;let r=t.get(o);return!r||Mt(r.status)})}function wt(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function Ot(e){let t=wt({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=vt({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:he(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:Et(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(l=>x(l)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Lt=["stop","aborted","timeout","cancelled","interrupted","error"],Pt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Ce(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Nt(e,t){return{...e,content:[...Ce(e.content),...Ce(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 Dt(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 Bt(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function Ut(e){return new Set((e??Lt).map(t=>t.trim().toLowerCase()))}function _e(e,t){return e?Ut(t).has(e.trim().toLowerCase()):!1}function Gt(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function j(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(l=>{if(l.role==="assistant"&&Array.isArray(l.tool_calls)){let c=l.tool_calls.filter(u=>Bt(u));return{...l,...c.length>0?{tool_calls:c}:{tool_calls:void 0}}}return{...l}}),n=new Set;for(let l of t)if(!(l.role!=="assistant"||!Array.isArray(l.tool_calls)))for(let c of l.tool_calls)typeof c.id=="string"&&c.id&&n.add(c.id);let o=t.filter(l=>l.role!=="tool"?!0:!!(l.tool_call_id&&n.has(l.tool_call_id))),r=new Set;for(let l of o)l.role==="tool"&&typeof l.tool_call_id=="string"&&l.tool_call_id&&r.add(l.tool_call_id);let s=[];for(let l of o){if(l.role==="assistant"&&Array.isArray(l.tool_calls)&&l.tool_calls.length>0){let c=l.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(c.length===0){let{tool_calls:u,...p}=l;p.content!=null&&p.content!==""&&s.push(p);continue}if(c.length<l.tool_calls.length){s.push({...l,tool_calls:c});continue}}s.push(l)}let i=Dt(s),a=[];for(let l of i){let c=a.length>0?a[a.length-1]:void 0;if(l.role==="user"&&c?.role==="user"){a[a.length-1]=Nt(c,l);continue}a.push(l)}return a}function $(e,t){return _e(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Pt)delete o[r];return o}):[...e]}function H(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function jt(e,t){let n=j(e),o=$(n,t);return H(o,t)}function be(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=_e(t?.stopReason,t?.forcedStopReasons),r=[];for(let c=0;c<e.length;c+=1){let u=e[c];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(c+1).some(m=>m&&typeof m=="object"&&m.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let p={...u};if(typeof p.id=="string"){let d=Gt(p.id);d.itemId?.startsWith("fc_")&&(p.id=d.callId)}r.push(p)}let s=new Set,i=new Map;for(let c of r){if(c.type!=="function_call")continue;let u=typeof c.call_id=="string"&&c.call_id?c.call_id:typeof c.id=="string"?c.id:void 0;u&&(s.add(u),i.set(u,c))}let a=new Set,l=[];for(let c of r)if(!(o&&c.type==="function_call")){if(c.type==="function_call_output"){let u=typeof c.call_id=="string"?c.call_id:"";if(!u||!s.has(u))continue;a.add(u)}l.push(c)}for(let[c]of i)a.has(c)||o||l.push({type:"function_call_output",call_id:c,output:n});return l}function $t(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function Ht(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function zt(e){let t=new Set,n=new Set;for(let o of e){if(o.type==="function_call"){let r=typeof o.call_id=="string"&&o.call_id?o.call_id:typeof o.id=="string"?o.id:"";r&&t.add(r)}o.type==="function_call_output"&&typeof o.call_id=="string"&&o.call_id&&n.add(o.call_id)}return[...t].filter(o=>!n.has(o))}function qt(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function Re(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Yt(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Xt(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Kt(e){let t=[],n=j(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=$(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=H(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Re({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:$t(r),completedToolCallIds:Ht(r)}),recoveryActions:t}}function Wt(e){let t=be(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:Re({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:zt(t),completedToolCallIds:qt(t)}),recoveryActions:n}}var Vt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Jt(e){return e?Vt.has(e):!0}function Zt(e){return e===429||e===529}function Qt(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var no={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function en(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var z=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var q="<fork-child-context>",Se="Fork started \u2014 processing in background";function tn(e){return JSON.stringify(e).includes(q)}function nn(e){return e<G}function on(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
19
+ ${m}`}))}if(l.length===0)return e;let u=[...e],p=-1;for(let d=0;d<u.length;d++)u[d].role==="system"&&(p=d);return u.splice(p+1,0,...l),u}function Qe(e,t,n=x){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let a of e){let l=a.tool_call_id??"";if(l&&t.has(l)){o+=n(a),r++,t.delete(l);continue}i.push(a)}let s=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:s}}function et(){return{stages:[]}}function tt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=se(e,t),s=ot(i,t,o);if(s.length===0)return{messages:i,stagedCount:0};for(let a of s)t.stages.push(a);return i=se(e,t),{messages:i,stagedCount:s.length}}function nt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:ie(e,t),committed:n}}function se(e,t){return t.stages.filter(o=>o.committed).length===0?e:ie(e,t)}function ie(e,t){let n=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),o=[...e];for(let r of n){let[i,s]=r.range;if(i>=o.length)continue;let a=Math.min(s,o.length),l={role:"system",content:r.summary};o.splice(i,a-i,l)}return o}function ot(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),s=-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==="")s<0&&(s=l),a++;else{if(a>=3){let p=`${s}-${s+a}`;i.has(p)||r.push({id:`collapse_${s}_${s+a}`,range:[s,s+a],summary:`[${a} tool results collapsed]`,committed:!1})}s=-1,a=0}}if(a>=3){let l=`${s}-${s+a}`;i.has(l)||r.push({id:`collapse_${s}_${s+a}`,range:[s,s+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}function rt(e){return[...new Set(e.map(S).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function ae(e){let t=rt(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not invent or attempt any tool outside this list. If the request needs a capability none of these tools cover, do not silently refuse: consider exec-based scripts/OS commands, and otherwise state plainly which capability is missing.`}function st(e){let t=[...new Set(e.map(S).filter(Boolean))].sort((s,a)=>s.localeCompare(a)),n=new Set(t),o=ae(e),r=n.has("exec"),i=["read","search","write","edit","patch"].some(s=>n.has(s));return!r||!i?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function S(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function it(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function at(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function lt(e){if(!e.eligibility?.length)return[...e.tools];let t=at(e.eligibility);return e.tools.filter(n=>{let o=S(n);if(!o)return!1;let r=t.get(o);return!r||it(r.status)})}function ct(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 ut(e){let t=ct({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,...r.length>0?{extraSystemPrompt:ae(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:st(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,s=typeof i?.name=="string"?i.name.trim():"";if(!s)throw new Error("tool_choice.function.name is required");let a=r.filter(l=>S(l)===s);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${s}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:s}},extraSystemPrompt:`You must call the ${s} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var pt=["stop","aborted","timeout","cancelled","interrupted","error"],dt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function le(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function mt(e,t){return{...e,content:[...le(e.content),...le(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 gt(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 i=ft(r);if(i.size!==0)for(let s=o+1;s<e.length;s+=1){if(t.has(s))continue;let a=e[s];a?.role==="tool"&&typeof a.tool_call_id=="string"&&i.has(a.tool_call_id)&&(n.push(a),t.add(s))}}return n}function yt(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 Tt(e){return new Set((e??pt).map(t=>t.trim().toLowerCase()))}function ce(e,t){return e?Tt(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 G(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=>yt(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 i=[];for(let l of o){if(l.role==="assistant"&&Array.isArray(l.tool_calls)&&l.tool_calls.length>0){let c=l.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(c.length===0){let{tool_calls:u,...p}=l;p.content!=null&&p.content!==""&&i.push(p);continue}if(c.length<l.tool_calls.length){i.push({...l,tool_calls:c});continue}}i.push(l)}let s=gt(i),a=[];for(let l of s){let c=a.length>0?a[a.length-1]:void 0;if(l.role==="user"&&c?.role==="user"){a[a.length-1]=mt(c,l);continue}a.push(l)}return a}function $(e,t){return ce(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of dt)delete o[r];return o}):[...e]}function j(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&o.add(i.tool_call_id);let r=[];for(let i of e)if(r.push({...i}),!(i.role!=="assistant"||!Array.isArray(i.tool_calls)||i.tool_calls.length===0))for(let s of i.tool_calls)typeof s.id!="string"||!s.id||o.has(s.id)||(o.add(s.id),r.push({role:"tool",tool_call_id:s.id,content:n}));return r}function Ct(e,t){let n=G(e),o=$(n,t);return j(o,t)}function ue(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=ce(t?.stopReason,t?.forcedStopReasons),r=[];for(let c=0;c<e.length;c+=1){let u=e[c];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(c+1).some(m=>m&&typeof m=="object"&&m.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let p={...u};if(typeof p.id=="string"){let d=ht(p.id);d.itemId?.startsWith("fc_")&&(p.id=d.callId)}r.push(p)}let i=new Set,s=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&&(i.add(u),s.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||!i.has(u))continue;a.add(u)}l.push(c)}for(let[c]of s)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 bt(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 Rt(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 pe(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function St(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 At(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function kt(e){let t=[],n=G(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=$(n,e.options);o.some((i,s)=>i!==n[s])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=j(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:pe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:_t(r),completedToolCallIds:bt(r)}),recoveryActions:t}}function Et(e){let t=ue(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:pe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:Rt(t),completedToolCallIds:xt(t)}),recoveryActions:n}}var Mt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function vt(e){return e?Mt.has(e):!0}function It(e){return e===429||e===529}function wt(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 Cn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Ot(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var H=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var bn=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Rn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var xn=720*60*60*1e3,z=4;var Sn=3600*1e3;var An=50*1024,kn=500*1024,En=500*1024*1024,Mn=50*1024*1024;var vn=60*1024;var q="<fork-child-context>",de="Fork started \u2014 processing in background";function Lt(e){return JSON.stringify(e).includes(q)}function Pt(e){return e<z}function Nt(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
20
20
 
21
21
  Your working directory is: ${e.worktreePath}
22
22
  All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${q}
23
23
 
24
24
  You are the "${t.agent.name}" agent.${o}
25
25
 
26
- ${t.taskPrompt}`}]};return n.push(r),n}function rn(e){return e.map(t=>({role:"tool",tool_call_id:t,content:Se}))}function sn(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolCapabilityProfile==="no_tools")return[];if(t.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent")}function an(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var ln={name:"general",label:"General Purpose",description:"A general-purpose sub-agent that can perform any task with full tool access.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!1},cn={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolCapabilityProfile:"read_tools",allowedTools:["read_file","search","web_search","web_fetch","memory"],canFork:!1,systemPromptSuffix:"You are READ-ONLY: never attempt to modify files or run mutating commands. Locate and understand code, then report concrete findings with file:line references. Read excerpts rather than whole files; surface conclusions, not raw dumps."},un={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolCapabilityProfile:"read_tools",allowedTools:["read_file","search","web_search","web_fetch","memory","task"],canFork:!1,systemPromptSuffix:"You PLAN but do not execute: never write files or run commands. Investigate enough to ground the plan in the real code, then return a concrete, step-by-step implementation plan naming the specific files and changes involved."},pn={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!0,systemPromptSuffix:"Implement the task directly by editing files. Read existing code before changing it, match the surrounding conventions, and verify your change compiles/passes where possible."},dn={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolCapabilityProfile:"read_tools",allowedTools:["web_search","web_fetch","read_file","search","memory"],canFork:!1,systemPromptSuffix:"Gather information from multiple sources before concluding. Distinguish facts from inferences, cite where each claim comes from, and synthesize \u2014 do not just dump search results."},mn={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolCapabilityProfile:"all_tools",allowedTools:["exec","read_file","search"],canFork:!1,systemPromptSuffix:"Verify by RUNNING things (tests, builds, type-checks) and reading the actual output \u2014 do not assume. Report a clear verdict (pass/fail) with the evidence that supports it."},Y=[ln,cn,un,pn,dn,mn];function fn(){return[...Y]}function gn(e){return Y.find(t=>t.name===e)}function yn(e){return Y.some(t=>t.name===e)}function Tn(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolCapabilityProfile==="no_tools")return[];if(e.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(o=>!n.has(o))}return e.canFork?[...t]:t.filter(n=>n!=="agent")}function hn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function Cn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function _n(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function bn(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function Rn(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function Sn(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}function xn(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
26
+ ${t.taskPrompt}`}]};return n.push(r),n}function Ft(e){return e.map(t=>({role:"tool",tool_call_id:t,content:de}))}function Dt(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolCapabilityProfile==="no_tools")return[];if(t.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent")}function Bt(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var Ut={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},Gt={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolCapabilityProfile:"read_tools",allowedTools:["read_file","search","web_search","web_fetch","memory"],canFork:!1,systemPromptSuffix:"You are READ-ONLY: never attempt to modify files or run mutating commands. Locate and understand code, then report concrete findings with file:line references. Read excerpts rather than whole files; surface conclusions, not raw dumps."},$t={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolCapabilityProfile:"read_tools",allowedTools:["read_file","search","web_search","web_fetch","memory","task"],canFork:!1,systemPromptSuffix:"You PLAN but do not execute: never write files or run commands. Investigate enough to ground the plan in the real code, then return a concrete, step-by-step implementation plan naming the specific files and changes involved."},jt={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."},Ht={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."},zt={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=[Ut,Gt,$t,jt,Ht,zt];function qt(){return[...Y]}function Yt(e){return Y.find(t=>t.name===e)}function Xt(e){return Y.some(t=>t.name===e)}function Wt(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolCapabilityProfile==="no_tools")return[];if(e.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(o=>!n.has(o))}return e.canFork?[...t]:t.filter(n=>n!=="agent")}function Kt(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function Vt(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Jt(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function Zt(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 Qt(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function en(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}function tn(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
27
27
  ${n.join(`
28
28
  `)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
29
29
  Step ${e.activeSkillContext.step}:
@@ -34,4 +34,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
34
34
 
35
35
  ${t.join(`
36
36
 
37
- `)}`}function kn(){return{attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function An(e){return!e.attemptedThisTurn}export{P as CacheAwareCompressionStrategy,N as CompressionMetricsCollector,F as ContextEngineRegistry,oe as DEFAULT_ADAPTIVE_BUDGET_CONFIG,Se as FORK_PLACEHOLDER_RESULT,q as FORK_SENTINEL_TAG,z as FallbackTriggeredError,O as HeadTailProtectedStrategy,L as IncrementalCompactStrategy,G as MAX_FORK_DEPTH,D as MicroCompactStrategy,I as SlidingWindowStrategy,v as SummarizeOldStrategy,w as ToolResultTrimStrategy,Yt as advanceToolLoopState,dt as applyContextCollapsesIfNeeded,Ot as applyToolChoicePolicy,xe as buildAssistantToolCallMessage,rn as buildForkPlaceholderResults,on as buildForkedMessages,xn as buildPostCompactRestorationMessage,kt as buildSkillInstruction,U as buildStructuredSummaryPrompt,ke as buildToolResultMessage,Te as buildToolSignature,_n as calculateTokenWarningState,nn as canForkAtDepth,tt as classifyError,rt as composeAsyncStrategies,ot as composeStrategies,st as computeAdaptiveBudget,Qt as computeRetryBackoff,pt as createCollapseStore,kn as createReactiveCompactState,hn as createTaskState,Cn as createTurnLoopGuardState,an as generateForkChildAgentId,gn as getBuiltInAgent,fn as getBuiltInAgents,Rt as getPatternStats,B as isAsyncCompressionStrategy,yn as isBuiltInAgent,Jt as isForegroundSource,tn as isInForkChild,en as isPersistentRetryEnabled,ee as isRetryableCategory,Zt as isTransientCapacityError,ct as postCompactFileRecovery,ye as recordPatternAndCheckThreshold,mt as recoverContextCollapseFromOverflow,Kt as recoverToolLoopStateFromChatConversation,Wt as recoverToolLoopStateFromResponsesItems,jt as repairOpenAiChatConversation,Tn as resolveAgentToolSet,bn as resolveApiErrorRecovery,sn as resolveForkChildTools,Rn as resolveOutputTokenEscalation,it as selectCompressionTier,Xt as settleToolLoopState,Sn as shouldAbortTurn,An as shouldAttemptReactiveCompact,ut as snipCompactIfNeeded};
37
+ `)}`}function nn(){return{attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function on(e){return!e.attemptedThisTurn}export{P as CacheAwareCompressionStrategy,N as CompressionMetricsCollector,F as ContextEngineRegistry,oe as DEFAULT_ADAPTIVE_BUDGET_CONFIG,de as FORK_PLACEHOLDER_RESULT,q as FORK_SENTINEL_TAG,H as FallbackTriggeredError,O as HeadTailProtectedStrategy,L as IncrementalCompactStrategy,z as MAX_FORK_DEPTH,D as MicroCompactStrategy,v as SlidingWindowStrategy,I as SummarizeOldStrategy,w as ToolResultTrimStrategy,St as advanceToolLoopState,tt as applyContextCollapsesIfNeeded,ut as applyToolChoicePolicy,me as buildAssistantToolCallMessage,Ft as buildForkPlaceholderResults,Nt as buildForkedMessages,tn as buildPostCompactRestorationMessage,U as buildStructuredSummaryPrompt,fe as buildToolResultMessage,Jt as calculateTokenWarningState,Pt as canForkAtDepth,ze as classifyError,Xe as composeAsyncStrategies,Ye as composeStrategies,We as computeAdaptiveBudget,wt as computeRetryBackoff,et as createCollapseStore,nn as createReactiveCompactState,Kt as createTaskState,Vt as createTurnLoopGuardState,Bt as generateForkChildAgentId,Yt as getBuiltInAgent,qt as getBuiltInAgents,B as isAsyncCompressionStrategy,Xt as isBuiltInAgent,vt as isForegroundSource,Lt as isInForkChild,Ot as isPersistentRetryEnabled,ee as isRetryableCategory,It as isTransientCapacityError,Ze as postCompactFileRecovery,nt as recoverContextCollapseFromOverflow,kt as recoverToolLoopStateFromChatConversation,Et as recoverToolLoopStateFromResponsesItems,Ct as repairOpenAiChatConversation,Wt as resolveAgentToolSet,Zt as resolveApiErrorRecovery,Dt as resolveForkChildTools,Qt as resolveOutputTokenEscalation,Ke as selectCompressionTier,At as settleToolLoopState,en as shouldAbortTurn,on as shouldAttemptReactiveCompact,Qe as snipCompactIfNeeded};
@@ -1,40 +1,41 @@
1
- import{readFile as F,readdir as oe,unlink as ne,stat as Ne,mkdir as Ue}from"node:fs/promises";import{existsSync as p,readFileSync as se,mkdirSync as ae,writeFileSync as Ae}from"node:fs";import{join as g}from"node:path";import{resolve as Ie}from"node:path";import{join as we}from"node:path";import{homedir as fe}from"node:os";import{join as f}from"node:path";import{existsSync as Qe}from"node:fs";import{createHash as le}from"node:crypto";import{resolve as ue}from"node:path";function N(r){return le("sha256").update(ue(r).toLowerCase()).digest("hex").slice(0,16)}var T=".qlogicagent";function y(){return process.env.QLOGICAGENT_HOME||f(fe(),T)}function E(){let r=process.env.QLOGIC_LLMROUTER_USER_ID?.trim();if(r)return r;let e=process.env.QLOGIC_IMPLICIT_OWNER_ID?.trim();if(e)return e;let t=process.env.QLOGIC_DEVICE_ID?.trim();return t?`oc_${t}`:"oc_local"}function ge(r){let e=r.trim();if(!e)throw new Error("ownerUserId is required for profile-scoped storage");return encodeURIComponent(e).replace(/\./g,"%2E")}function b(r=E()){return f(y(),"profiles",ge(r))}function X(r=E()){return f(b(r),"memory")}var de="projectData";function H(){return f(y(),de)}function U(r){if(!r)throw new Error("getProjectDataDirById: projectId is required");return f(H(),r)}function q(){return f(y(),"plugins")}function W(){return f(y(),"skills")}function B(){return f(b(),"settings.json")}function G(){return f(y(),"plugin-cache")}function z(){return f(y(),"mcp.json")}function J(){return f(y(),"marketplace.json")}function j(r){if(!r)throw new Error("getProjectAgentDir: cwd is required (must not fall back to process.cwd())");return f(r,T)}function Q(r){return f(j(r),"plugins")}function K(r){return f(j(r),"settings.json")}function Y(r){return f(j(r),"INSTRUCTIONS.md")}function V(r){return f(j(r),"rules")}import{resolve as et}from"node:path";var me=()=>{},A;function Z(){if(pe(),!A)throw new Error("host project authority negotiated but snapshot is not hydrated");return{activeProjectId:A.activeProjectId,projects:A.projects.map(r=>({...r}))}}function pe(){let r=me();if(!r)throw new Error("gateway project authority is not available");return r}function he(){let r=Z();return{activeProjectId:r.activeProjectId,projects:r.projects.map(e=>({...e}))}}function ee(r){return he().projects.find(e=>e.id===r)??null}function Pe(r){return ee(r)?r:N(r)}function xe(r){return U(Pe(r))}function te(r){return we(xe(r),"sessions")}var C=class{constructor(e={}){this.options=e}options;lastActiveWorkdir=null;getActiveProjectRoot(){return this.options.getActiveProjectRoot?.()??process.cwd()}setActiveWorkdir(e){let t=Ie(e);this.lastActiveWorkdir=t,this.options.setActiveWorkdir?.(t)}getActiveWorkdir(){return this.lastActiveWorkdir??this.getActiveProjectRoot()}resolveProjectDir(e){return this.options.resolveProjectDir?.(e)}resolveActiveOwnerUserId(){return E()}getUserAgentHome(){return y()}getOwnerProfileDir(e){return b(e)}getProfileMemoryDir(e){return X(e)}getUserSettingsPath(){return B()}getUserSkillsDir(){return W()}getUserPluginsDir(){return q()}getUserMcpConfigPath(){return z()}getUserPluginCacheDir(){return G()}getUserMarketplaceConfigPath(){return J()}getProjectAgentDir(e=this.getActiveProjectRoot()){return j(e)}getProjectSettingsPath(e=this.getActiveProjectRoot()){return K(e)}getProjectInstructionsPath(e=this.getActiveProjectRoot()){return Y(e)}getProjectPluginsDir(e=this.getActiveProjectRoot()){return Q(e)}getProjectRulesDir(e=this.getActiveProjectRoot()){return V(e)}getProjectSessionDataRoot(e=this.getActiveProjectRoot()){return te(e)}},je=new C;function re(){return je}import{readFile as gt,writeFile as ke,mkdir as ve,rename as De,unlink as Ee}from"node:fs/promises";import{dirname as be,join as $e}from"node:path";import{randomUUID as _e}from"node:crypto";async function D(r,e){let t=be(r);await ve(t,{recursive:!0});let n=$e(t,`.tmp-${_e()}`);try{await ke(n,e,"utf-8");let o;for(let s=0;s<3;s++)try{await De(n,r);return}catch(i){if(o=i,i.code!=="EPERM")throw i;await new Promise(a=>setTimeout(a,50*(s+1)))}throw o}catch(o){throw await Ee(n).catch(()=>{}),o}}var Se=/[一-鿿]/;function $(r){let e=[],t=r.toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[];for(let n of t){let o="",s=!1,i=()=>{if(o){if(s){o.length===1&&e.push(o);for(let a=0;a+1<o.length;a++)e.push(o.slice(a,a+2))}else e.push(o);o=""}};for(let a of n){let m=Se.test(a);o&&m!==s&&i(),s=m,o+=a}i()}return e}var Re=["add","replace","remove","create_file","write_file","read_file","delete_file","list_files","search","remember","temporal","feedback"],yt={type:"object",properties:{action:{type:"string",enum:Re,description:["Operation to perform:","","INDEX.md operations (project-level notes, always visible in system prompt):","- 'add' - Append a note to INDEX.md","- 'replace' - Replace text in INDEX.md (str_replace semantics)","- 'remove' - Remove text from INDEX.md","","Topic file operations (project-level, on-demand, for longer content):","- 'create_file' - Create a new .md topic file","- 'write_file' - Overwrite an existing topic file","- 'read_file' - Read a topic file","- 'delete_file' - Delete a topic file","- 'list_files' - List all memory topic files","","Long-term memory (user-level, persists across projects):","- 'remember' - Submit a fact/preference/lesson to the memory consolidation pipeline","- 'search' - Search long-term memory + local keyword match","- 'temporal' - Query memories by time range ('what happened last week')","","Feedback:","- 'feedback' - Mark memories as useful/irrelevant/outdated/wrong"].join(`
1
+ import{readFile as F,readdir as oe,unlink as ne,stat as se,mkdir as Ae}from"node:fs/promises";import{existsSync as p,readFileSync as ie,mkdirSync as ce,writeFileSync as Ce}from"node:fs";import{join as g}from"node:path";import{resolve as ke}from"node:path";import{join as xe}from"node:path";import{homedir as de}from"node:os";import{join as f}from"node:path";import{existsSync as Ye}from"node:fs";import{createHash as fe}from"node:crypto";import{resolve as ge}from"node:path";function N(r){return fe("sha256").update(ge(r).toLowerCase()).digest("hex").slice(0,16)}var T=".qlogicagent";function P(){return process.env.QLOGICAGENT_HOME||f(de(),T)}function b(){let r=process.env.QLOGIC_LLMROUTER_USER_ID?.trim();if(r)return r;let e=process.env.QLOGIC_IMPLICIT_OWNER_ID?.trim();if(e)return e;let t=process.env.QLOGIC_DEVICE_ID?.trim();return t?`oc_${t}`:"oc_local"}function me(r){let e=r.trim();if(!e)throw new Error("ownerUserId is required for profile-scoped storage");return encodeURIComponent(e).replace(/\./g,"%2E")}function $(r=b()){return f(P(),"profiles",me(r))}function X(r=b()){return f($(r),"memory")}var pe="projectData";function H(){return f(P(),pe)}function U(r){if(!r)throw new Error("getProjectDataDirById: projectId is required");return f(H(),r)}function q(){return f(P(),"plugins")}function W(){return f(P(),"skills")}function B(){return f($(),"settings.json")}function G(){return f(P(),"plugin-cache")}function z(){return f(P(),"mcp.json")}function J(){return f(P(),"marketplace.json")}function j(r){if(!r)throw new Error("getProjectAgentDir: cwd is required (must not fall back to process.cwd())");return f(r,T)}function Q(r){return f(j(r),"plugins")}function K(r){return f(j(r),"settings.json")}function Y(r){return f(j(r),"INSTRUCTIONS.md")}function V(r){return f(j(r),"rules")}import{resolve as rt}from"node:path";var he=()=>{},A;function Z(){if(ye(),!A)throw new Error("host project authority negotiated but snapshot is not hydrated");return{activeProjectId:A.activeProjectId,projects:A.projects.map(r=>({...r}))}}function ye(){let r=he();if(!r)throw new Error("gateway project authority is not available");return r}function we(){let r=Z();return{activeProjectId:r.activeProjectId,projects:r.projects.map(e=>({...e}))}}function ee(r){return we().projects.find(e=>e.id===r)??null}function Ie(r){return ee(r)?r:N(r)}function je(r){return U(Ie(r))}function te(r){return xe(je(r),"sessions")}var C=class{constructor(e={}){this.options=e}options;lastActiveWorkdir=null;getActiveProjectRoot(){return this.options.getActiveProjectRoot?.()??process.cwd()}setActiveWorkdir(e){let t=ke(e);this.lastActiveWorkdir=t,this.options.setActiveWorkdir?.(t)}getActiveWorkdir(){return this.lastActiveWorkdir??this.getActiveProjectRoot()}resolveProjectDir(e){return this.options.resolveProjectDir?.(e)}resolveActiveOwnerUserId(){return b()}getUserAgentHome(){return P()}getOwnerProfileDir(e){return $(e)}getProfileMemoryDir(e){return X(e)}getUserSettingsPath(){return B()}getUserSkillsDir(){return W()}getUserPluginsDir(){return q()}getUserMcpConfigPath(){return z()}getUserPluginCacheDir(){return G()}getUserMarketplaceConfigPath(){return J()}getProjectAgentDir(e=this.getActiveProjectRoot()){return j(e)}getProjectSettingsPath(e=this.getActiveProjectRoot()){return K(e)}getProjectInstructionsPath(e=this.getActiveProjectRoot()){return Y(e)}getProjectPluginsDir(e=this.getActiveProjectRoot()){return Q(e)}getProjectRulesDir(e=this.getActiveProjectRoot()){return V(e)}getProjectSessionDataRoot(e=this.getActiveProjectRoot()){return te(e)}},ve=new C;function re(){return ve}import{readFile as mt,writeFile as De,mkdir as Ee,rename as be,unlink as $e}from"node:fs/promises";import{dirname as Se,join as _e}from"node:path";import{randomUUID as Me}from"node:crypto";async function v(r,e){let t=Se(r);await Ee(t,{recursive:!0});let n=_e(t,`.tmp-${Me()}`);try{await De(n,e,"utf-8");let o;for(let s=0;s<3;s++)try{await be(n,r);return}catch(i){if(o=i,i.code!=="EPERM")throw i;await new Promise(a=>setTimeout(a,50*(s+1)))}throw o}catch(o){throw await $e(n).catch(()=>{}),o}}var Re=/[一-鿿]/;function S(r){let e=[],t=r.toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[];for(let n of t){let o="",s=!1,i=()=>{if(o){if(s){o.length===1&&e.push(o);for(let a=0;a+1<o.length;a++)e.push(o.slice(a,a+2))}else e.push(o);o=""}};for(let a of n){let m=Re.test(a);o&&m!==s&&i(),s=m,o+=a}i()}return e}var Ne=["add","replace","remove","create_file","write_file","read_file","delete_file","list_files","search","remember","temporal","feedback"],Pt={type:"object",properties:{action:{type:"string",enum:Ne,description:["Operation to perform:","","INDEX.md operations (project-level notes, always visible in system prompt):","- 'add' - Append a note to INDEX.md","- 'replace' - Replace text in INDEX.md (str_replace semantics)","- 'remove' - Remove text from INDEX.md","","Topic file operations (project-level, on-demand, for longer content):","- 'create_file' - Create a new .md topic file","- 'write_file' - Overwrite an existing topic file","- 'read_file' - Read a topic file","- 'delete_file' - Delete a topic file","- 'list_files' - List all memory topic files","","Long-term memory (user-level, persists across projects):","- 'remember' - Submit a fact/preference/lesson to the memory consolidation pipeline","- 'search' - Search long-term memory + local keyword match","- 'temporal' - Query memories by time range ('what happened last week')","","Feedback:","- 'feedback' - Mark memories as useful/irrelevant/outdated/wrong"].join(`
2
2
  `)},content:{type:"string",description:["Content for add/replace/create_file/write_file.","For INDEX.md notes: write concise, factual statements.","For topic files: can be longer (up to 8KB), use markdown formatting."].join(`
3
- `)},old_text:{type:"string",description:"For 'replace'/'remove': the exact text to find in INDEX.md."},new_text:{type:"string",description:"For 'replace': the replacement text."},file:{type:"string",description:"Filename for file operations (e.g. 'project-notes.md', 'lesson-esbuild.md'). Must be kebab-case .md."},query:{type:"string",description:"For 'search'/'temporal': natural language query to find relevant memories."},days:{type:"number",description:"For 'temporal': look back N days from today (default: 7)."},memory_ids:{type:"array",items:{type:"string"},description:"For 'feedback': IDs of memories to give feedback on."},signal:{type:"string",enum:["useful","irrelevant","outdated","wrong"],description:"For 'feedback': the feedback signal to apply."},category:{type:"string",enum:["preference","personal_fact","lesson","pattern","decision","context"],description:"For 'remember': categorize the memory (helps with future recall precision)."}},required:["action"]},wt=["Manage persistent memory across sessions. Two distinct systems with clear roles:","","## Project memory (INDEX.md + topic files)","Scope: current project / workspace. Visible every turn.","Use for: architecture decisions, file conventions, build commands, known issues, task logs.","Actions: add, replace, remove, create_file, write_file, read_file, delete_file, list_files.","","## Long-term memory (QMemory)","Scope: user-level, persists across all projects. Searched on demand.","Use for: user preferences, personal facts, recurring lessons, communication style, past insights.","Actions: remember, search, temporal, feedback.","","## When to store (guidelines):","- User explicitly says 'remember this' or 'note that' -> submit a high-priority memory candidate","- User states a preference (style, format, tools, habits) -> remember (long-term)","- Project-specific decision or fact -> add/create_file (project memory)","- A debugging lesson or insight that applies broadly -> remember (long-term)","- DO NOT store: trivial/obvious info, one-off questions, transient state","- DO NOT store: information the user did not share or confirm","","## When to recall:","- Use 'search' when you suspect relevant past context exists for the current task","- Use 'temporal' to find what happened in a specific time period","- Memory is auto-recalled each turn - manual search is for deeper queries"].join(`
4
- `),Me=[/ignore\s+(previous|all|above|prior)\s+instructions/i,/you\s+are\s+now\s+/i,/do\s+not\s+tell\s+the\s+user/i,/system\s+prompt\s+override/i,/忽略(之前|以上|上面|前面|所有|全部)的?.{0,4}(指令|指示|提示|设定|规则)/,/你现在(是|就是|扮演)/,/不要(告诉|透露给?|让)用户/,/系统提示词?.{0,6}(覆盖|无效|作废|重写)/];function k(r){return!Me.some(e=>e.test(r))}var l=12288,O=200,_=8192,Ce="memory",P="INDEX.md";function Fe(r){return g(re().getProjectAgentDir(r),Ce)}var Oe=/^[a-z0-9][a-z0-9\-_.]*\.md$/i;function S(r){return!(!Oe.test(r)||r===P||r.includes("..")||r.includes("/")||r.includes("\\"))}function Le(r){return r.trim().match(/^([A-Za-z][A-Za-z0-9_-]{2,})\s*:/)?.[1]??null}function Te(r,e){let t=r.split(`
5
- `),n=[],o=!1;for(let s=0;s<t.length;s++){let i=t[s];if(Xe(i)&&i.includes(e)){for(o=!0;s+1<t.length&&ce(t[s+1]);)s++;continue}n.push(i)}return o?n.join(`
6
- `):null}function Xe(r){return r.trim()!==""&&!r.startsWith("#")&&!r.startsWith("<!--")&&!ce(r)}function ce(r){return r.startsWith(" ")||r.startsWith(" ")}var R=new Map;async function x(r,e){let t=R.get(r)??Promise.resolve(),n,o=new Promise(i=>{n=i}),s=t.catch(()=>{}).then(()=>o);R.set(r,s),await t.catch(()=>{});try{return await e()}finally{n(),R.get(r)===s&&R.delete(r)}}var L=class{root;constructor(e){this.root=Fe(e)}getRootPath(){return this.root}ensureInitialized(){p(this.root)||ae(this.root,{recursive:!0});let e=g(this.root,P);if(!p(e)){let t=["# Memory Index","","<!-- Agent-managed memory. Lines here are always visible in system prompt.>","<!-- Use memory tool to add notes, or create topic files for longer content.>","","## User Profile","","## Notes",""].join(`
7
- `);He(e,t)}}getIndexForPrompt(){let e=g(this.root,P);if(!p(e))return"";let t;try{t=se(e,"utf-8")}catch(o){return o?.code!=="ENOENT"&&console.error(`[memdir] INDEX.md read failed \u2014 injected as empty this turn: ${o instanceof Error?o.message:String(o)}`),""}let n=t.split(`
3
+ `)},old_text:{type:"string",description:"For 'replace'/'remove': the exact text to find in INDEX.md."},new_text:{type:"string",description:"For 'replace': the replacement text."},file:{type:"string",description:"Filename for file operations (e.g. 'project-notes.md', 'lesson-esbuild.md'). Must be kebab-case .md."},query:{type:"string",description:"For 'search'/'temporal': natural language query to find relevant memories."},days:{type:"number",description:"For 'temporal': look back N days from today (default: 7)."},memory_ids:{type:"array",items:{type:"string"},description:"For 'feedback': IDs of memories to give feedback on."},signal:{type:"string",enum:["useful","irrelevant","outdated","wrong"],description:"For 'feedback': the feedback signal to apply."},category:{type:"string",enum:["preference","personal_fact","lesson","pattern","decision","context"],description:"For 'remember': categorize the memory (helps with future recall precision)."}},required:["action"]},xt=["Manage persistent memory across sessions. Two distinct systems with clear roles:","","## Project memory (INDEX.md + topic files)","Scope: current project / workspace. Visible every turn.","Use for: architecture decisions, file conventions, build commands, known issues, task logs.","Actions: add, replace, remove, create_file, write_file, read_file, delete_file, list_files.","","## Long-term memory (QMemory)","Scope: user-level, persists across all projects. Searched on demand.","Use for: user preferences, personal facts, recurring lessons, communication style, past insights.","Actions: remember, search, temporal, feedback.","","## When to store (guidelines):","- User explicitly says 'remember this' or 'note that' -> submit a high-priority memory candidate","- User states a preference (style, format, tools, habits) -> remember (long-term)","- Project-specific decision or fact -> add/create_file (project memory)","- A debugging lesson or insight that applies broadly -> remember (long-term)","- DO NOT store: trivial/obvious info, one-off questions, transient state","- DO NOT store: information the user did not share or confirm","","## When to recall:","- Use 'search' when you suspect relevant past context exists for the current task","- Use 'temporal' to find what happened in a specific time period","- Memory is auto-recalled each turn - manual search is for deeper queries"].join(`
4
+ `),Ue=[/ignore\s+(previous|all|above|prior)\s+instructions/i,/you\s+are\s+now\s+/i,/do\s+not\s+tell\s+the\s+user/i,/system\s+prompt\s+override/i,/忽略(之前|以上|上面|前面|所有|全部)的?.{0,4}(指令|指示|提示|设定|规则)/,/你现在(是|就是|扮演)/,/不要(告诉|透露给?|让)用户/,/系统提示词?.{0,6}(覆盖|无效|作废|重写)/];function k(r){return!Ue.some(e=>e.test(r))}var l=12288,O=200,_=8192,Fe="memory",x="INDEX.md";function Oe(r){return g(re().getProjectAgentDir(r),Fe)}var Le=/^[a-z0-9][a-z0-9\-_.]*\.md$/i;function M(r){return!(!Le.test(r)||r===x||r.includes("..")||r.includes("/")||r.includes("\\"))}function Te(r){return r.trim().match(/^([A-Za-z][A-Za-z0-9_-]{2,})\s*:/)?.[1]??null}function Xe(r,e){let t=r.split(`
5
+ `),n=[],o=!1;for(let s=0;s<t.length;s++){let i=t[s];if(He(i)&&i.includes(e)){for(o=!0;s+1<t.length&&le(t[s+1]);)s++;continue}n.push(i)}return o?n.join(`
6
+ `):null}function He(r){return r.trim()!==""&&!r.startsWith("#")&&!r.startsWith("<!--")&&!le(r)}function le(r){return r.startsWith(" ")||r.startsWith(" ")}var R=new Map;async function I(r,e){let t=R.get(r)??Promise.resolve(),n,o=new Promise(i=>{n=i}),s=t.catch(()=>{}).then(()=>o);R.set(r,s),await t.catch(()=>{});try{return await e()}finally{n(),R.get(r)===s&&R.delete(r)}}function qe(r){return r.split(`
7
+ `).every(e=>{let t=e.trim();return t===""||t.startsWith("#")||t.startsWith("<!--")&&t.endsWith(">")})}var L=class{root;constructor(e){this.root=Oe(e)}getRootPath(){return this.root}ensureInitialized(){p(this.root)||ce(this.root,{recursive:!0});let e=g(this.root,x);if(!p(e)){let t=["# Memory Index","","<!-- Agent-managed memory. Lines here are always visible in system prompt.>","<!-- Use memory tool to add notes, or create topic files for longer content.>","","## User Profile","","## Notes",""].join(`
8
+ `);We(e,t)}}getIndexForPrompt(){let e=g(this.root,x);if(!p(e))return"";let t;try{t=ie(e,"utf-8")}catch(o){return o?.code!=="ENOENT"&&console.error(`[memdir] INDEX.md read failed \u2014 injected as empty this turn: ${o instanceof Error?o.message:String(o)}`),""}if(qe(t))return"";let n=t.split(`
8
9
  `);return n.length>O&&(t=n.slice(0,O).join(`
9
10
  `)+`
10
11
 
11
12
  <!-- INDEX.md truncated: ${n.length} lines total, showing first ${O}>`),Buffer.byteLength(t,"utf-8")>l&&(t=Buffer.from(t,"utf-8").subarray(0,l).toString("utf-8")+`
12
13
 
13
- <!-- INDEX.md truncated at ${l} bytes>`),t}getIndexRaw(){let e=g(this.root,P);if(!p(e))return"";try{return se(e,"utf-8")}catch(t){return t?.code!=="ENOENT"&&console.error(`[memdir] INDEX.md read failed \u2014 treated as empty: ${t instanceof Error?t.message:String(t)}`),""}}getIndexUsage(){let e=this.getIndexRaw(),t=Buffer.byteLength(e,"utf-8"),n=e.split(`
14
- `).length;return{chars:t,lines:n,percent:Math.round(t/l*100)}}async addToIndex(e){return e.trim()?k(e)?x(this.root,async()=>{let t=this.getIndexRaw(),n=t.endsWith(`
14
+ <!-- INDEX.md truncated at ${l} bytes>`),t}getIndexRaw(){let e=g(this.root,x);if(!p(e))return"";try{return ie(e,"utf-8")}catch(t){return t?.code!=="ENOENT"&&console.error(`[memdir] INDEX.md read failed \u2014 treated as empty: ${t instanceof Error?t.message:String(t)}`),""}}getIndexUsage(){let e=this.getIndexRaw(),t=Buffer.byteLength(e,"utf-8"),n=e.split(`
15
+ `).length;return{chars:t,lines:n,percent:Math.round(t/l*100)}}async addToIndex(e){return e.trim()?k(e)?I(this.root,async()=>{let t=this.getIndexRaw(),n=t.endsWith(`
15
16
  `)?t+e.trim()+`
16
17
  `:t+`
17
18
  `+e.trim()+`
18
19
  `;if(Buffer.byteLength(n,"utf-8")>l){let s=this.autoCompactIndex(t,e.trim());if(s){await this.writeIndexUnlocked(s);let a=this.getIndexUsage();return{ok:!0,message:`Added to INDEX.md (auto-compacted old entries). [${a.chars}/${l} chars, ${a.percent}%]`,indexUsage:`${a.chars}/${l}`}}return{ok:!1,message:`INDEX.md would exceed limit (${this.getIndexUsage().chars}/${l} bytes) even after compaction. Create a topic file instead.`}}await this.writeIndexUnlocked(n);let o=this.getIndexUsage();return{ok:!0,message:`Added to INDEX.md. [${o.chars}/${l} chars, ${o.percent}%]`,indexUsage:`${o.chars}/${l}`}}):{ok:!1,message:"Content rejected: potential injection detected."}:{ok:!1,message:"Content cannot be empty."}}autoCompactIndex(e,t){let n=e.split(`
19
20
  `),o=Buffer.byteLength(t+`
20
- `,"utf-8"),s=l-o-64;if(s<256)return null;let i=u=>u.startsWith("#")||u.startsWith("<!--")||u.trim()==="",a=u=>u.startsWith(" ")||u.startsWith(" "),m=4,h=[...n],w=0;for(;Buffer.byteLength(h.join(`
21
- `),"utf-8")>s&&w<n.length;){let u=h.findIndex((v,M)=>M>=m&&!i(v)&&!a(v));if(u===-1)break;let I=1;for(;u+I<h.length&&a(h[u+I]);)I++;h.splice(u,I),w++}let c=h.join(`
21
+ `,"utf-8"),s=l-o-64;if(s<256)return null;let i=u=>u.startsWith("#")||u.startsWith("<!--")||u.trim()==="",a=u=>u.startsWith(" ")||u.startsWith(" "),m=4,h=[...n],y=0;for(;Buffer.byteLength(h.join(`
22
+ `),"utf-8")>s&&y<n.length;){let u=h.findIndex((D,E)=>E>=m&&!i(D)&&!a(D));if(u===-1)break;let w=1;for(;u+w<h.length&&a(h[u+w]);)w++;h.splice(u,w),y++}let c=h.join(`
22
23
  `),d=c.endsWith(`
23
24
  `)?c+t+`
24
25
  `:c+`
25
26
  `+t+`
26
- `;return Buffer.byteLength(d,"utf-8")<=l?d:null}async replaceInIndex(e,t){return e.trim()?t.trim()?k(t)?x(this.root,async()=>{let n=this.getIndexRaw(),o=n.split(e).length-1;if(o===0)return{ok:!1,message:`No match found for: "${e.slice(0,80)}"`};if(o>1)return{ok:!1,message:`Multiple matches (${o}) for: "${e.slice(0,80)}". Be more specific.`};let s=n.replace(e,t);if(Buffer.byteLength(s,"utf-8")>l)return{ok:!1,message:`Replacement would exceed INDEX.md limit (${Buffer.byteLength(s,"utf-8")}/${l} bytes).`};await this.writeIndexUnlocked(s);let i=this.getIndexUsage();return{ok:!0,message:`Replaced in INDEX.md. [${i.chars}/${l} chars]`,indexUsage:`${i.chars}/${l}`}}):{ok:!1,message:"Content rejected: potential injection detected."}:{ok:!1,message:"new_text cannot be empty. Use 'remove' to delete."}:{ok:!1,message:"old_text cannot be empty."}}async removeFromIndex(e){return e.trim()?x(this.root,async()=>{let t=this.getIndexRaw(),n=Le(e),o=n?Te(t,n):null;if(o===null){if(!t.includes(e))return{ok:!1,message:`No match found for: "${e.slice(0,80)}"`};o=t.replace(e,"")}o=o.replace(/\n{3,}/g,`
27
+ `;return Buffer.byteLength(d,"utf-8")<=l?d:null}async replaceInIndex(e,t){return e.trim()?t.trim()?k(t)?I(this.root,async()=>{let n=this.getIndexRaw(),o=n.split(e).length-1;if(o===0)return{ok:!1,message:`No match found for: "${e.slice(0,80)}"`};if(o>1)return{ok:!1,message:`Multiple matches (${o}) for: "${e.slice(0,80)}". Be more specific.`};let s=n.replace(e,t);if(Buffer.byteLength(s,"utf-8")>l)return{ok:!1,message:`Replacement would exceed INDEX.md limit (${Buffer.byteLength(s,"utf-8")}/${l} bytes).`};await this.writeIndexUnlocked(s);let i=this.getIndexUsage();return{ok:!0,message:`Replaced in INDEX.md. [${i.chars}/${l} chars]`,indexUsage:`${i.chars}/${l}`}}):{ok:!1,message:"Content rejected: potential injection detected."}:{ok:!1,message:"new_text cannot be empty. Use 'remove' to delete."}:{ok:!1,message:"old_text cannot be empty."}}async removeFromIndex(e){return e.trim()?I(this.root,async()=>{let t=this.getIndexRaw(),n=Te(e),o=n?Xe(t,n):null;if(o===null){if(!t.includes(e))return{ok:!1,message:`No match found for: "${e.slice(0,80)}"`};o=t.replace(e,"")}o=o.replace(/\n{3,}/g,`
27
28
 
28
- `),await this.writeIndexUnlocked(o);let s=this.getIndexUsage();return{ok:!0,message:`Removed from INDEX.md. [${s.chars}/${l} chars]`,indexUsage:`${s.chars}/${l}`}}):{ok:!1,message:"old_text cannot be empty."}}async listFiles(){if(!p(this.root))return[];let e=await oe(this.root),t=[];for(let n of e){if(n===P||!n.endsWith(".md"))continue;let o=g(this.root,n);try{let s=await Ne(o);if(!s.isFile())continue;let a=(await F(o,"utf-8")).split(`
29
- `).find(m=>m.trim()&&!m.startsWith("#"))?.trim();t.push({name:n,size:s.size,modifiedAt:s.mtime.toISOString(),preview:a?.slice(0,100)})}catch{}}return t.sort((n,o)=>o.modifiedAt.localeCompare(n.modifiedAt))}async createFile(e,t){if(!S(e))return{ok:!1,message:`Invalid filename: "${e}". Use kebab-case .md files (e.g. "project-notes.md").`};if(!k(t))return{ok:!1,message:"Content rejected: potential injection detected."};if(t.length>_)return{ok:!1,message:`Content too long (${t.length} chars, max ${_}).`};let n=g(this.root,e);if(p(n))return{ok:!1,message:`File already exists: "${e}". Use write_file to update.`};await this.ensureDir(),await D(n,t);let o=`- [${e}] \u2014 created ${new Date().toISOString().slice(0,10)}`;return{ok:!0,message:await this.appendIndexEntry(o)?`Created "${e}" (${t.length} chars). Entry added to INDEX.md.`:`Created "${e}" (${t.length} chars). WARNING: INDEX.md is full \u2014 the index entry was NOT added, so this file will not surface automatically. Remove stale INDEX.md entries, then add one for [${e}].`,file:e}}async writeFile(e,t){if(!S(e))return{ok:!1,message:`Invalid filename: "${e}". Use kebab-case .md files.`};if(!k(t))return{ok:!1,message:"Content rejected: potential injection detected."};if(t.length>_)return this.writeFileSplit(e,t);let n=g(this.root,e),o=!p(n);await this.ensureDir(),await D(n,t);let s=!0;if(o){let i=`- [${e}] \u2014 created ${new Date().toISOString().slice(0,10)}`;s=await this.appendIndexEntry(i)}return{ok:!0,message:`${o?"Created":"Updated"} "${e}" (${t.length} chars).`+(s?"":" WARNING: INDEX.md is full \u2014 no index entry was added, so this file will not surface automatically."),file:e}}async writeFileSplit(e,t){let n=e.replace(/\.md$/,""),o=t.split(/\n{2,}/),s=[],i="";for(let c of o)i.length+c.length+2>_*.9&&i.length>0?(s.push(i),i=c):i=i?i+`
29
+ `),await this.writeIndexUnlocked(o);let s=this.getIndexUsage();return{ok:!0,message:`Removed from INDEX.md. [${s.chars}/${l} chars]`,indexUsage:`${s.chars}/${l}`}}):{ok:!1,message:"old_text cannot be empty."}}async listFiles(){if(!p(this.root))return[];let e=await oe(this.root),t=[];for(let n of e){if(n===x||!n.endsWith(".md"))continue;let o=g(this.root,n);try{let s=await se(o);if(!s.isFile())continue;let a=(await F(o,"utf-8")).split(`
30
+ `).find(m=>m.trim()&&!m.startsWith("#"))?.trim();t.push({name:n,size:s.size,modifiedAt:s.mtime.toISOString(),preview:a?.slice(0,100)})}catch{}}return t.sort((n,o)=>o.modifiedAt.localeCompare(n.modifiedAt))}async createFile(e,t){if(!M(e))return{ok:!1,message:`Invalid filename: "${e}". Use kebab-case .md files (e.g. "project-notes.md").`};if(!k(t))return{ok:!1,message:"Content rejected: potential injection detected."};if(t.length>_)return{ok:!1,message:`Content too long (${t.length} chars, max ${_}).`};let n=g(this.root,e);if(p(n))return{ok:!1,message:`File already exists: "${e}". Use write_file to update.`};await this.ensureDir(),await v(n,t);let o=`- [${e}] \u2014 created ${new Date().toISOString().slice(0,10)}`;return{ok:!0,message:await this.appendIndexEntry(o)?`Created "${e}" (${t.length} chars). Entry added to INDEX.md.`:`Created "${e}" (${t.length} chars). WARNING: INDEX.md is full \u2014 the index entry was NOT added, so this file will not surface automatically. Remove stale INDEX.md entries, then add one for [${e}].`,file:e}}async writeFile(e,t){if(!M(e))return{ok:!1,message:`Invalid filename: "${e}". Use kebab-case .md files.`};if(!k(t))return{ok:!1,message:"Content rejected: potential injection detected."};if(t.length>_)return this.writeFileSplit(e,t);let n=g(this.root,e),o=!p(n);await this.ensureDir(),await v(n,t);let s=!0;if(o){let i=`- [${e}] \u2014 created ${new Date().toISOString().slice(0,10)}`;s=await this.appendIndexEntry(i)}return{ok:!0,message:`${o?"Created":"Updated"} "${e}" (${t.length} chars).`+(s?"":" WARNING: INDEX.md is full \u2014 no index entry was added, so this file will not surface automatically."),file:e}}async writeFileSplit(e,t){let n=e.replace(/\.md$/,""),o=t.split(/\n{2,}/),s=[],i="";for(let c of o)i.length+c.length+2>_*.9&&i.length>0?(s.push(i),i=c):i=i?i+`
30
31
 
31
- `+c:c;i&&s.push(i);let a=[];for(let c=0;c<s.length;c++){let d=`${n}-${c+1}.md`,u=g(this.root,d);await this.ensureDir(),await D(u,s[c]),a.push(d)}let m=g(this.root,e);p(m)&&(await ne(m),await x(this.root,async()=>{let c=this.getIndexRaw(),d=new RegExp(`^.*\\[${ie(e)}\\].*$\\n?`,"m");d.test(c)&&await this.writeIndexUnlocked(c.replace(d,"").replace(/\n{3,}/g,`
32
+ `+c:c;i&&s.push(i);let a=[];for(let c=0;c<s.length;c++){let d=`${n}-${c+1}.md`,u=g(this.root,d);await this.ensureDir(),await v(u,s[c]),a.push(d)}let m=g(this.root,e);p(m)&&(await ne(m),await I(this.root,async()=>{let c=this.getIndexRaw(),d=new RegExp(`^.*\\[${ae(e)}\\].*$\\n?`,"m");d.test(c)&&await this.writeIndexUnlocked(c.replace(d,"").replace(/\n{3,}/g,`
32
33
 
33
- `))}));let h=this.getIndexRaw(),w=0;for(let c of a)if(!h.includes(`[${c}]`)){let d=`- [${c}] \u2014 auto-split ${new Date().toISOString().slice(0,10)}`;await this.appendIndexEntry(d)||w++}return{ok:!0,message:`Auto-split "${e}" into ${s.length} parts (${t.length} chars total): ${a.join(", ")}`+(w>0?` WARNING: INDEX.md is full \u2014 ${w} part(s) got no index entry and will not surface automatically.`:""),file:a[0]}}async readFile(e){if(!S(e)&&e!==P)return{ok:!1,message:`Invalid filename: "${e}".`};let t=g(this.root,e);try{let n=await F(t,"utf-8");return{ok:!0,content:n,message:`Read "${e}" (${n.length} chars).`}}catch(n){return n.code==="ENOENT"?{ok:!1,message:`File not found: "${e}".`}:{ok:!1,message:`Error reading "${e}": ${n.message}`}}}async deleteFile(e){if(e===P)return{ok:!1,message:"Cannot delete INDEX.md. Use 'remove' to clear entries."};if(!S(e))return{ok:!1,message:`Invalid filename: "${e}".`};let t=g(this.root,e);return p(t)?(await ne(t),await x(this.root,async()=>{let n=this.getIndexRaw(),o=new RegExp(`^.*\\[${ie(e)}\\].*$\\n?`,"m");if(o.test(n)){let s=n.replace(o,"").replace(/\n{3,}/g,`
34
+ `))}));let h=this.getIndexRaw(),y=0;for(let c of a)if(!h.includes(`[${c}]`)){let d=`- [${c}] \u2014 auto-split ${new Date().toISOString().slice(0,10)}`;await this.appendIndexEntry(d)||y++}return{ok:!0,message:`Auto-split "${e}" into ${s.length} parts (${t.length} chars total): ${a.join(", ")}`+(y>0?` WARNING: INDEX.md is full \u2014 ${y} part(s) got no index entry and will not surface automatically.`:""),file:a[0]}}async readFile(e){if(!M(e)&&e!==x)return{ok:!1,message:`Invalid filename: "${e}".`};let t=g(this.root,e);try{let n=await F(t,"utf-8");return{ok:!0,content:n,message:`Read "${e}" (${n.length} chars).`}}catch(n){return n.code==="ENOENT"?{ok:!1,message:`File not found: "${e}".`}:{ok:!1,message:`Error reading "${e}": ${n.message}`}}}async deleteFile(e){if(e===x)return{ok:!1,message:"Cannot delete INDEX.md. Use 'remove' to clear entries."};if(!M(e))return{ok:!1,message:`Invalid filename: "${e}".`};let t=g(this.root,e);return p(t)?(await ne(t),await I(this.root,async()=>{let n=this.getIndexRaw(),o=new RegExp(`^.*\\[${ae(e)}\\].*$\\n?`,"m");if(o.test(n)){let s=n.replace(o,"").replace(/\n{3,}/g,`
34
35
 
35
- `);await this.writeIndexUnlocked(s)}}),{ok:!0,message:`Deleted "${e}" and removed INDEX.md entry.`,file:e}):{ok:!1,message:`File not found: "${e}".`}}async searchLocal(e){if(!p(this.root))return[];let t=Array.from(new Set($(e)));if(t.length===0)return[];let n=await oe(this.root),o=[];for(let s of n){if(!s.endsWith(".md"))continue;let i=g(this.root,s);try{let a=await F(i,"utf-8"),m=new Set($(a)),h=t.filter(u=>m.has(u)).length;if(h===0)continue;let w=a.split(`
36
- `),c="",d=0;for(let u of w){let I=new Set($(u)),v=t.filter(M=>I.has(M)).length;v>d&&(d=v,c=u.trim())}o.push({file:s,snippet:c.slice(0,200),score:h/t.length})}catch{}}return o.sort((s,i)=>i.score-s.score).slice(0,10)}async writeIndex(e){await x(this.root,()=>this.writeIndexUnlocked(e))}async writeIndexUnlocked(e){await this.ensureDir(),await D(g(this.root,P),e)}async ensureDir(){p(this.root)||await Ue(this.root,{recursive:!0})}async appendIndexEntry(e){return x(this.root,async()=>{let t=this.getIndexRaw();if(t.includes(e))return!0;let n=t.endsWith(`
36
+ `);await this.writeIndexUnlocked(s)}}),{ok:!0,message:`Deleted "${e}" and removed INDEX.md entry.`,file:e}):{ok:!1,message:`File not found: "${e}".`}}async searchLocal(e){if(!p(this.root))return[];let t=Array.from(new Set(S(e)));if(t.length===0)return[];let n=await oe(this.root),o=[];for(let s of n){if(!s.endsWith(".md")||s===x)continue;let i=g(this.root,s);try{let[a,m]=await Promise.all([F(i,"utf-8"),se(i)]),h=new Set(S(a)),y=t.filter(w=>h.has(w)).length;if(y===0)continue;let c=a.split(`
37
+ `),d="",u=0;for(let w of c){let D=new Set(S(w)),E=t.filter(ue=>D.has(ue)).length;E>u&&(u=E,d=w.trim())}o.push({file:s,snippet:d.slice(0,200),score:y/t.length,mtimeMs:m.mtimeMs})}catch{}}return o.sort((s,i)=>i.score-s.score).slice(0,10)}async writeIndex(e){await I(this.root,()=>this.writeIndexUnlocked(e))}async writeIndexUnlocked(e){await this.ensureDir(),await v(g(this.root,x),e)}async ensureDir(){p(this.root)||await Ae(this.root,{recursive:!0})}async appendIndexEntry(e){return I(this.root,async()=>{let t=this.getIndexRaw();if(t.includes(e))return!0;let n=t.endsWith(`
37
38
  `)?t+e+`
38
39
  `:t+`
39
40
  `+e+`
40
- `;if(Buffer.byteLength(n,"utf-8")<=l)return await this.writeIndexUnlocked(n),!0;let o=this.autoCompactIndex(t,e);return o?(await this.writeIndexUnlocked(o),!0):(console.error(`[memdir] INDEX.md full \u2014 entry not added (file stays invisible to recall): ${e.slice(0,80)}`),!1)})}};function He(r,e){let t=g(r,"..");p(t)||ae(t,{recursive:!0}),Ae(r,e,"utf-8")}function ie(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}export{L as Memdir};
41
+ `;if(Buffer.byteLength(n,"utf-8")<=l)return await this.writeIndexUnlocked(n),!0;let o=this.autoCompactIndex(t,e);return o?(await this.writeIndexUnlocked(o),!0):(console.error(`[memdir] INDEX.md full \u2014 entry not added (file stays invisible to recall): ${e.slice(0,80)}`),!1)})}};function We(r,e){let t=g(r,"..");p(t)||ce(t,{recursive:!0}),Ce(r,e,"utf-8")}function ae(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}export{L as Memdir};