qlogicagent 2.20.6 → 2.20.7

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 (183) hide show
  1. package/README.md +27 -54
  2. package/dist/agent-contract.js +1 -1
  3. package/dist/agent.js +42 -41
  4. package/dist/cli.js +1 -1
  5. package/dist/host-contract.js +1 -1
  6. package/dist/index.js +539 -565
  7. package/dist/orchestration.js +14 -14
  8. package/dist/project-memory-host.js +30 -33
  9. package/dist/protocol.js +1 -1
  10. package/dist/types/agent/memory-recall-context.d.ts +7 -0
  11. package/dist/types/agent/tool-loop/artifact-final-contract.d.ts +2 -0
  12. package/dist/types/agent/tool-loop/direct-response-contract.d.ts +12 -0
  13. package/dist/types/agent/tool-loop/final-status-stream-suppressor.d.ts +22 -0
  14. package/dist/types/agent/tool-loop/loop-helpers.d.ts +2 -2
  15. package/dist/types/agent/tool-loop.d.ts +5 -1
  16. package/dist/types/agent/types.d.ts +27 -15
  17. package/dist/types/cli/acp-commands.d.ts +1 -1
  18. package/dist/types/cli/acp-extended-handlers.d.ts +13 -3
  19. package/dist/types/cli/agent-runtime-session-state.d.ts +1 -0
  20. package/dist/types/cli/base-tool-bootstrap.d.ts +0 -7
  21. package/dist/types/cli/community-skill-installer.d.ts +2 -0
  22. package/dist/types/cli/core-tool-coordinator.d.ts +0 -3
  23. package/dist/types/cli/core-tools/registry.d.ts +1 -4
  24. package/dist/types/cli/handlers/config-handler.d.ts +0 -1
  25. package/dist/types/cli/handlers/goal-handler.d.ts +24 -0
  26. package/dist/types/cli/handlers/memory-handler.d.ts +1 -2
  27. package/dist/types/cli/handlers/skill-curator-handler.d.ts +8 -0
  28. package/dist/types/cli/handlers/turn-handler.d.ts +9 -12
  29. package/dist/types/cli/memory-candidate-service.d.ts +1 -8
  30. package/dist/types/cli/memory-coordinator.d.ts +1 -13
  31. package/dist/types/cli/product-acp-params.d.ts +1 -0
  32. package/dist/types/cli/provider-core-facade.d.ts +2 -30
  33. package/dist/types/cli/rpc-registry.d.ts +2 -4
  34. package/dist/types/cli/runtime-hook-bootstrap.d.ts +1 -2
  35. package/dist/types/cli/stdio-acp-request-host.d.ts +1 -2
  36. package/dist/types/cli/stdio-rpc-handler-hosts.d.ts +0 -2
  37. package/dist/types/cli/stdio-runtime-bootstrap.d.ts +0 -7
  38. package/dist/types/cli/stdio-runtime-services.d.ts +1 -8
  39. package/dist/types/cli/stdio-server.d.ts +0 -4
  40. package/dist/types/cli/tool-bootstrap-core-registration.d.ts +0 -4
  41. package/dist/types/cli/tool-bootstrap.d.ts +0 -17
  42. package/dist/types/contracts/memory-recall-packet.d.ts +31 -0
  43. package/dist/types/contracts/memory-response-contract.d.ts +2 -0
  44. package/dist/types/contracts/tool-execution-evidence.d.ts +8 -0
  45. package/dist/types/contracts/tool-name.d.ts +10 -0
  46. package/dist/types/contracts/turn-event.d.ts +36 -3
  47. package/dist/types/host-contract/acp-content.d.ts +45 -0
  48. package/dist/types/host-contract/index.d.ts +59 -48
  49. package/dist/types/orchestration/agent-instance.d.ts +21 -1
  50. package/dist/types/orchestration/agent-roster.d.ts +14 -15
  51. package/dist/types/orchestration/dag-scheduler.d.ts +4 -0
  52. package/dist/types/orchestration/goal-context-envelope.d.ts +7 -0
  53. package/dist/types/orchestration/goal-loop-coordinator.d.ts +55 -12
  54. package/dist/types/orchestration/goal-mode-adapters.d.ts +13 -1
  55. package/dist/types/orchestration/goal-run-persistence.d.ts +9 -2
  56. package/dist/types/orchestration/goal-run-types.d.ts +127 -13
  57. package/dist/types/orchestration/index.d.ts +1 -1
  58. package/dist/types/orchestration/product-persistence.d.ts +10 -1
  59. package/dist/types/orchestration/product-planner.d.ts +3 -3
  60. package/dist/types/orchestration/testing/delegate-test-bridge.d.ts +1 -0
  61. package/dist/types/orchestration/workflow/data-item.d.ts +1 -1
  62. package/dist/types/orchestration/workflow/expression.d.ts +1 -2
  63. package/dist/types/orchestration/workflow/workflow-patch.d.ts +1 -2
  64. package/dist/types/orchestration/workflow/workflow-render.d.ts +1 -2
  65. package/dist/types/project-memory-host.d.ts +1 -0
  66. package/dist/types/protocol/agent-contract.d.ts +10 -8
  67. package/dist/types/protocol/methods.d.ts +2 -19
  68. package/dist/types/protocol/notifications.d.ts +1 -1
  69. package/dist/types/protocol/wire/acp-agent-management.d.ts +48 -6
  70. package/dist/types/protocol/wire/acp-protocol.d.ts +11 -24
  71. package/dist/types/protocol/wire/agent-methods.d.ts +5 -142
  72. package/dist/types/protocol/wire/chat-types.d.ts +50 -0
  73. package/dist/types/protocol/wire/index.d.ts +2 -2
  74. package/dist/types/protocol/wire/notification-payloads.d.ts +73 -122
  75. package/dist/types/protocol/wire/thread-protocol.d.ts +4 -40
  76. package/dist/types/runtime/community/community-consent-client.d.ts +0 -13
  77. package/dist/types/runtime/context/context-compression-strategies.d.ts +29 -0
  78. package/dist/types/runtime/context/context-envelope.d.ts +3 -0
  79. package/dist/types/runtime/execution/dream-agent.d.ts +4 -5
  80. package/dist/types/runtime/execution/mcp-capability-selection.d.ts +54 -0
  81. package/dist/types/runtime/execution/memory-decay.d.ts +1 -1
  82. package/dist/types/runtime/execution/search-result-quality.d.ts +22 -0
  83. package/dist/types/runtime/execution/streaming-tool-executor.d.ts +2 -0
  84. package/dist/types/runtime/execution/tool-result-storage.d.ts +44 -0
  85. package/dist/types/runtime/hooks/memory-hooks.d.ts +3 -2
  86. package/dist/types/runtime/infra/agent-paths.d.ts +0 -8
  87. package/dist/types/runtime/infra/default-path-service.d.ts +0 -2
  88. package/dist/types/runtime/infra/llmrouter-managed-inference.d.ts +54 -1
  89. package/dist/types/runtime/infra/media-persistence.d.ts +6 -36
  90. package/dist/types/runtime/memory/implicit-extraction.d.ts +7 -15
  91. package/dist/types/runtime/memory/memory-recall-attribution.d.ts +24 -0
  92. package/dist/types/runtime/ports/agent-runtime-ports.d.ts +14 -0
  93. package/dist/types/runtime/ports/index.d.ts +1 -3
  94. package/dist/types/runtime/ports/memory-provider.d.ts +2 -19
  95. package/dist/types/runtime/ports/memory-writer.d.ts +1 -1
  96. package/dist/types/runtime/ports/path-service.d.ts +0 -2
  97. package/dist/types/runtime/prompt/capability-routing-policy.d.ts +13 -0
  98. package/dist/types/runtime/prompt/environment-context.d.ts +3 -6
  99. package/dist/types/runtime/prompt/fresh-workspace-evidence.d.ts +8 -13
  100. package/dist/types/runtime/prompt/tool-necessity-policy.d.ts +12 -0
  101. package/dist/types/skills/mcp/mcp-manager.d.ts +29 -4
  102. package/dist/types/skills/memory/host-memory-provider.d.ts +3 -9
  103. package/dist/types/skills/memory/memdir.d.ts +1 -1
  104. package/dist/types/skills/memory/memory-content-safety.d.ts +1 -0
  105. package/dist/types/skills/permissions/hook-runner.d.ts +3 -3
  106. package/dist/types/skills/portable-tool.d.ts +5 -0
  107. package/dist/types/skills/skill-system/skill-lifecycle.d.ts +1 -0
  108. package/dist/types/skills/tools/exec-tool.d.ts +1 -5
  109. package/dist/types/skills/tools/shell/command-compatibility.d.ts +3 -0
  110. package/dist/types/skills/tools/shell/index.d.ts +4 -3
  111. package/dist/types/skills/tools/shell/shell-exec.d.ts +15 -8
  112. package/dist/types/skills/tools/shell/shell-provider.d.ts +26 -0
  113. package/dist/types/transport/acp-server.d.ts +4 -1
  114. package/dist/types/transport/host-community-client.d.ts +0 -1
  115. package/dist/types/transport/host-request-client.d.ts +1 -0
  116. package/dist/types/transport/host-run-state-client.d.ts +1 -1
  117. package/dist/workflow-host.js +6 -6
  118. package/package.json +4 -3
  119. package/dist/skills/mcp/astraclaw-native-mcp-server.js +0 -12
  120. package/dist/types/cli/core-tools/checkpoint-tool-bootstrap.d.ts +0 -9
  121. package/dist/types/cli/core-tools/checkpoint-tool-service.d.ts +0 -7
  122. package/dist/types/cli/core-tools/config-tool-bootstrap.d.ts +0 -7
  123. package/dist/types/cli/core-tools/config-tool-service.d.ts +0 -13
  124. package/dist/types/cli/core-tools/monitor-tool-bootstrap.d.ts +0 -7
  125. package/dist/types/cli/core-tools/monitor-tool-service.d.ts +0 -6
  126. package/dist/types/cli/dev-tool-bootstrap.d.ts +0 -9
  127. package/dist/types/cli/dev-tools/dev-tool-bootstrap-service.d.ts +0 -7
  128. package/dist/types/cli/dev-tools/dev-tool-registry.d.ts +0 -8
  129. package/dist/types/cli/dev-tools/incremental-repo-map.d.ts +0 -81
  130. package/dist/types/cli/dev-tools/lsp-supervisor.d.ts +0 -59
  131. package/dist/types/cli/dev-tools/lsp-tool-service.d.ts +0 -7
  132. package/dist/types/cli/handlers/media-handler.d.ts +0 -19
  133. package/dist/types/cli/handlers/skills-handler.d.ts +0 -37
  134. package/dist/types/cli/industrial-runtime-store.d.ts +0 -16
  135. package/dist/types/cli/media-capability-schema.d.ts +0 -49
  136. package/dist/types/cli/media-file-api-service.d.ts +0 -73
  137. package/dist/types/cli/media-file-tool-service.d.ts +0 -13
  138. package/dist/types/cli/media-inline.d.ts +0 -31
  139. package/dist/types/cli/media-runtime-facade.d.ts +0 -51
  140. package/dist/types/cli/media-understanding.d.ts +0 -102
  141. package/dist/types/cli/skill-invocation-service.d.ts +0 -10
  142. package/dist/types/cli/skill-tools-bootstrap.d.ts +0 -35
  143. package/dist/types/cli/skills-query-service.d.ts +0 -41
  144. package/dist/types/cli/tool-bootstrap-media-registration.d.ts +0 -20
  145. package/dist/types/cli/turn-media-setup.d.ts +0 -34
  146. package/dist/types/cli/turn-preview-browser-setup.d.ts +0 -15
  147. package/dist/types/runtime/infra/astraclaw-capabilities.d.ts +0 -33
  148. package/dist/types/runtime/infra/builtin-skills-seed.d.ts +0 -31
  149. package/dist/types/runtime/infra/checkpoint-backend.d.ts +0 -9
  150. package/dist/types/runtime/infra/industrial-runtime-session-server.d.ts +0 -20
  151. package/dist/types/runtime/infra/migrate-project-skills.d.ts +0 -24
  152. package/dist/types/runtime/infra/project-skill-manifest.d.ts +0 -21
  153. package/dist/types/runtime/infra/skill-resolver.d.ts +0 -74
  154. package/dist/types/runtime/infra/worktree-backend.d.ts +0 -86
  155. package/dist/types/runtime/ports/checkpoint-contracts.d.ts +0 -19
  156. package/dist/types/runtime/ports/worktree-contracts.d.ts +0 -22
  157. package/dist/types/skills/mcp/astraclaw-native-mcp-server.d.ts +0 -1
  158. package/dist/types/skills/memory/memory-tool.d.ts +0 -87
  159. package/dist/types/skills/tools/checkpoint-tool.d.ts +0 -66
  160. package/dist/types/skills/tools/config-tool.d.ts +0 -61
  161. package/dist/types/skills/tools/file-management-tool.d.ts +0 -90
  162. package/dist/types/skills/tools/image-generate-tool.d.ts +0 -98
  163. package/dist/types/skills/tools/instructions-tool.d.ts +0 -65
  164. package/dist/types/skills/tools/lsp-tool.d.ts +0 -153
  165. package/dist/types/skills/tools/media-cancel-tool.d.ts +0 -30
  166. package/dist/types/skills/tools/media-understand-tool.d.ts +0 -28
  167. package/dist/types/skills/tools/monitor-tool.d.ts +0 -113
  168. package/dist/types/skills/tools/music-generate-tool.d.ts +0 -80
  169. package/dist/types/skills/tools/notebook-edit-tool.d.ts +0 -15
  170. package/dist/types/skills/tools/preview-browser-tool.d.ts +0 -136
  171. package/dist/types/skills/tools/repo-map-tool.d.ts +0 -52
  172. package/dist/types/skills/tools/skill-tool.d.ts +0 -142
  173. package/dist/types/skills/tools/sleep-tool.d.ts +0 -49
  174. package/dist/types/skills/tools/stt-tool.d.ts +0 -33
  175. package/dist/types/skills/tools/subagent-decision-tool.d.ts +0 -15
  176. package/dist/types/skills/tools/three-d-generate-tool.d.ts +0 -46
  177. package/dist/types/skills/tools/tts-tool.d.ts +0 -50
  178. package/dist/types/skills/tools/video-edit-tool.d.ts +0 -72
  179. package/dist/types/skills/tools/video-generate-tool.d.ts +0 -162
  180. package/dist/types/skills/tools/video-merge-tool.d.ts +0 -105
  181. package/dist/types/skills/tools/video-upscale-tool.d.ts +0 -45
  182. package/dist/types/skills/tools/voice-clone-tool.d.ts +0 -40
  183. package/dist/types/skills/tools/worktree-tool.d.ts +0 -69
@@ -1,29 +1,29 @@
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(`}
1
+ function be(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Re(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 xe=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,T={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Ae=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Se=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,ke=512,Ee=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Me=new Set([500,502,503,504,521,522,523,524,529]),Ie=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],ve=["upgrade your plan","upgrade plan","current plan","subscription"],we=["daily","weekly","monthly"],Oe=["try again","retry","temporary","cooldown"],Le=["usage limit","rate limit","organization usage"],Pe=["organization","workspace"],Ne=["billing period","exceeded","reached","exhausted"],De=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,Fe=/^(?: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 Be(e){return h(e,T.format)}function Q(e){return h(e,T.rateLimit)}function Ue(e){return h(e,T.timeout)}function Ge(e){return xe.test(e)}function P(e){let t=e.toLowerCase();return t?e.length>ke?Se.test(t):h(t,T.billing)?!0:Ae.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function ee(e){return h(e,T.authPermanent)}function $e(e){return h(e,T.auth)}function te(e){return h(e,T.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function je(e){return y(e,Ie)||y(e,ve)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function ze(e){let t=y(e,we),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,Pe);return y(e,Oe)&&y(e,Le)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,Ne))}function qe(e){return e.trim().toLowerCase().replace(Fe,"").trim()}function ne(e){let t=qe(e);return!t||je(t)?"billing":Q(t)||ze(t)?"rate_limit":"billing"}function He(e){return De.test(e)?ne(e):null}function oe(e){let t=e.match(Ee);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Ye(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Xe(e){let t=e.trim();if(!t)return!1;let n=oe(t);return n?Me.has(n.code):!1}function re(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?ne(t):"billing":e===429?"rate_limit":e===401||e===403?t&&ee(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&te(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&P(t)?"billing":"format":null}function We(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function Ke(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 se(e){if(Ke(e))return"session_expired";if(We(e))return"model_not_found";let t=He(e);return t||(Ge(e)?P(e)?"billing":"rate_limit":Q(e)?"rate_limit":te(e)?"overloaded":Xe(e)?oe(e.trim())?.code===529?"overloaded":"timeout":Ye(e)?"timeout":Be(e)?"format":P(e)?"billing":Ue(e)?"timeout":ee(e)?"auth_permanent":$e(e)?"auth":null)}var Ve=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ie(e){return Ve.has(e)}var Je={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"};function Ze(e,t){let n=re(e,t)??(t?se(t):null);return n?Je[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function q(e){return typeof e.compressAsync=="function"}var E="[Context capsule v1]";function C(e){return e.replace(/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|password|passwd|secret)\b\s*[:=]\s*["']?[^\s"',;]+/giu,"$1=[REDACTED]").replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}\b/gu,"[REDACTED_TOKEN]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}\b/giu,"Bearer [REDACTED]")}function Qe(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function A(e){if(!(!e||typeof e.content!="string"||!e.content.startsWith(E)))try{let t=JSON.parse(e.content.slice(E.length).trim());return t?.receipt?.version===1&&typeof t.receipt.digest=="string"?t:void 0}catch{return}}function ce(e,t,n,o){let r=e.map(c=>c.itemId).filter(c=>!!c),i={...o?.state.anchors??{}};for(let c of e)for(let u of c.contextAnchors??[]){let p=i[u.category]??[];i[u.category]=[...new Set([...p,C(u.value)])].slice(-50)}let s=[...o?.state.userRequests??[],...e.filter(c=>c.role==="user").map(c=>C(typeof c.content=="string"?c.content:JSON.stringify(c.content??"")))].slice(-50),a={summary:C(t),userRequests:s,anchors:i},l={version:1,sourceMessageCount:(o?.receipt.sourceMessageCount??0)+e.length,sourceItemIds:[...new Set([...o?.receipt.sourceItemIds??[],...r])].slice(-200),firstItemId:o?.receipt.firstItemId??r[0],lastItemId:r.at(-1)??o?.receipt.lastItemId,priorDigest:o?.receipt.digest,tokensBefore:(o?.receipt.tokensBefore??0)+e.reduce((c,u)=>c+n(u),0)};return{receipt:{...l,digest:Qe(JSON.stringify({receipt:l,state:a}))},state:a}}function ue(e){return{role:"system",content:`${E}
2
+ ${JSON.stringify(e)}`}}var ae=4;function le(e){return{role:"system",content:`[${e} earlier messages removed to fit the context budget]`}}var N=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(le(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>=ae)break;if(i-m<0&&l<ae){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(le(c)),u.push(...a),{messages:u,droppedCount:c,strategy:"sliding-window"}}},D=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]
3
+ ${a}`},...s],droppedCount:i.length,strategy:"summarize-old"}}},F=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:et(i.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function et(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
4
  `),n.lastIndexOf(`]
4
5
  `));if(i>t*.5)return n.slice(0,i+1)+`
5
6
  [...truncated: ${e.length-i-1} chars omitted]`}let r=n.lastIndexOf(`
6
7
  `);return r>t*.7?n.slice(0,r)+`
7
8
  [...truncated: ${e.length-r} chars omitted]`:n+`
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]
9
+ [...truncated: ${e.length-t} chars omitted]`}function tt(...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 nt(...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=q(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 H(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","Preserve exact non-secret operational facts: file paths, URLs, port numbers, numeric values, version numbers, proper nouns, identifiers, and user-provided constraints. Never reproduce passwords, API keys, bearer tokens, cookies, or credentials; write [REDACTED] instead.","","### 6. All User Messages",`List ALL ${n.length} user messages chronologically, each as 1-2 sentences capturing the core request. Include exact non-secret values, identifiers, and keywords. Redact every secret even if the user asked to remember it. 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=C(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(`
10
+ `)}var B=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??M,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}=de(t),s=r.findIndex(f=>A(f)!==void 0),a=A(s>=0?r[s]:void 0),l=s>=0?[...r.slice(0,s),...r.slice(s+1)]:r,c=t.reduce((f,L)=>f+this.config.estimateTokens(L),0);if(c<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let u=0,p=0;for(let f=0;f<i.length&&(i[f].role==="user"&&p++,!(p>this.config.protectedHeadExchanges));f++)u=f+1;let d=Math.max(this.config.protectedTailMessages,Math.floor(i.length*.4)),m=Math.max(u,i.length-d);if(m<=u)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let _=i.slice(0,u),b=i.slice(u,m),v=i.slice(m),w=H(b,{taskContext:[this.config.taskContext,a?`Prior verified capsule:
11
+ ${JSON.stringify(a.state)}`:void 0].filter(Boolean).join(`
10
12
 
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
- ${a.content}
13
+ `)||void 0}),S=C(await this.config.summarize(b,w)),O=ue(ce(b,S,this.config.estimateTokens,a)),x=[...l,..._,O,...v],g=Date.now()-o,R=x.reduce((f,L)=>f+this.config.estimateTokens(L),0);return{messages:x,droppedCount:b.length,strategy:"head-tail-protected",metrics:{tokensBefore:c,tokensAfter:R,compressionRatio:c>0?R/c:1,latencyMs:g,usedLlm:!0,cacheInvalidated:!0}}}},U=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??M}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=de(t),s=r.findIndex(g=>A(g)!==void 0),a=s>=0?r[s]:void 0,l=A(a),c=s>=0?[...r.slice(0,s),...r.slice(s+1)]:r,u=Math.max(0,i.length-this.config.preserveRecentCount);if(u<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let p=t.reduce((g,R)=>g+this.config.estimateTokens(R),0);if(p<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=i.slice(0,u),m=i.slice(u),_=l?`Prior verified capsule state:
14
+ ${JSON.stringify(l.state)}
13
15
 
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]
16
+ Integrate only the new messages below:`:void 0,b=H(d,{taskContext:_}),v=C(await this.config.summarize(d,b)),w=ue(ce(d,v,this.config.estimateTokens,l)),S=[...c,w,...m],O=Date.now()-o,x=S.reduce((g,R)=>g+this.config.estimateTokens(R),0);return{messages:S,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:p,tokensAfter:x,compressionRatio:p>0?x/p:1,latencyMs:O,usedLlm:!0,cacheInvalidated:!0}}}},G=class{config;constructor(t){this.config=t}compress(t,n){let o=k(t),r=this.config.inner.compress(t,n),i=k(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=k(t),r=q(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),i=k(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}}}},pe={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function ot(e={}){let t={...pe,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function rt(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var $=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}},j=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 de(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function M(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function k(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 st=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"]),z=class{constructor(t=20,n=M){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||!st.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 it(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 at(e,t,n){let o=n.estimateTokens??(d=>Math.ceil(d.length/4)),r=it(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 _=o(m);_>a||(a-=_,c++,l.push({role:"system",content:`[Post-compact file recovery: ${d}]
15
18
 
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
-
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?`
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 lt(e,t,n=M){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 ct(){return{stages:[]}}function ut(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=me(e,t),s=dt(i,t,o);if(s.length===0)return{messages:i,stagedCount:0};for(let a of s)t.stages.push(a);return i=me(e,t),{messages:i,stagedCount:s.length}}function pt(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:fe(e,t),committed:n}}function me(e,t){return t.stages.filter(o=>o.committed).length===0?e:fe(e,t)}function fe(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 dt(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 mt(e){return[...new Set(e.map(I).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function ge(e){let t=mt(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 ft(e){let t=[...new Set(e.map(I).filter(Boolean))].sort((s,a)=>s.localeCompare(a)),n=new Set(t),o=ge(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 I(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 gt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function yt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Tt(e){if(!e.eligibility?.length)return[...e.tools];let t=yt(e.eligibility);return e.tools.filter(n=>{let o=I(n);if(!o)return!1;let r=t.get(o);return!r||gt(r.status)})}function ht(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 Ct(e){let t=ht({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Tt({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:ge(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:ft(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=>I(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 _t=["stop","aborted","timeout","cancelled","interrupted","error"],bt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function ye(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Rt(e,t){return{...e,content:[...ye(e.content),...ye(t.content)]}}function xt(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 At(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=xt(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 St(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 kt(e){return new Set((e??_t).map(t=>t.trim().toLowerCase()))}function Te(e,t){return e?kt(t).has(e.trim().toLowerCase()):!1}function Et(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 Y(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=>St(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=At(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]=Rt(c,l);continue}a.push(l)}return a}function X(e,t){return Te(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of bt)delete o[r];return o}):[...e]}function W(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 Mt(e,t){let n=Y(e),o=X(n,t);return W(o,t)}function he(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=Te(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=Et(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 It(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 vt(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 wt(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 Ot(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 Ce(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Lt(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 Pt(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 Nt(e){let t=[],n=Y(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=X(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=W(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:Ce({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:It(r),completedToolCallIds:vt(r)}),recoveryActions:t}}function Dt(e){let t=he(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:Ce({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:wt(t),completedToolCallIds:Ot(t)}),recoveryActions:n}}var Ft=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Bt(e){return e?Ft.has(e):!0}function Ut(e){return e===429||e===529}function Gt(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 Mn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function $t(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var K=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var vn=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),wn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var On=720*60*60*1e3,V=4;var Ln=3600*1e3;var Pn=50*1024,Nn=500*1024,Dn=500*1024*1024,Fn=50*1024*1024;var Bn=60*1024;var J="<fork-child-context>",_e="Fork started \u2014 processing in background";function jt(e){return JSON.stringify(e).includes(J)}function zt(e){return e<V}function qt(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
20
20
 
21
21
  Your working directory is: ${e.worktreePath}
22
- All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${q}
22
+ All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${J}
23
23
 
24
24
  You are the "${t.agent.name}" agent.${o}
25
25
 
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","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","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","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","search","task"],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
26
+ ${t.taskPrompt}`}]};return n.push(r),n}function Ht(e){return e.map(t=>({role:"tool",tool_call_id:t,content:_e}))}function Yt(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 Xt(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var Wt={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},Kt={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","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."},Vt={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","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."},Zt={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","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."},Qt={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolCapabilityProfile:"all_tools",allowedTools:["exec","read","search","task"],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."},Z=[Wt,Kt,Vt,Jt,Zt,Qt];function en(){return[...Z]}function tn(e){return Z.find(t=>t.name===e)}function nn(e){return Z.some(t=>t.name===e)}function on(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 rn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function sn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function an(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 ln(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 cn(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 un(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}function pn(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 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};
37
+ `)}`}function dn(){return{attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function mn(e){return!e.attemptedThisTurn}export{E as CONTEXT_CAPSULE_MARKER,G as CacheAwareCompressionStrategy,$ as CompressionMetricsCollector,j as ContextEngineRegistry,pe as DEFAULT_ADAPTIVE_BUDGET_CONFIG,_e as FORK_PLACEHOLDER_RESULT,J as FORK_SENTINEL_TAG,K as FallbackTriggeredError,B as HeadTailProtectedStrategy,U as IncrementalCompactStrategy,V as MAX_FORK_DEPTH,z as MicroCompactStrategy,N as SlidingWindowStrategy,D as SummarizeOldStrategy,F as ToolResultTrimStrategy,Lt as advanceToolLoopState,ut as applyContextCollapsesIfNeeded,Ct as applyToolChoicePolicy,be as buildAssistantToolCallMessage,Ht as buildForkPlaceholderResults,qt as buildForkedMessages,pn as buildPostCompactRestorationMessage,H as buildStructuredSummaryPrompt,Re as buildToolResultMessage,an as calculateTokenWarningState,zt as canForkAtDepth,Ze as classifyError,nt as composeAsyncStrategies,tt as composeStrategies,ot as computeAdaptiveBudget,Gt as computeRetryBackoff,ct as createCollapseStore,dn as createReactiveCompactState,rn as createTaskState,sn as createTurnLoopGuardState,Xt as generateForkChildAgentId,tn as getBuiltInAgent,en as getBuiltInAgents,q as isAsyncCompressionStrategy,nn as isBuiltInAgent,Bt as isForegroundSource,jt as isInForkChild,$t as isPersistentRetryEnabled,ie as isRetryableCategory,Ut as isTransientCapacityError,A as parseContextCapsule,at as postCompactFileRecovery,pt as recoverContextCollapseFromOverflow,Nt as recoverToolLoopStateFromChatConversation,Dt as recoverToolLoopStateFromResponsesItems,C as redactCompressionSecrets,Mt as repairOpenAiChatConversation,on as resolveAgentToolSet,ln as resolveApiErrorRecovery,Yt as resolveForkChildTools,cn as resolveOutputTokenEscalation,rt as selectCompressionTier,Pt as settleToolLoopState,un as shouldAbortTurn,mn as shouldAttemptReactiveCompact,lt as snipCompactIfNeeded};
@@ -1,41 +1,38 @@
1
- import{readFile as T,readdir as ne,unlink as se,stat as ie,mkdir as Oe}from"node:fs/promises";import{existsSync as p,readFileSync as ae,mkdirSync as le,writeFileSync as Te}from"node:fs";import{join as m}from"node:path";import{resolve as ve}from"node:path";import{join as Ie}from"node:path";import{homedir as de}from"node:os";import{join as f}from"node:path";import{existsSync as Ze}from"node:fs";import{createHash as me}from"node:crypto";import{resolve as ge}from"node:path";function N(r){return me("sha256").update(ge(r).toLowerCase()).digest("hex").slice(0,16)}var q=".qlogicagent";function P(){return process.env.QLOGICAGENT_HOME||f(de(),q)}function M(){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 pe(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=M()){return f(P(),"profiles",pe(r))}function X(r=M()){return f(_(r),"memory")}var he="projectData";function H(){return f(P(),he)}function C(r){if(!r)throw new Error("getProjectDataDirById: projectId is required");return f(H(),r)}function W(){return f(P(),"plugins")}function B(){return f(P(),"skills")}function G(){return f(_(),"settings.json")}function z(){return f(P(),"plugin-cache")}function J(){return f(P(),"mcp.json")}function Y(){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,q)}function Q(r){return f(j(r),"plugins")}function K(r){return f(j(r),"settings.json")}function V(r){return f(j(r),"INSTRUCTIONS.md")}function Z(r){return f(j(r),"rules")}import{resolve as nt}from"node:path";var ye=()=>{},A;function ee(){if(we(),!A)throw new Error("host project authority negotiated but snapshot is not hydrated");return{activeProjectId:A.activeProjectId,projects:A.projects.map(r=>({...r}))}}function we(){let r=ye();if(!r)throw new Error("gateway project authority is not available");return r}function Pe(){let r=ee();return{activeProjectId:r.activeProjectId,projects:r.projects.map(e=>({...e}))}}function te(r){return Pe().projects.find(e=>e.id===r)??null}function je(r){return te(r)?r:N(r)}function ke(r){return C(je(r))}function re(r){return Ie(ke(r),"sessions")}var U=class{constructor(e={}){this.options=e}options;lastActiveWorkdir=null;getActiveProjectRoot(){return this.options.getActiveProjectRoot?.()??process.cwd()}setActiveWorkdir(e){let t=ve(e);this.lastActiveWorkdir=t,this.options.setActiveWorkdir?.(t)}getActiveWorkdir(){return this.lastActiveWorkdir??this.getActiveProjectRoot()}resolveProjectDir(e){return this.options.resolveProjectDir?.(e)}resolveActiveOwnerUserId(){return M()}getUserAgentHome(){return P()}getOwnerProfileDir(e){return _(e)}getProfileMemoryDir(e){return X(e)}getUserSettingsPath(){return G()}getUserSkillsDir(){return B()}getUserPluginsDir(){return W()}getUserMcpConfigPath(){return J()}getUserPluginCacheDir(){return z()}getUserMarketplaceConfigPath(){return Y()}getProjectAgentDir(e=this.getActiveProjectRoot()){return j(e)}getProjectSettingsPath(e=this.getActiveProjectRoot()){return K(e)}getProjectInstructionsPath(e=this.getActiveProjectRoot()){return V(e)}getProjectPluginsDir(e=this.getActiveProjectRoot()){return Q(e)}getProjectRulesDir(e=this.getActiveProjectRoot()){return Z(e)}getProjectSessionDataRoot(e=this.getActiveProjectRoot()){return re(e)}},Ee=new U;function oe(){return Ee}import{readFile as ht,writeFile as De,mkdir as Me,rename as _e,unlink as Re}from"node:fs/promises";import{dirname as Se,join as be}from"node:path";import{randomUUID as $e}from"node:crypto";async function v(r,e){let t=Se(r);await Me(t,{recursive:!0});let n=be(t,`.tmp-${$e()}`);try{await De(n,e,"utf-8");let o;for(let s=0;s<3;s++)try{await _e(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 Re(n).catch(()=>{}),o}}var Ne=/[一-鿿]/;function R(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 d=Ne.test(a);o&&d!==s&&i(),s=d,o+=a}i()}return e}var O=["fact","preference","insight","lesson","decision","plan","event","pattern","context","procedure","general"],It=new Set(O),Ce=["equals","includes","excludes"],jt=new Set(Ce);var Ae=["add","replace","remove","create_file","write_file","read_file","delete_file","list_files","search","remember","temporal","feedback"],Dt={type:"object",properties:{action:{type:"string",enum:Ae,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
- `)},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:O,description:"For 'remember': categorize the memory (helps with future recall precision)."}},required:["action"]},Mt=["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,L=200,S=8192,Le="memory",x="INDEX.md";function Fe(r){return m(oe().getProjectAgentDir(r),Le)}var qe=/^[a-z0-9][a-z0-9\-_.]*\.md$/i;function b(r){return!(!qe.test(r)||r===x||r.includes("..")||r.includes("/")||r.includes("\\"))}function Xe(r){return r.trim().match(/^([A-Za-z][A-Za-z0-9_-]{2,})\s*:/)?.[1]??null}function He(r,e){let t=r.split(`
5
- `),n=[],o=!1;for(let s=0;s<t.length;s++){let i=t[s];if(We(i)&&i.includes(e)){for(o=!0;s+1<t.length&&ue(t[s+1]);)s++;continue}n.push(i)}return o?n.join(`
6
- `):null}function We(r){return r.trim()!==""&&!r.startsWith("#")&&!r.startsWith("<!--")&&!ue(r)}function ue(r){return r.startsWith(" ")||r.startsWith(" ")}var $=new Map;async function I(r,e){let t=$.get(r)??Promise.resolve(),n,o=new Promise(i=>{n=i}),s=t.catch(()=>{}).then(()=>o);$.set(r,s),await t.catch(()=>{});try{return await e()}finally{n(),$.get(r)===s&&$.delete(r)}}function Be(r){return r.split(`
7
- `).every(e=>{let t=e.trim();return t===""||t.startsWith("#")||t.startsWith("<!--")&&t.endsWith(">")})}var F=class{root;constructor(e){this.root=Fe(e)}getRootPath(){return this.root}ensureInitialized(){p(this.root)||le(this.root,{recursive:!0});let e=m(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
- `);Ge(e,t)}}getIndexForPrompt(){let e=m(this.root,x);if(!p(e))return"";let t;try{t=ae(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(Be(t))return"";let n=t.split(`
9
- `);return n.length>L&&(t=n.slice(0,L).join(`
1
+ import{readFile as _,readdir as et,unlink as rt,stat as nt,mkdir as Ut}from"node:fs/promises";import{existsSync as p,readFileSync as it,mkdirSync as st,writeFileSync as At}from"node:fs";import{join as f}from"node:path";import{resolve as xt}from"node:path";import{join as wt}from"node:path";import{homedir as gt}from"node:os";import{join as g}from"node:path";import{existsSync as zt}from"node:fs";import{createHash as ut}from"node:crypto";import{resolve as lt}from"node:path";function A(r){return ut("sha256").update(lt(r).toLowerCase()).digest("hex").slice(0,16)}var O=".qlogicagent";function j(){return process.env.QLOGICAGENT_HOME||g(gt(),O)}function S(){let r=process.env.QLOGIC_LLMROUTER_USER_ID?.trim();if(r)return r;let t=process.env.QLOGIC_IMPLICIT_OWNER_ID?.trim();if(t)return t;let e=process.env.QLOGIC_DEVICE_ID?.trim();return e?`oc_${e}`:"oc_local"}function ft(r){let t=r.trim();if(!t)throw new Error("ownerUserId is required for profile-scoped storage");return encodeURIComponent(t).replace(/\./g,"%2E")}function $(r=S()){return g(j(),"profiles",ft(r))}function W(r=S()){return g($(r),"memory")}var dt="projectData";function X(){return g(j(),dt)}function b(r){if(!r)throw new Error("getProjectDataDirById: projectId is required");return g(X(),r)}function T(){return g(j(),"plugins")}function B(){return g($(),"settings.json")}function G(){return g(j(),"plugin-cache")}function J(){return g(j(),"marketplace.json")}function v(r){if(!r)throw new Error("getProjectAgentDir: cwd is required (must not fall back to process.cwd())");return g(r,O)}function q(r){return g(v(r),"plugins")}function z(r){return g(v(r),"settings.json")}function Q(r){return g(v(r),"INSTRUCTIONS.md")}function V(r){return g(v(r),"rules")}import{resolve as Yt}from"node:path";var mt=()=>{},M;function K(){if(pt(),!M)throw new Error("host project authority negotiated but snapshot is not hydrated");return{activeProjectId:M.activeProjectId,projects:M.projects.map(r=>({...r}))}}function pt(){let r=mt();if(!r)throw new Error("gateway project authority is not available");return r}function ht(){let r=K();return{activeProjectId:r.activeProjectId,projects:r.projects.map(t=>({...t}))}}function Z(r){return ht().projects.find(t=>t.id===r)??null}function It(r){return Z(r)?r:A(r)}function jt(r){return b(It(r))}function Y(r){return wt(jt(r),"sessions")}var F=class{constructor(t={}){this.options=t}options;lastActiveWorkdir=null;getActiveProjectRoot(){return this.options.getActiveProjectRoot?.()??process.cwd()}setActiveWorkdir(t){let e=xt(t);this.lastActiveWorkdir=e,this.options.setActiveWorkdir?.(e)}getActiveWorkdir(){return this.lastActiveWorkdir??this.getActiveProjectRoot()}resolveProjectDir(t){return this.options.resolveProjectDir?.(t)}resolveActiveOwnerUserId(){return S()}getUserAgentHome(){return j()}getOwnerProfileDir(t){return $(t)}getProfileMemoryDir(t){return W(t)}getUserSettingsPath(){return B()}getUserPluginsDir(){return T()}getUserPluginCacheDir(){return G()}getUserMarketplaceConfigPath(){return J()}getProjectAgentDir(t=this.getActiveProjectRoot()){return v(t)}getProjectSettingsPath(t=this.getActiveProjectRoot()){return z(t)}getProjectInstructionsPath(t=this.getActiveProjectRoot()){return Q(t)}getProjectPluginsDir(t=this.getActiveProjectRoot()){return q(t)}getProjectRulesDir(t=this.getActiveProjectRoot()){return V(t)}getProjectSessionDataRoot(t=this.getActiveProjectRoot()){return Y(t)}},yt=new F;function tt(){return yt}import{readFile as ge,writeFile as vt,mkdir as Dt,rename as Et,unlink as kt}from"node:fs/promises";import{dirname as St,join as $t}from"node:path";import{randomUUID as Rt}from"node:crypto";async function D(r,t){let e=St(r);await Dt(e,{recursive:!0});let i=$t(e,`.tmp-${Rt()}`);try{await vt(i,t,"utf-8");let n;for(let o=0;o<3;o++)try{await Et(i,r);return}catch(s){if(n=s,s.code!=="EPERM")throw s;await new Promise(a=>setTimeout(a,50*(o+1)))}throw n}catch(n){throw await kt(i).catch(()=>{}),n}}var Nt=/[一-鿿]/;function R(r){let t=[],e=r.toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[];for(let i of e){let n="",o=!1,s=()=>{if(n){if(o){n.length===1&&t.push(n);for(let a=0;a+1<n.length;a++)t.push(n.slice(a,a+2))}else t.push(n);n=""}};for(let a of i){let m=Nt.test(a);n&&m!==o&&s(),o=m,n+=a}s()}return t}var Ct=[/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 x(r){return!Ct.some(t=>t.test(r))}var u=12288,L=200,N=8192,bt="memory",I="INDEX.md";function Mt(r){return f(tt().getProjectAgentDir(r),bt)}var Ft=/^[a-z0-9][a-z0-9\-_.]*\.md$/i;function C(r){return!(!Ft.test(r)||r===I||r.includes("..")||r.includes("/")||r.includes("\\"))}function _t(r){return r.trim().match(/^([A-Za-z][A-Za-z0-9_-]{2,})\s*:/)?.[1]??null}function Lt(r,t){let e=r.split(`
2
+ `),i=[],n=!1;for(let o=0;o<e.length;o++){let s=e[o];if(Ht(s)&&s.includes(t)){for(n=!0;o+1<e.length&&at(e[o+1]);)o++;continue}i.push(s)}return n?i.join(`
3
+ `):null}function Ht(r){return r.trim()!==""&&!r.startsWith("#")&&!r.startsWith("<!--")&&!at(r)}function at(r){return r.startsWith(" ")||r.startsWith(" ")}var U=new Map;async function y(r,t){let e=U.get(r)??Promise.resolve(),i,n=new Promise(s=>{i=s}),o=e.catch(()=>{}).then(()=>n);U.set(r,o),await e.catch(()=>{});try{return await t()}finally{i(),U.get(r)===o&&U.delete(r)}}function Ot(r){return r.split(`
4
+ `).every(t=>{let e=t.trim();return e===""||e.startsWith("#")||e.startsWith("<!--")&&e.endsWith(">")})}var H=class{root;constructor(t){this.root=Mt(t)}getRootPath(){return this.root}ensureInitialized(){p(this.root)||st(this.root,{recursive:!0});let t=f(this.root,I);if(!p(t)){let e=["# Memory Index","","<!-- Host-managed project memory. Lines here are visible in the agent context.>","<!-- Use the Host project-memory capability to add notes or manage topic files.>","","## User Profile","","## Notes",""].join(`
5
+ `);Wt(t,e)}}getIndexForPrompt(){let t=f(this.root,I);if(!p(t))return"";let e;try{e=it(t,"utf-8")}catch(n){return n?.code!=="ENOENT"&&console.error(`[memdir] INDEX.md read failed \u2014 injected as empty this turn: ${n instanceof Error?n.message:String(n)}`),""}if(Ot(e))return"";let i=e.split(`
6
+ `);return i.length>L&&(e=i.slice(0,L).join(`
10
7
  `)+`
11
8
 
12
- <!-- INDEX.md truncated: ${n.length} lines total, showing first ${L}>`),Buffer.byteLength(t,"utf-8")>l&&(t=Buffer.from(t,"utf-8").subarray(0,l).toString("utf-8")+`
9
+ <!-- INDEX.md truncated: ${i.length} lines total, showing first ${L}>`),Buffer.byteLength(e,"utf-8")>u&&(e=Buffer.from(e,"utf-8").subarray(0,u).toString("utf-8")+`
13
10
 
14
- <!-- INDEX.md truncated at ${l} bytes>`),t}getIndexRaw(){let e=m(this.root,x);if(!p(e))return"";try{return ae(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(`
16
- `)?t+e.trim()+`
17
- `:t+`
18
- `+e.trim()+`
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(`
20
- `),o=Buffer.byteLength(t+`
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(" "),d=4,h=[...n],y=0;for(;Buffer.byteLength(h.join(`
22
- `),"utf-8")>s&&y<n.length;){let u=h.findIndex((E,D)=>D>=d&&!i(E)&&!a(E));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(`
23
- `),g=c.endsWith(`
24
- `)?c+t+`
11
+ <!-- INDEX.md truncated at ${u} bytes>`),e}getIndexRaw(){let t=f(this.root,I);if(!p(t))return"";try{return it(t,"utf-8")}catch(e){return e?.code!=="ENOENT"&&console.error(`[memdir] INDEX.md read failed \u2014 treated as empty: ${e instanceof Error?e.message:String(e)}`),""}}getIndexUsage(){let t=this.getIndexRaw(),e=Buffer.byteLength(t,"utf-8"),i=t.split(`
12
+ `).length;return{chars:e,lines:i,percent:Math.round(e/u*100)}}async addToIndex(t){return t.trim()?x(t)?y(this.root,async()=>{let e=this.getIndexRaw(),i=e.endsWith(`
13
+ `)?e+t.trim()+`
14
+ `:e+`
15
+ `+t.trim()+`
16
+ `;if(Buffer.byteLength(i,"utf-8")>u){let o=this.autoCompactIndex(e,t.trim());if(o){await this.writeIndexUnlocked(o);let a=this.getIndexUsage();return{ok:!0,message:`Added to INDEX.md (auto-compacted old entries). [${a.chars}/${u} chars, ${a.percent}%]`,indexUsage:`${a.chars}/${u}`}}return{ok:!1,message:`INDEX.md would exceed limit (${this.getIndexUsage().chars}/${u} bytes) even after compaction. Create a topic file instead.`}}await this.writeIndexUnlocked(i);let n=this.getIndexUsage();return{ok:!0,message:`Added to INDEX.md. [${n.chars}/${u} chars, ${n.percent}%]`,indexUsage:`${n.chars}/${u}`}}):{ok:!1,message:"Content rejected: potential injection detected."}:{ok:!1,message:"Content cannot be empty."}}autoCompactIndex(t,e){let i=t.split(`
17
+ `),n=Buffer.byteLength(e+`
18
+ `,"utf-8"),o=u-n-64;if(o<256)return null;let s=l=>l.startsWith("#")||l.startsWith("<!--")||l.trim()==="",a=l=>l.startsWith(" ")||l.startsWith(" "),m=4,h=[...i],P=0;for(;Buffer.byteLength(h.join(`
19
+ `),"utf-8")>o&&P<i.length;){let l=h.findIndex((E,k)=>k>=m&&!s(E)&&!a(E));if(l===-1)break;let w=1;for(;l+w<h.length&&a(h[l+w]);)w++;h.splice(l,w),P++}let c=h.join(`
20
+ `),d=c.endsWith(`
21
+ `)?c+e+`
25
22
  `:c+`
26
- `+t+`
27
- `;return Buffer.byteLength(g,"utf-8")<=l?g: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=Xe(e),o=n?He(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,`
23
+ `+e+`
24
+ `;return Buffer.byteLength(d,"utf-8")<=u?d:null}async replaceInIndex(t,e){return t.trim()?e.trim()?x(e)?y(this.root,async()=>{let i=this.getIndexRaw(),n=i.split(t).length-1;if(n===0)return{ok:!1,message:`No match found for: "${t.slice(0,80)}"`};if(n>1)return{ok:!1,message:`Multiple matches (${n}) for: "${t.slice(0,80)}". Be more specific.`};let o=i.replace(t,e);if(Buffer.byteLength(o,"utf-8")>u)return{ok:!1,message:`Replacement would exceed INDEX.md limit (${Buffer.byteLength(o,"utf-8")}/${u} bytes).`};await this.writeIndexUnlocked(o);let s=this.getIndexUsage();return{ok:!0,message:`Replaced in INDEX.md. [${s.chars}/${u} chars]`,indexUsage:`${s.chars}/${u}`}}):{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(t){return t.trim()?y(this.root,async()=>{let e=this.getIndexRaw(),i=_t(t),n=i?Lt(e,i):null;if(n===null){if(!e.includes(t))return{ok:!1,message:`No match found for: "${t.slice(0,80)}"`};n=e.replace(t,"")}n=n.replace(/\n{3,}/g,`
28
25
 
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 ne(this.root),t=[];for(let n of e){if(n===x||!n.endsWith(".md"))continue;let o=m(this.root,n);try{let s=await ie(o);if(!s.isFile())continue;let a=(await T(o,"utf-8")).split(`
30
- `).find(d=>d.trim()&&!d.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(!b(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>S)return{ok:!1,message:`Content too long (${t.length} chars, max ${S}).`};let n=m(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(!b(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>S)return this.writeFileSplit(e,t);let n=m(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>S*.9&&i.length>0?(s.push(i),i=c):i=i?i+`
26
+ `),await this.writeIndexUnlocked(n);let o=this.getIndexUsage();return{ok:!0,message:`Removed from INDEX.md. [${o.chars}/${u} chars]`,indexUsage:`${o.chars}/${u}`}}):{ok:!1,message:"old_text cannot be empty."}}async listFiles(){if(!p(this.root))return[];let t=await et(this.root),e=[];for(let i of t){if(i===I||!i.endsWith(".md"))continue;let n=f(this.root,i);try{let o=await nt(n);if(!o.isFile())continue;let a=(await _(n,"utf-8")).split(`
27
+ `).find(m=>m.trim()&&!m.startsWith("#"))?.trim();e.push({name:i,size:o.size,modifiedAt:o.mtime.toISOString(),preview:a?.slice(0,100)})}catch{}}return e.sort((i,n)=>n.modifiedAt.localeCompare(i.modifiedAt))}async createFile(t,e){if(!C(t))return{ok:!1,message:`Invalid filename: "${t}". Use kebab-case .md files (e.g. "project-notes.md").`};if(!x(e))return{ok:!1,message:"Content rejected: potential injection detected."};if(e.length>N)return{ok:!1,message:`Content too long (${e.length} chars, max ${N}).`};let i=f(this.root,t);if(p(i))return{ok:!1,message:`File already exists: "${t}". Use write_file to update.`};await this.ensureDir(),await D(i,e);let n=`- [${t}] \u2014 created ${new Date().toISOString().slice(0,10)}`;return{ok:!0,message:await this.appendIndexEntry(n)?`Created "${t}" (${e.length} chars). Entry added to INDEX.md.`:`Created "${t}" (${e.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 [${t}].`,file:t}}async writeFile(t,e){if(!C(t))return{ok:!1,message:`Invalid filename: "${t}". Use kebab-case .md files.`};if(!x(e))return{ok:!1,message:"Content rejected: potential injection detected."};if(e.length>N)return this.writeFileSplit(t,e);let i=f(this.root,t),n=!p(i);await this.ensureDir(),await D(i,e);let o=!0;if(n){let s=`- [${t}] \u2014 created ${new Date().toISOString().slice(0,10)}`;o=await this.appendIndexEntry(s)}return{ok:!0,message:`${n?"Created":"Updated"} "${t}" (${e.length} chars).`+(o?"":" WARNING: INDEX.md is full \u2014 no index entry was added, so this file will not surface automatically."),file:t}}async writeFileSplit(t,e){let i=t.replace(/\.md$/,""),n=e.split(/\n{2,}/),o=[],s="";for(let c of n)s.length+c.length+2>N*.9&&s.length>0?(o.push(s),s=c):s=s?s+`
31
28
 
32
- `+c:c;i&&s.push(i);let a=[];for(let c=0;c<s.length;c++){let g=`${n}-${c+1}.md`,u=m(this.root,g);await this.ensureDir(),await v(u,s[c]),a.push(g)}let d=m(this.root,e);p(d)&&(await se(d),await I(this.root,async()=>{let c=this.getIndexRaw(),g=new RegExp(`^.*\\[${ce(e)}\\].*$\\n?`,"m");g.test(c)&&await this.writeIndexUnlocked(c.replace(g,"").replace(/\n{3,}/g,`
29
+ `+c:c;s&&o.push(s);let a=[];for(let c=0;c<o.length;c++){let d=`${i}-${c+1}.md`,l=f(this.root,d);await this.ensureDir(),await D(l,o[c]),a.push(d)}let m=f(this.root,t);p(m)&&(await rt(m),await y(this.root,async()=>{let c=this.getIndexRaw(),d=new RegExp(`^.*\\[${ot(t)}\\].*$\\n?`,"m");d.test(c)&&await this.writeIndexUnlocked(c.replace(d,"").replace(/\n{3,}/g,`
33
30
 
34
- `))}));let h=this.getIndexRaw(),y=0;for(let c of a)if(!h.includes(`[${c}]`)){let g=`- [${c}] \u2014 auto-split ${new Date().toISOString().slice(0,10)}`;await this.appendIndexEntry(g)||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(!b(e)&&e!==x)return{ok:!1,message:`Invalid filename: "${e}".`};let t=m(this.root,e);try{let n=await T(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(!b(e))return{ok:!1,message:`Invalid filename: "${e}".`};let t=m(this.root,e);return p(t)?(await se(t),await I(this.root,async()=>{let n=this.getIndexRaw(),o=new RegExp(`^.*\\[${ce(e)}\\].*$\\n?`,"m");if(o.test(n)){let s=n.replace(o,"").replace(/\n{3,}/g,`
31
+ `))}));let h=this.getIndexRaw(),P=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)||P++}return{ok:!0,message:`Auto-split "${t}" into ${o.length} parts (${e.length} chars total): ${a.join(", ")}`+(P>0?` WARNING: INDEX.md is full \u2014 ${P} part(s) got no index entry and will not surface automatically.`:""),file:a[0]}}async readFile(t){if(!C(t)&&t!==I)return{ok:!1,message:`Invalid filename: "${t}".`};let e=f(this.root,t);try{let i=await _(e,"utf-8");return{ok:!0,content:i,message:`Read "${t}" (${i.length} chars).`}}catch(i){return i.code==="ENOENT"?{ok:!1,message:`File not found: "${t}".`}:{ok:!1,message:`Error reading "${t}": ${i.message}`}}}async deleteFile(t){if(t===I)return{ok:!1,message:"Cannot delete INDEX.md. Use 'remove' to clear entries."};if(!C(t))return{ok:!1,message:`Invalid filename: "${t}".`};let e=f(this.root,t);return p(e)?(await rt(e),await y(this.root,async()=>{let i=this.getIndexRaw(),n=new RegExp(`^.*\\[${ot(t)}\\].*$\\n?`,"m");if(n.test(i)){let o=i.replace(n,"").replace(/\n{3,}/g,`
35
32
 
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(R(e)));if(t.length===0)return[];let n=await ne(this.root),o=[];for(let s of n){if(!s.endsWith(".md")||s===x)continue;let i=m(this.root,s);try{let[a,d]=await Promise.all([T(i,"utf-8"),ie(i)]),h=new Set(R(a)),y=t.filter(w=>h.has(w)).length;if(y===0)continue;let c=a.split(`
37
- `),g="",u=0;for(let w of c){let E=new Set(R(w)),D=t.filter(fe=>E.has(fe)).length;D>u&&(u=D,g=w.trim())}o.push({file:s,snippet:g.slice(0,200),score:y/t.length,mtimeMs:d.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(m(this.root,x),e)}async ensureDir(){p(this.root)||await Oe(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(`
38
- `)?t+e+`
39
- `:t+`
40
- `+e+`
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 Ge(r,e){let t=m(r,"..");p(t)||le(t,{recursive:!0}),Te(r,e,"utf-8")}function ce(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}export{F as Memdir};
33
+ `);await this.writeIndexUnlocked(o)}}),{ok:!0,message:`Deleted "${t}" and removed INDEX.md entry.`,file:t}):{ok:!1,message:`File not found: "${t}".`}}async searchLocal(t){if(!p(this.root))return[];let e=Array.from(new Set(R(t)));if(e.length===0)return[];let i=await et(this.root),n=[];for(let o of i){if(!o.endsWith(".md")||o===I)continue;let s=f(this.root,o);try{let[a,m]=await Promise.all([_(s,"utf-8"),nt(s)]),h=new Set(R(a)),P=e.filter(w=>h.has(w)).length;if(P===0)continue;let c=a.split(`
34
+ `),d="",l=0;for(let w of c){let E=new Set(R(w)),k=e.filter(ct=>E.has(ct)).length;k>l&&(l=k,d=w.trim())}n.push({file:o,snippet:d.slice(0,200),score:P/e.length,mtimeMs:m.mtimeMs})}catch{}}return n.sort((o,s)=>s.score-o.score).slice(0,10)}async writeIndex(t){await y(this.root,()=>this.writeIndexUnlocked(t))}async writeIndexUnlocked(t){await this.ensureDir(),await D(f(this.root,I),t)}async ensureDir(){p(this.root)||await Ut(this.root,{recursive:!0})}async appendIndexEntry(t){return y(this.root,async()=>{let e=this.getIndexRaw();if(e.includes(t))return!0;let i=e.endsWith(`
35
+ `)?e+t+`
36
+ `:e+`
37
+ `+t+`
38
+ `;if(Buffer.byteLength(i,"utf-8")<=u)return await this.writeIndexUnlocked(i),!0;let n=this.autoCompactIndex(e,t);return n?(await this.writeIndexUnlocked(n),!0):(console.error(`[memdir] INDEX.md full \u2014 entry not added (file stays invisible to recall): ${t.slice(0,80)}`),!1)})}};function Wt(r,t){let e=f(r,"..");p(e)||st(e,{recursive:!0}),At(r,t,"utf-8")}function ot(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}export{H as Memdir,x as isMemoryContentSafe};