qlogicagent 2.7.0 → 2.10.0
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.
- package/dist/agent.js +18 -18
- package/dist/cli.js +445 -433
- package/dist/index.js +444 -432
- package/dist/orchestration.js +6 -6
- package/dist/protocol.js +1 -1
- package/dist/types/agent/agent.d.ts +1 -1
- package/dist/types/agent/tool-loop.d.ts +1 -1
- package/dist/types/agent/tunable-defaults.d.ts +4 -0
- package/dist/types/agent/types.d.ts +7 -18
- package/dist/types/cli/handlers/agents-handler.d.ts +19 -0
- package/dist/types/cli/handlers/config-handler.d.ts +17 -0
- package/dist/types/cli/handlers/dream-handler.d.ts +5 -0
- package/dist/types/cli/handlers/files-handler.d.ts +15 -0
- package/dist/types/cli/handlers/media-handler.d.ts +13 -0
- package/dist/types/cli/handlers/memory-handler.d.ts +21 -0
- package/dist/types/cli/handlers/pet-handler.d.ts +28 -0
- package/dist/types/cli/handlers/product-handler.d.ts +32 -0
- package/dist/types/cli/handlers/project-handler.d.ts +19 -0
- package/dist/types/cli/handlers/session-handler.d.ts +38 -0
- package/dist/types/cli/handlers/settings-handler.d.ts +24 -0
- package/dist/types/cli/handlers/skills-handler.d.ts +20 -0
- package/dist/types/cli/handlers/solo-handler.d.ts +15 -0
- package/dist/types/cli/handlers/turn-handler.d.ts +17 -0
- package/dist/types/cli/main.d.ts +2 -2
- package/dist/types/cli/stdio-server.d.ts +90 -106
- package/dist/types/cli/tool-bootstrap.d.ts +4 -3
- package/dist/types/config/config.d.ts +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/llm/index.d.ts +1 -31
- package/dist/types/orchestration/tool-cascade.d.ts +2 -2
- package/dist/types/protocol/methods.d.ts +153 -5
- package/dist/types/protocol/wire/agent-events.d.ts +2 -2
- package/dist/types/protocol/wire/agent-methods.d.ts +5 -3
- package/dist/types/protocol/wire/gateway-rpc.d.ts +125 -4
- package/dist/types/protocol/wire/index.d.ts +1 -1
- package/dist/types/protocol/wire/notification-payloads.d.ts +79 -1
- package/dist/types/runtime/execution/dream-agent.d.ts +1 -1
- package/dist/types/runtime/execution/forked-agent.d.ts +1 -1
- package/dist/types/runtime/hooks/context-compression.d.ts +1 -1
- package/dist/types/runtime/hooks/memory-hooks.d.ts +1 -1
- package/dist/types/runtime/infra/acp-types.d.ts +4 -0
- package/dist/types/runtime/infra/agent-paths.d.ts +22 -25
- package/dist/types/runtime/infra/agent-process.d.ts +1 -1
- package/dist/types/runtime/infra/builtin-providers.d.ts +36 -0
- package/dist/types/runtime/infra/checkpoint-backend.d.ts +1 -1
- package/dist/types/runtime/infra/index.d.ts +1 -2
- package/dist/types/runtime/infra/key-pool.d.ts +120 -0
- package/dist/types/runtime/infra/media-persistence.d.ts +26 -15
- package/dist/types/runtime/infra/model-registry.d.ts +187 -0
- package/dist/types/runtime/infra/project-instructions-store.d.ts +3 -3
- package/dist/types/runtime/infra/project-store.d.ts +3 -0
- package/dist/types/runtime/infra/token-budget.d.ts +2 -2
- package/dist/types/runtime/infra/worktree-backend.d.ts +1 -1
- package/dist/types/runtime/pet/index.d.ts +10 -0
- package/dist/types/runtime/pet/pet-consistency.d.ts +79 -0
- package/dist/types/runtime/pet/pet-context-injection.d.ts +8 -0
- package/dist/types/runtime/pet/pet-file-loader.d.ts +62 -0
- package/dist/types/runtime/pet/pet-growth-engine.d.ts +60 -0
- package/dist/types/runtime/pet/pet-reaction-service.d.ts +33 -0
- package/dist/types/runtime/pet/pet-skeleton.d.ts +70 -0
- package/dist/types/runtime/pet/pet-soul-service.d.ts +71 -0
- package/dist/types/runtime/session/group-session-split.d.ts +38 -0
- package/dist/types/runtime/session/index.d.ts +4 -2
- package/dist/types/runtime/session/session-locator.d.ts +24 -0
- package/dist/types/runtime/session/session-memory.d.ts +4 -4
- package/dist/types/runtime/session/session-persistence.d.ts +47 -46
- package/dist/types/runtime/session/session-state.d.ts +3 -5
- package/dist/types/skills/memory/local-memory-provider.d.ts +11 -1
- package/dist/types/skills/memory/local-store.d.ts +3 -2
- package/dist/types/skills/memory/memdir.d.ts +7 -4
- package/dist/types/skills/memory/memory-provider-factory.d.ts +2 -8
- package/dist/types/skills/permissions/denial-audit-log.d.ts +1 -1
- package/dist/types/skills/permissions/permission-classifier.d.ts +1 -1
- package/dist/types/skills/tools/search-tool.d.ts +1 -1
- package/dist/types/skills/tools.d.ts +3 -3
- package/dist/types/transport/acp-event-emitter.d.ts +1 -1
- package/dist/types/transport/acp-server.d.ts +2 -2
- package/package.json +2 -1
- package/dist/types/llm/adapters/aliyun-oss-file-upload-adapter.d.ts +0 -44
- package/dist/types/llm/adapters/gemini-file-upload-adapter.d.ts +0 -26
- package/dist/types/llm/adapters/hub-oss-file-upload-adapter.d.ts +0 -29
- package/dist/types/llm/adapters/index.d.ts +0 -10
- package/dist/types/llm/adapters/openai-file-upload-adapter.d.ts +0 -38
- package/dist/types/llm/adapters/volcengine-file-upload-adapter.d.ts +0 -24
- package/dist/types/llm/builtin-providers.d.ts +0 -10
- package/dist/types/llm/debug-transport.d.ts +0 -12
- package/dist/types/llm/file-upload-service.d.ts +0 -68
- package/dist/types/llm/gemini-schema-utils.d.ts +0 -17
- package/dist/types/llm/llm-client.d.ts +0 -43
- package/dist/types/llm/media-client.d.ts +0 -42
- package/dist/types/llm/media-transport.d.ts +0 -176
- package/dist/types/llm/model-catalog.d.ts +0 -82
- package/dist/types/llm/model-detection.d.ts +0 -22
- package/dist/types/llm/provider-def.d.ts +0 -203
- package/dist/types/llm/provider-registry.d.ts +0 -59
- package/dist/types/llm/provider-tool-api.d.ts +0 -44
- package/dist/types/llm/retry.d.ts +0 -37
- package/dist/types/llm/transport.d.ts +0 -281
- package/dist/types/llm/transports/anthropic-messages.d.ts +0 -65
- package/dist/types/llm/transports/gemini-cache-api.d.ts +0 -86
- package/dist/types/llm/transports/gemini-file-api.d.ts +0 -90
- package/dist/types/llm/transports/gemini-generatecontent.d.ts +0 -56
- package/dist/types/llm/transports/gemini-lyria-realtime.d.ts +0 -117
- package/dist/types/llm/transports/gemini-media.d.ts +0 -53
- package/dist/types/llm/transports/media-resolve.d.ts +0 -50
- package/dist/types/llm/transports/minimax-media.d.ts +0 -55
- package/dist/types/llm/transports/openai-chat.d.ts +0 -81
- package/dist/types/llm/transports/openai-media.d.ts +0 -24
- package/dist/types/llm/transports/openai-responses.d.ts +0 -63
- package/dist/types/llm/transports/qwen-media.d.ts +0 -50
- package/dist/types/llm/transports/realtime-transport.d.ts +0 -183
- package/dist/types/llm/transports/volcengine-grounding.d.ts +0 -58
- package/dist/types/llm/transports/volcengine-media.d.ts +0 -93
- package/dist/types/llm/transports/volcengine-responses.d.ts +0 -64
- package/dist/types/llm/transports/zhipu-media.d.ts +0 -82
- package/dist/types/llm/transports/zhipu-tool-api.d.ts +0 -35
- package/dist/types/runtime/infra/project-plan-store.d.ts +0 -27
package/dist/orchestration.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function Ae(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Me(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var Ee=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,y={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Ie=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,ve=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Le=512,
|
|
1
|
+
function Ae(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Me(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var Ee=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,y={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Ie=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,ve=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Le=512,Oe=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var we=new Set([500,502,503,504,521,522,523,524,529]),Pe=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ne=["upgrade your plan","upgrade plan","current plan","subscription"],Fe=["daily","weekly","monthly"],De=["try again","retry","temporary","cooldown"],Be=["usage limit","rate limit","organization usage"],Ue=["organization","workspace"],je=["billing period","exceeded","reached","exhausted"],Ge=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,$e=/^(?: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 He(e){return h(e,y.format)}function W(e){return h(e,y.rateLimit)}function ze(e){return h(e,y.timeout)}function qe(e){return Ee.test(e)}function E(e){let t=e.toLowerCase();return t?e.length>Le?ve.test(t):h(t,y.billing)?!0:Ie.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function V(e){return h(e,y.authPermanent)}function Xe(e){return h(e,y.auth)}function J(e){return h(e,y.overloaded)}function T(e,t){return t.some(n=>e.includes(n))}function Ke(e){return T(e,Pe)||T(e,Ne)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ye(e){let t=T(e,Fe),n=e.includes("spend limit")||e.includes("spending limit"),o=T(e,Ue);return T(e,De)&&T(e,Be)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||T(e,je))}function We(e){return e.trim().toLowerCase().replace($e,"").trim()}function Z(e){let t=We(e);return!t||Ke(t)?"billing":W(t)||Ye(t)?"rate_limit":"billing"}function Ve(e){return Ge.test(e)?Z(e):null}function Q(e){let t=e.match(Oe);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Je(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Ze(e){let t=e.trim();if(!t)return!1;let n=Q(t);return n?we.has(n.code):!1}function ee(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?Z(t):"billing":e===429?"rate_limit":e===401||e===403?t&&V(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&J(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&E(t)?"billing":"format":null}function Qe(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function et(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function te(e){if(et(e))return"session_expired";if(Qe(e))return"model_not_found";let t=Ve(e);return t||(qe(e)?E(e)?"billing":"rate_limit":W(e)?"rate_limit":J(e)?"overloaded":Ze(e)?Q(e.trim())?.code===529?"overloaded":"timeout":Je(e)?"timeout":He(e)?"format":E(e)?"billing":ze(e)?"timeout":V(e)?"auth_permanent":Xe(e)?"auth":null)}var tt={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"},nt=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ot(e,t){let n=ee(e,t)??(t?te(t):null);return n?tt[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function rt(e){return nt.has(e)}function B(e){return typeof e.compressAsync=="function"}var ne=4,I=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let c of t)c.role==="system"?o.push(c):r.push(c);let i=n;for(let c of o)i-=this.estimateTokens(c);let a;for(let c of r)if(c.role==="user"){a=c;break}if(a&&(i-=this.estimateTokens(a)),i<=0)return{messages:a?[...o,a]:o,droppedCount:r.length-(a?1:0),strategy:"sliding-window"};let s=[],l=0;for(let c=r.length-1;c>=0;c--){let d=r[c];if(d===a)continue;let p=this.estimateTokens(d);if(i-p<0&&l>=ne)break;if(i-p<0&&l<ne){s.unshift(d),l++;continue}i-=p,s.unshift(d),l++}let u=[...o];return a&&!s.includes(a)&&u.push(a),u.push(...s),{messages:u,droppedCount:r.length-(s.length+(a&&!s.includes(a)?1:0)),strategy:"sliding-window"}}},v=class{constructor(t,n){this.recentCount=t;this.summarize=n}recentCount;summarize;compress(t,n){let o=t.filter(l=>l.role==="system"),r=t.filter(l=>l.role!=="system");if(r.length<=this.recentCount)return{messages:t,droppedCount:0,strategy:"summarize-old"};let i=r.slice(0,r.length-this.recentCount),a=r.slice(r.length-this.recentCount),s=this.summarize(i);return{messages:[...o,{role:"system",content:`[Conversation summary]
|
|
2
2
|
${s}`},...a],droppedCount:i.length,strategy:"summarize-old"}}},L=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(i=>i.role!=="tool"||typeof i.content!="string"||i.content.length<=this.maxToolResultChars?i:(o++,{...i,content:st(i.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function st(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let i=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
|
|
3
3
|
`),n.lastIndexOf(`]
|
|
4
4
|
`));if(i>t*.5)return n.slice(0,i+1)+`
|
|
@@ -6,9 +6,9 @@ ${s}`},...a],droppedCount:i.length,strategy:"summarize-old"}}},L=class{construct
|
|
|
6
6
|
`);return r>t*.7?n.slice(0,r)+`
|
|
7
7
|
[...truncated: ${e.length-r} chars omitted]`:n+`
|
|
8
8
|
[...truncated: ${e.length-t} chars omitted]`}function it(...e){return{compress(t,n){let o=t,r=0,i=[];for(let a of e){let s=a.compress(o,n);o=s.messages,r+=s.droppedCount,s.droppedCount>0&&i.push(s.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}}}}function at(...e){return{compress(t,n){let o=t,r=0,i=[];for(let a of e){let s=a.compress(o,n);o=s.messages,r+=s.droppedCount,s.droppedCount>0&&i.push(s.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}},async compressAsync(t,n){let o=t,r=0,i=[],a=0,s=!1,l=!1;for(let u of e){let c=B(u)?await u.compressAsync(o,n):u.compress(o,n);o=c.messages,r+=c.droppedCount,c.droppedCount>0&&i.push(c.strategy),c.metrics&&(a+=c.metrics.latencyMs,s=s||c.metrics.usedLlm,l=l||!!c.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none",metrics:a>0||s?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:a,usedLlm:s,cacheInvalidated:l}:void 0}}}}function U(e,t){let n=e.filter(a=>a.role==="user"),o=e.filter(a=>a.tool_calls!=null),r=e.filter(a=>a.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(a=>{let s=typeof a.content=="string"?a.content:JSON.stringify(a.content??""),l=a.role==="user"?s:s.length>2e3?s.slice(0,2e3)+"...":s;return`[${a.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
|
|
9
|
+
`)}var O=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??S,taskContext:t.taskContext}}compress(t,n){return{messages:t,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=re(t),a=t.reduce((m,g)=>m+this.config.estimateTokens(g),0);if(a<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let s=0,l=0;for(let m=0;m<i.length&&(i[m].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));m++)s=m+1;let u=Math.max(this.config.protectedTailMessages,Math.floor(i.length*.4)),c=Math.max(s,i.length-u);if(c<=s)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let d=i.slice(0,s),p=i.slice(s,c),f=i.slice(c),C=U(p,{taskContext:this.config.taskContext}),k=await this.config.summarize(p,C),A={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
|
|
10
10
|
|
|
11
|
-
${k}`},_=[...r,...d,A,...f],M=Date.now()-o,b=_.reduce((m,g)=>m+this.config.estimateTokens(g),0);return{messages:_,droppedCount:p.length,strategy:"head-tail-protected",metrics:{tokensBefore:a,tokensAfter:b,compressionRatio:a>0?b/a:1,latencyMs:M,usedLlm:!0,cacheInvalidated:!0}}}},
|
|
11
|
+
${k}`},_=[...r,...d,A,...f],M=Date.now()-o,b=_.reduce((m,g)=>m+this.config.estimateTokens(g),0);return{messages:_,droppedCount:p.length,strategy:"head-tail-protected",metrics:{tokensBefore:a,tokensAfter:b,compressionRatio:a>0?b/a:1,latencyMs:M,usedLlm:!0,cacheInvalidated:!0}}}},w=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??S}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=re(t),a=r.findIndex(m=>typeof m.content=="string"&&m.content.startsWith("[Conversation summary")),s=a>=0?r[a]:void 0,l=a>=0?[...r.slice(0,a),...r.slice(a+1)]:r,u=Math.max(0,i.length-this.config.preserveRecentCount);if(u<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let c=t.reduce((m,g)=>m+this.config.estimateTokens(g),0);if(c<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=i.slice(0,u),p=i.slice(u),f=s&&typeof s.content=="string"?`Previous summary:
|
|
12
12
|
${s.content}
|
|
13
13
|
|
|
14
14
|
New messages to integrate:`:void 0,C=U(d,{taskContext:f}),k=await this.config.summarize(d,C),A={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
|
|
@@ -16,8 +16,8 @@ New messages to integrate:`:void 0,C=U(d,{taskContext:f}),k=await this.config.su
|
|
|
16
16
|
${k}`},_=[...l,A,...p],M=Date.now()-o,b=_.reduce((m,g)=>m+this.config.estimateTokens(g),0);return{messages:_,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:c,tokensAfter:b,compressionRatio:c>0?b/c:1,latencyMs:M,usedLlm:!0,cacheInvalidated:!0}}}},P=class{config;constructor(t){this.config=t}compress(t,n){let o=R(t),r=this.config.inner.compress(t,n),i=R(r.messages),a=o!==i&&r.droppedCount>0;return a&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:a}}}async compressAsync(t,n){let o=R(t),r=B(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),i=R(r.messages),a=o!==i&&r.droppedCount>0;return a&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:a}}}},oe={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function lt(e={}){let t={...oe,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function ct(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var N=class{events=[];maxEvents;constructor(t=100){this.maxEvents=t}record(t){this.events.push(t),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let t=this.events.length;if(t===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let n=0,o=0,r=0,i=0,a=0;for(let s of this.events)n+=s.tokensBefore>0?s.tokensAfter/s.tokensBefore:1,o+=s.latencyMs,r+=Math.max(0,s.tokensBefore-s.tokensAfter),s.usedLlm&&i++,s.cacheInvalidated&&a++;return{totalCompressions:t,totalLlmCalls:i,totalCacheInvalidations:a,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},F=class{engines=new Map;activeId;register(t){this.engines.set(t.id,t)}activate(t){return this.engines.has(t)?(this.activeId=t,!0):!1}getActive(){return this.activeId?this.engines.get(this.activeId):void 0}listEngines(){return Array.from(this.engines.values()).map(t=>({id:t.id,label:t.label,active:t.id===this.activeId}))}};function re(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function S(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function R(e){let t=Math.min(e.length,5),n=[];for(let o=0;o<t;o++){let r=e[o],i=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${i}`)}return n.join("|")}var ut=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),D=class{constructor(t=20,n=S){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=t.length-this.preserveRecentCount,r=0,i=0;return{messages:t.map((s,l)=>{if(l>=o||s.role!=="tool"||typeof s.content!="string"||!s.name||!ut.has(s.name)||s.content.length<=200)return s;let u=this.estimateTokens(s);return i+=u,r++,{...s,content:`[result cleared \u2014 ${s.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function pt(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let i=r.function?.name??"";if(/read|edit|write|file/i.test(i)&&r.function?.arguments)try{let a=JSON.parse(r.function.arguments),s=a.path??a.filePath??a.file_path??a.file;s&&typeof s=="string"&&t.set(s,n)}catch{}}o.role==="tool"&&o.name&&/read|edit|write|file/i.test(o.name)}return[...t.entries()].sort((n,o)=>o[1]-n[1]).map(([n])=>n)}async function dt(e,t,n){let o=n.estimateTokens??(p=>Math.ceil(p.length/4)),r=pt(t);if(r.length===0)return e;let i=e.map(p=>typeof p.content=="string"?p.content:"").join(`
|
|
17
17
|
`),a=r.filter(p=>!i.includes(p));if(a.length===0)return e;let s=n.maxTokenBudget,l=[],u=0;for(let p of a){if(u>=n.maxFiles||s<=0)break;let f=await n.readFile(p);if(!f)continue;let C=o(f);C>s||(s-=C,u++,l.push({role:"system",content:`[Post-compact file recovery: ${p}]
|
|
18
18
|
|
|
19
|
-
${f}`}))}if(l.length===0)return e;let c=[...e],d=-1;for(let p=0;p<c.length;p++)c[p].role==="system"&&(d=p);return c.splice(d+1,0,...l),c}function mt(e,t,n=S){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let s of e){let l=s.tool_call_id??"";if(l&&t.has(l)){o+=n(s),r++,t.delete(l);continue}i.push(s)}let a=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:a}}function ft(){return{stages:[]}}function gt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=se(e,t),a=yt(i,t,o);if(a.length===0)return{messages:i,stagedCount:0};for(let s of a)t.stages.push(s);return i=se(e,t),{messages:i,stagedCount:a.length}}function Tt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:ie(e,t),committed:n}}function se(e,t){return t.stages.filter(o=>o.committed).length===0?e:ie(e,t)}function ie(e,t){let n=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),o=[...e];for(let r of n){let[i,a]=r.range;if(i>=o.length)continue;let s=Math.min(a,o.length),l={role:"system",content:r.summary};o.splice(i,s-i,l)}return o}function yt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),a=-1,s=0;for(let l=0;l<o;l++){let u=e[l];if(u.role==="tool"||u.role==="assistant"&&typeof u.content=="string"&&u.content==="")a<0&&(a=l),s++;else{if(s>=3){let d=`${a}-${a+s}`;i.has(d)||r.push({id:`collapse_${a}_${a+s}`,range:[a,a+s],summary:`[${s} tool results collapsed]`,committed:!1})}a=-1,s=0}}if(s>=3){let l=`${a}-${a+s}`;i.has(l)||r.push({id:`collapse_${a}_${a+s}`,range:[a,a+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}import{existsSync as G,readFileSync as fe,writeFileSync as ht,readdirSync as ge,mkdirSync as Ct}from"node:fs";import{join as $,dirname as _t}from"node:path";var Bn=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100);var ae=20;var le=3,ce=2,ue=300*1e3,pe=3,de=720*60*60*1e3;var Un=300*1e3,j=4;var jn=
|
|
20
|
-
`).map(u=>u.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(x(l)===n)return r.name}}catch{}}}catch{}return null}function kt(e){if(!G(e))return 0;try{return ge(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&G($(e,t.name,"SKILL.md"))).length}catch{return 0}}function At(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<le||e.distinctToolCount<ce||Date.now()-Te<ue||t?.projectSkillsDir&&(kt(t.projectSkillsDir)>=ae||t.tools.length>0&&xt(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Ce(t.projectRoot,t.tools))}function Mt(e){return e.existingSkillName?e.feedback==="negative":!1}function Et(e,t){return Mt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:At(e,t)?(Te=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function _e(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function It(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function vt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Lt(e){if(!e.eligibility?.length)return[...e.tools];let t=vt(e.eligibility);return e.tools.filter(n=>{let o=_e(n);if(!o)return!1;let r=t.get(o);return!r||It(r.status)})}function wt(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function Ot(e){let t=wt({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Lt({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,a=typeof i?.name=="string"?i.name.trim():"";if(!a)throw new Error("tool_choice.function.name is required");let s=r.filter(l=>_e(l)===a);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${a}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:a}},extraSystemPrompt:`You must call the ${a} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Pt=["stop","aborted","timeout","cancelled","interrupted","error"],Nt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function be(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Ft(e,t){return{...e,content:[...be(e.content),...be(t.content)]}}function Dt(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function Bt(e){return new Set((e??Pt).map(t=>t.trim().toLowerCase()))}function Re(e,t){return e?Bt(t).has(e.trim().toLowerCase()):!1}function Ut(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function H(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(s=>{if(s.role==="assistant"&&Array.isArray(s.tool_calls)){let l=s.tool_calls.filter(u=>Dt(u));return{...s,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...s}}),n=new Set;for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let l of s.tool_calls)typeof l.id=="string"&&l.id&&n.add(l.id);let o=t.filter(s=>s.role!=="tool"?!0:!!(s.tool_call_id&&n.has(s.tool_call_id))),r=new Set;for(let s of o)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&r.add(s.tool_call_id);let i=[];for(let s of o){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let l=s.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(l.length===0){let{tool_calls:u,...c}=s;c.content!=null&&c.content!==""&&i.push(c);continue}if(l.length<s.tool_calls.length){i.push({...s,tool_calls:l});continue}}i.push(s)}let a=[];for(let s of i){let l=a.length>0?a[a.length-1]:void 0;if(s.role==="user"&&l?.role==="user"){a[a.length-1]=Ft(l,s);continue}a.push(s)}return a}function z(e,t){return Re(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Nt)delete o[r];return o}):[...e]}function q(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&o.add(i.tool_call_id);let r=[];for(let i of e)if(r.push({...i}),!(i.role!=="assistant"||!Array.isArray(i.tool_calls)||i.tool_calls.length===0))for(let a of i.tool_calls)typeof a.id!="string"||!a.id||o.has(a.id)||(o.add(a.id),r.push({role:"tool",tool_call_id:a.id,content:n}));return r}function jt(e,t){let n=H(e),o=z(n,t);return q(o,t)}function Se(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=Re(t?.stopReason,t?.forcedStopReasons),r=[];for(let u=0;u<e.length;u+=1){let c=e[u];if(!c||typeof c!="object"){r.push(c);continue}if(c.type==="reasoning"&&typeof c.id=="string"&&c.id.startsWith("rs_")&&!e.slice(u+1).some(f=>f&&typeof f=="object"&&f.type!=="reasoning"))continue;if(c.type!=="function_call"){r.push({...c});continue}let d={...c};if(typeof d.id=="string"){let p=Ut(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let i=new Set,a=new Map;for(let u of r){if(u.type!=="function_call")continue;let c=typeof u.call_id=="string"&&u.call_id?u.call_id:typeof u.id=="string"?u.id:void 0;c&&(i.add(c),a.set(c,u))}let s=new Set,l=[];for(let u of r)if(!(o&&u.type==="function_call")){if(u.type==="function_call_output"){let c=typeof u.call_id=="string"?u.call_id:"";if(!c||!i.has(c))continue;s.add(c)}l.push(u)}for(let[u]of a)s.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function Gt(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function $t(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function Ht(e){let t=new Set,n=new Set;for(let o of e){if(o.type==="function_call"){let r=typeof o.call_id=="string"&&o.call_id?o.call_id:typeof o.id=="string"?o.id:"";r&&t.add(r)}o.type==="function_call_output"&&typeof o.call_id=="string"&&o.call_id&&n.add(o.call_id)}return[...t].filter(o=>!n.has(o))}function zt(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function xe(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function qt(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Xt(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Kt(e){let t=[],n=H(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=z(n,e.options);o.some((i,a)=>i!==n[a])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=q(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Gt(r),completedToolCallIds:$t(r)}),recoveryActions:t}}function Yt(e){let t=Se(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:Ht(t),completedToolCallIds:zt(t)}),recoveryActions:n}}var Wt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Vt(e){return e?Wt.has(e):!0}function Jt(e){return e===429||e===529}function Zt(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var to={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Qt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var X=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var K="<fork-child-context>",ke="Fork started \u2014 processing in background";function en(e){return JSON.stringify(e).includes(K)}function tn(e){return e<j}function nn(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
|
|
19
|
+
${f}`}))}if(l.length===0)return e;let c=[...e],d=-1;for(let p=0;p<c.length;p++)c[p].role==="system"&&(d=p);return c.splice(d+1,0,...l),c}function mt(e,t,n=S){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let s of e){let l=s.tool_call_id??"";if(l&&t.has(l)){o+=n(s),r++,t.delete(l);continue}i.push(s)}let a=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:a}}function ft(){return{stages:[]}}function gt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=se(e,t),a=yt(i,t,o);if(a.length===0)return{messages:i,stagedCount:0};for(let s of a)t.stages.push(s);return i=se(e,t),{messages:i,stagedCount:a.length}}function Tt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:ie(e,t),committed:n}}function se(e,t){return t.stages.filter(o=>o.committed).length===0?e:ie(e,t)}function ie(e,t){let n=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),o=[...e];for(let r of n){let[i,a]=r.range;if(i>=o.length)continue;let s=Math.min(a,o.length),l={role:"system",content:r.summary};o.splice(i,s-i,l)}return o}function yt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),a=-1,s=0;for(let l=0;l<o;l++){let u=e[l];if(u.role==="tool"||u.role==="assistant"&&typeof u.content=="string"&&u.content==="")a<0&&(a=l),s++;else{if(s>=3){let d=`${a}-${a+s}`;i.has(d)||r.push({id:`collapse_${a}_${a+s}`,range:[a,a+s],summary:`[${s} tool results collapsed]`,committed:!1})}a=-1,s=0}}if(s>=3){let l=`${a}-${a+s}`;i.has(l)||r.push({id:`collapse_${a}_${a+s}`,range:[a,a+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}import{existsSync as G,readFileSync as fe,writeFileSync as ht,readdirSync as ge,mkdirSync as Ct}from"node:fs";import{join as $,dirname as _t}from"node:path";var Bn=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100);var ae=20;var le=3,ce=2,ue=300*1e3,pe=3,de=720*60*60*1e3;var Un=300*1e3,j=4;var jn=3600*1e3;var Gn=50*1024,$n=500*1024,Hn=500*1024*1024,zn=50*1024*1024;var qn=60*1024;var Te=0;var bt="skill-patterns.json";function ye(e){return $(e,".qlogicagent",bt)}function he(e){let t=ye(e);try{return JSON.parse(fe(t,"utf8"))}catch{return{version:1,patterns:{}}}}function me(e,t){let n=ye(e);Ct(_t(n),{recursive:!0}),ht(n,JSON.stringify(t,null,2),"utf8")}function Rt(e){let t=Date.now()-de;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function Ce(e,t){if(t.length===0)return!1;let n=x(t),o=he(e);Rt(o);let r=new Date().toISOString(),i=o.patterns[n];if(i||(i={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=i),i.promoted)return me(e,o),!1;i.count++,i.lastSeen=r;let a=i.count>=pe;return a&&(i.promoted=!0),me(e,o),a}function St(e){let t=he(e);return Object.values(t.patterns)}function x(e){return[...e].sort().join("+")}function xt(e,t){if(!G(t))return null;let n=x(e);try{let o=ge(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let i=$(t,r.name,"SKILL.md");try{let s=fe(i,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(s){let l=s[1].split(`
|
|
20
|
+
`).map(u=>u.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(x(l)===n)return r.name}}catch{}}}catch{}return null}function kt(e){if(!G(e))return 0;try{return ge(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&G($(e,t.name,"SKILL.md"))).length}catch{return 0}}function At(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<le||e.distinctToolCount<ce||Date.now()-Te<ue||t?.projectSkillsDir&&(kt(t.projectSkillsDir)>=ae||t.tools.length>0&&xt(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Ce(t.projectRoot,t.tools))}function Mt(e){return e.existingSkillName?e.feedback==="negative":!1}function Et(e,t){return Mt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:At(e,t)?(Te=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function _e(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function It(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function vt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Lt(e){if(!e.eligibility?.length)return[...e.tools];let t=vt(e.eligibility);return e.tools.filter(n=>{let o=_e(n);if(!o)return!1;let r=t.get(o);return!r||It(r.status)})}function Ot(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function wt(e){let t=Ot({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Lt({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,a=typeof i?.name=="string"?i.name.trim():"";if(!a)throw new Error("tool_choice.function.name is required");let s=r.filter(l=>_e(l)===a);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${a}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:a}},extraSystemPrompt:`You must call the ${a} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Pt=["stop","aborted","timeout","cancelled","interrupted","error"],Nt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function be(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Ft(e,t){return{...e,content:[...be(e.content),...be(t.content)]}}function Dt(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function Bt(e){return new Set((e??Pt).map(t=>t.trim().toLowerCase()))}function Re(e,t){return e?Bt(t).has(e.trim().toLowerCase()):!1}function Ut(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function H(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(s=>{if(s.role==="assistant"&&Array.isArray(s.tool_calls)){let l=s.tool_calls.filter(u=>Dt(u));return{...s,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...s}}),n=new Set;for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let l of s.tool_calls)typeof l.id=="string"&&l.id&&n.add(l.id);let o=t.filter(s=>s.role!=="tool"?!0:!!(s.tool_call_id&&n.has(s.tool_call_id))),r=new Set;for(let s of o)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&r.add(s.tool_call_id);let i=[];for(let s of o){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let l=s.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(l.length===0){let{tool_calls:u,...c}=s;c.content!=null&&c.content!==""&&i.push(c);continue}if(l.length<s.tool_calls.length){i.push({...s,tool_calls:l});continue}}i.push(s)}let a=[];for(let s of i){let l=a.length>0?a[a.length-1]:void 0;if(s.role==="user"&&l?.role==="user"){a[a.length-1]=Ft(l,s);continue}a.push(s)}return a}function z(e,t){return Re(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Nt)delete o[r];return o}):[...e]}function q(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&o.add(i.tool_call_id);let r=[];for(let i of e)if(r.push({...i}),!(i.role!=="assistant"||!Array.isArray(i.tool_calls)||i.tool_calls.length===0))for(let a of i.tool_calls)typeof a.id!="string"||!a.id||o.has(a.id)||(o.add(a.id),r.push({role:"tool",tool_call_id:a.id,content:n}));return r}function jt(e,t){let n=H(e),o=z(n,t);return q(o,t)}function Se(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=Re(t?.stopReason,t?.forcedStopReasons),r=[];for(let u=0;u<e.length;u+=1){let c=e[u];if(!c||typeof c!="object"){r.push(c);continue}if(c.type==="reasoning"&&typeof c.id=="string"&&c.id.startsWith("rs_")&&!e.slice(u+1).some(f=>f&&typeof f=="object"&&f.type!=="reasoning"))continue;if(c.type!=="function_call"){r.push({...c});continue}let d={...c};if(typeof d.id=="string"){let p=Ut(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let i=new Set,a=new Map;for(let u of r){if(u.type!=="function_call")continue;let c=typeof u.call_id=="string"&&u.call_id?u.call_id:typeof u.id=="string"?u.id:void 0;c&&(i.add(c),a.set(c,u))}let s=new Set,l=[];for(let u of r)if(!(o&&u.type==="function_call")){if(u.type==="function_call_output"){let c=typeof u.call_id=="string"?u.call_id:"";if(!c||!i.has(c))continue;s.add(c)}l.push(u)}for(let[u]of a)s.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function Gt(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function $t(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function Ht(e){let t=new Set,n=new Set;for(let o of e){if(o.type==="function_call"){let r=typeof o.call_id=="string"&&o.call_id?o.call_id:typeof o.id=="string"?o.id:"";r&&t.add(r)}o.type==="function_call_output"&&typeof o.call_id=="string"&&o.call_id&&n.add(o.call_id)}return[...t].filter(o=>!n.has(o))}function zt(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function xe(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function qt(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Xt(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Kt(e){let t=[],n=H(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=z(n,e.options);o.some((i,a)=>i!==n[a])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=q(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Gt(r),completedToolCallIds:$t(r)}),recoveryActions:t}}function Yt(e){let t=Se(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:Ht(t),completedToolCallIds:zt(t)}),recoveryActions:n}}var Wt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Vt(e){return e?Wt.has(e):!0}function Jt(e){return e===429||e===529}function Zt(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var no={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Qt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var X=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var K="<fork-child-context>",ke="Fork started \u2014 processing in background";function en(e){return JSON.stringify(e).includes(K)}function tn(e){return e<j}function nn(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
|
|
21
21
|
|
|
22
22
|
Your working directory is: ${e.worktreePath}
|
|
23
23
|
All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${K}
|
|
@@ -35,4 +35,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
|
|
|
35
35
|
|
|
36
36
|
${t.join(`
|
|
37
37
|
|
|
38
|
-
`)}`}function Mn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function En(e,t=kn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{P as CacheAwareCompressionStrategy,N as CompressionMetricsCollector,F as ContextEngineRegistry,oe as DEFAULT_ADAPTIVE_BUDGET_CONFIG,ke as FORK_PLACEHOLDER_RESULT,K as FORK_SENTINEL_TAG,X as FallbackTriggeredError,
|
|
38
|
+
`)}`}function Mn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function En(e,t=kn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{P as CacheAwareCompressionStrategy,N as CompressionMetricsCollector,F as ContextEngineRegistry,oe as DEFAULT_ADAPTIVE_BUDGET_CONFIG,ke as FORK_PLACEHOLDER_RESULT,K as FORK_SENTINEL_TAG,X as FallbackTriggeredError,O as HeadTailProtectedStrategy,w as IncrementalCompactStrategy,j as MAX_FORK_DEPTH,D as MicroCompactStrategy,I as SlidingWindowStrategy,v as SummarizeOldStrategy,L as ToolResultTrimStrategy,qt as advanceToolLoopState,gt as applyContextCollapsesIfNeeded,wt as applyToolChoicePolicy,Ae as buildAssistantToolCallMessage,on as buildForkPlaceholderResults,nn as buildForkedMessages,An as buildPostCompactRestorationMessage,Et as buildSkillInstruction,U as buildStructuredSummaryPrompt,Me as buildToolResultMessage,x as buildToolSignature,bn as calculateTokenWarningState,tn as canForkAtDepth,ot as classifyError,at as composeAsyncStrategies,it as composeStrategies,lt as computeAdaptiveBudget,Zt as computeRetryBackoff,ft as createCollapseStore,Mn as createReactiveCompactState,Cn as createTaskState,_n as createTurnLoopGuardState,hn as filterToolsByRole,sn as generateForkChildAgentId,fn as getBuiltInAgent,mn as getBuiltInAgents,St as getPatternStats,B as isAsyncCompressionStrategy,gn as isBuiltInAgent,Vt as isForegroundSource,en as isInForkChild,Qt as isPersistentRetryEnabled,rt as isRetryableCategory,Jt as isTransientCapacityError,dt as postCompactFileRecovery,Ce as recordPatternAndCheckThreshold,Tt as recoverContextCollapseFromOverflow,Kt as recoverToolLoopStateFromChatConversation,Yt as recoverToolLoopStateFromResponsesItems,jt as repairOpenAiChatConversation,Tn as resolveAgentToolSet,Rn as resolveApiErrorRecovery,rn as resolveForkChildTools,Sn as resolveOutputTokenEscalation,ct as selectCompressionTier,Xt as settleToolLoopState,xn as shouldAbortTurn,En as shouldAttemptReactiveCompact,mt as snipCompactIfNeeded};
|
package/dist/protocol.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var V="1.0.0",W={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TURN_ABORTED:-32e3,TURN_TIMEOUT:-32001,LLM_ERROR:-32010,LLM_AUTH_ERROR:-32011,LLM_RATE_LIMIT:-32012,LLM_QUOTA_EXHAUSTED:-32013,LLM_MODEL_NOT_FOUND:-32014,TOOL_INVOKE_FAILED:-32020,TOOL_TIMEOUT:-32021,PROTOCOL_MISMATCH:-32030},F={REQUEST:"tool.approval.request",RESPONSE:"tool.approval.response"};function S(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&t.method.length>0}function P(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&(typeof t.id=="string"||typeof t.id=="number")&&!("method"in t)}function T(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function B(e){let t;try{t=JSON.parse(e)}catch{return null}return P(t)||S(t)||T(t)?t:null}var j=["session.list","session.get","session.create","session.update","session.delete","session.archive","session.getState","session.switchProject","session.getMessages","project.list","project.create","project.delete","project.rename","project.archive","project.unarchive","project.archiveByGroup","instructions.list","instructions.read","instructions.write","instructions.delete","files.list","files.read","files.create","files.rename","files.delete","files.gitStatus"];var C=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.approval_request","turn.skill_instruction","turn.ask_user","turn.media_result","turn.media_progress","turn.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_delta","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.usage_update","team.member.notification","session.info","memory.updated"],b=["solo.progress","solo.agentDelta","solo.agentUsage","solo.agentDiff","solo.evaluation","product.taskStarted","product.taskOutput","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.checkpointed","product.dagTopology","plan.interrupted"],Y=[...C,...b];var X=1,H={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_END:"session/end",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",SESSION_UPDATE:"session/update",SESSION_REQUEST_PERMISSION:"session/request_permission",FS_READ_TEXT_FILE:"fs/read_text_file",FS_WRITE_TEXT_FILE:"fs/write_text_file"},G={ABORT:"x/abort",DREAM:"x/dream",AGENTS_LIST:"x/agents.list",SOLO_START:"x/solo.start",SOLO_STATUS:"x/solo.status",SOLO_SELECT:"x/solo.select",SOLO_CANCEL:"x/solo.cancel",PRODUCT_CREATE:"x/product.create",PRODUCT_PLAN:"x/product.plan",PRODUCT_CONFIRM:"x/product.confirm",PRODUCT_MESSAGE:"x/product.message",PRODUCT_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_STATUS:"x/product.status",SOLO_SUBSCRIBE:"x/solo.subscribe",SOLO_MESSAGE:"x/solo.message",SOLO_EVALUATE:"x/solo.evaluate",PRODUCT_SUBSCRIBE:"x/product.subscribe",TEAM_DELEGATE:"x/team.delegate"},I={AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",USAGE_UPDATE:"usage_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",AVAILABLE_COMMANDS_UPDATE:"available_commands_update"},q={X_SUBAGENT_STARTED:"x_subagent_started",X_SUBAGENT_DELTA:"x_subagent_delta",X_SUBAGENT_ENDED:"x_subagent_ended",X_MEDIA_RESULT:"x_media_result",X_MEDIA_PROGRESS:"x_media_progress",X_SKILL_INSTRUCTION:"x_skill_instruction",X_RECOVERY:"x_recovery",X_SIDECHAIN_STARTED:"x_sidechain_started",X_SIDECHAIN_COMPLETED:"x_sidechain_completed",X_SUGGESTIONS:"x_suggestions",X_ASK_USER:"x_ask_user",X_SESSION_INFO:"x_session_info",X_MEMORY_UPDATED:"x_memory_updated",X_TEAM_MEMBER_UPDATE:"x_team_member_update",X_SOLO_STARTED:"x_solo_started",X_SOLO_AGENT_FINISHED:"x_solo_agent_finished",X_SOLO_SELECTED:"x_solo_selected",X_PRODUCT_TASK_STARTED:"x_product_task_started",X_PRODUCT_TASK_COMPLETED:"x_product_task_completed",X_PRODUCT_CHECKPOINT:"x_product_checkpoint"};function v(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&"id"in t}function M(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function h(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&"id"in t&&!("method"in t)}function z(e){let t;try{t=JSON.parse(e)}catch{return null}return h(t)||v(t)||M(t)?t:null}function J(e){return Object.values(I).includes(e)}function $(e){return e.startsWith("x_")}var A=["gatewayVersion","toolNamespaces","workspaceIds","installedCapabilities","enabledCapabilities","features","approvalMode","toolManifests","skillManifests","pluginManifests","mcpManifests","approvalPolicy","workspaceSummaries"];function d(e){return e?e.map(t=>({...t})):void 0}function m(e){return e?e.map(t=>({...t})):void 0}function Q(e){return e?[...e]:void 0}function k(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort((t,o)=>t.localeCompare(o))}function g(e){return{...e,toolNamespaces:[...e.toolNamespaces],workspaceIds:[...e.workspaceIds],...e.changedSections?{changedSections:[...e.changedSections]}:{},...e.installedCapabilities?{installedCapabilities:[...e.installedCapabilities]}:{},...e.enabledCapabilities?{enabledCapabilities:[...e.enabledCapabilities]}:{},...e.features?{features:[...e.features]}:{},...e.toolManifests?{toolManifests:d(e.toolManifests)}:{},...e.skillManifests?{skillManifests:d(e.skillManifests)}:{},...e.pluginManifests?{pluginManifests:d(e.pluginManifests)}:{},...e.mcpManifests?{mcpManifests:d(e.mcpManifests)}:{},...e.approvalPolicy?{approvalPolicy:{...e.approvalPolicy}}:{},...e.workspaceSummaries?{workspaceSummaries:m(e.workspaceSummaries)}:{}}}function Z(e){let{previous:t,update:o}=e;return!(o.syncMode==="diff"&&t&&(!o.baseSnapshotVersion||t.snapshotVersion===o.baseSnapshotVersion))||!t?g(o):{...g(t),snapshotVersion:o.snapshotVersion,updatedAt:o.updatedAt,...o.gatewayVersion!==void 0?{gatewayVersion:o.gatewayVersion}:{},...o.syncMode?{syncMode:o.syncMode}:{},...o.baseSnapshotVersion?{baseSnapshotVersion:o.baseSnapshotVersion}:{},...o.changedSections?{changedSections:[...o.changedSections]}:{},...o.toolNamespaces?{toolNamespaces:[...o.toolNamespaces]}:{},...o.workspaceIds?{workspaceIds:[...o.workspaceIds]}:{},...o.installedCapabilities?{installedCapabilities:[...o.installedCapabilities]}:{},...o.enabledCapabilities?{enabledCapabilities:[...o.enabledCapabilities]}:{},...o.features?{features:[...o.features]}:{},...o.approvalMode?{approvalMode:o.approvalMode}:{},...o.toolManifests?{toolManifests:d(o.toolManifests)}:{},...o.skillManifests?{skillManifests:d(o.skillManifests)}:{},...o.pluginManifests?{pluginManifests:d(o.pluginManifests)}:{},...o.mcpManifests?{mcpManifests:d(o.mcpManifests)}:{},...o.approvalPolicy?{approvalPolicy:{...o.approvalPolicy}}:{},...o.workspaceSummaries?{workspaceSummaries:m(o.workspaceSummaries)}:{}}}function ee(e){return k(e.map(t=>t.name.split(".")[0]??"").filter(Boolean))}function te(e){return k(e.map(t=>t.id))}function oe(e){let{previous:t,current:o}=e;if(!t)return{...g(o),syncMode:"full"};if(t.snapshotVersion===o.snapshotVersion)return null;let i=A.filter(n=>JSON.stringify(t[n])!==JSON.stringify(o[n]));if(i.length===A.length)return{...g(o),syncMode:"full"};let u={snapshotVersion:o.snapshotVersion,updatedAt:o.updatedAt,syncMode:"diff",baseSnapshotVersion:t.snapshotVersion,changedSections:i,toolNamespaces:[...o.toolNamespaces],workspaceIds:[...o.workspaceIds]},p=u;for(let n of i){let r=o[n];if(r!==void 0)switch(n){case"toolNamespaces":case"workspaceIds":case"installedCapabilities":case"enabledCapabilities":case"features":p[n]=Q(r);break;case"approvalPolicy":p[n]={...r};break;case"workspaceSummaries":p[n]=m(r);break;case"toolManifests":case"skillManifests":case"pluginManifests":case"mcpManifests":p[n]=d(r);break;default:p[n]=r;break}}return u}var re=["web_search","web_fetch","deep_research","browser_execution"],ie=["web-intelligence","browser-execution"],ne=["discovery","read-url","multi-source-research","interactive-browser"],se=["stateless","render-backend","interactive-session"],ae=["stateless","stateless-single-step","stateful-session-required"],pe=["required","conditional","none"],ce=["browser-read","browser-authenticated-read","browser-state-changing"],le=["read-page","read-authenticated-page","fill-form","submit-form","download-file","reuse-session"],de=["web_search","web_fetch","deep_research","blocked"],ue=["requires-interaction","requires-login-state","requires-rendered-dom","requires-persistent-session","requires-state-changing-action"],ge=["none","same-capability-once","degrade-only"];var ye=["prefetch","sync_turn","on_pre_compress","on_session_end","on_delegation","on_memory_write"],fe=["turn","sidechain","compress","session-end","agent-remember","auto-extract","implicit-extract","profile-extraction","dream"],Ae=["observe-only","parent-write","deny"];var me=2,s={gatewayImage:"gateway.image.desktop-slim",whisperModelTiny:"speech.whisper.model.tiny",ffmpegWin32X64:"runtime.ffmpeg.win32-x64",nodeWin32X64:"runtime.node.win32-x64",dockerDesktopWin32X64:"runtime.docker-desktop.win32-x64",dockerDesktopDarwinX64:"runtime.docker-desktop.darwin-x64",dockerDesktopDarwinArm64:"runtime.docker-desktop.darwin-arm64"},y={desktopDockerBridge:"desktop.docker-bridge",desktopEmbeddedWin32X64:"desktop.embedded.win32-x64"};function O(e){return{...e,artifacts:e.artifacts.map(t=>({...t}))}}function Ee(e){return{...e,assetIds:[...e.assetIds]}}function N(){return{[y.desktopDockerBridge]:{id:y.desktopDockerBridge,title:"Desktop Docker Bridge",platform:"any",assetIds:[s.gatewayImage,s.dockerDesktopWin32X64,s.dockerDesktopDarwinX64,s.dockerDesktopDarwinArm64],description:"Docker bridge mode downloads the desktop slim gateway image on demand."},[y.desktopEmbeddedWin32X64]:{id:y.desktopEmbeddedWin32X64,title:"Desktop Embedded Win32 x64",platform:"win32-x64",assetIds:[s.nodeWin32X64,s.ffmpegWin32X64,s.whisperModelTiny],description:"Embedded desktop mode requires the bundled Node/FFmpeg runtimes and the whisper model asset."}}}function D(e,t){return e.assets[t]}function w(e,t){return e.profiles[t]}function Re(e,t){let o=w(e,t);return o?o.assetIds.map(i=>D(e,i)).filter(i=>!!i):[]}function _e(e,t){return e.assets[t.id]=O(t),U(e)}function E(e){if(!e)return;let t=e.artifacts[0];if(!(!t?.url||!t.sha256||typeof t.size!="number"))return{version:e.version,sha256:t.sha256,size:t.size,url:t.url}}function U(e){let t=E(e.assets[s.gatewayImage]),o=E(e.assets[s.whisperModelTiny]);return{...e,gateway:t,whisperModel:o}}function x(e,t){if(!(typeof e.version!="string"||typeof e.url!="string"))return{...t,version:e.version,artifacts:[{fileName:e.url.split("/").pop()||`${t.id}.bin`,url:e.url,sha256:typeof e.sha256=="string"?e.sha256:void 0,size:typeof e.size=="number"?e.size:void 0}]}}function Se(e){let t=e&&typeof e=="object"?e:{},o={},i=t.assets&&typeof t.assets=="object"?t.assets:{};for(let[r,a]of Object.entries(i)){if(!a||typeof a!="object")continue;let l=a;!l.id||!Array.isArray(l.artifacts)||(o[r]=O(l))}if(!o[s.gatewayImage]&&t.gateway&&typeof t.gateway=="object"){let r=x(t.gateway,{id:s.gatewayImage,title:"OpenClaw Gateway Image (Desktop Slim)",kind:"container-image",delivery:"remote",platform:"any",description:"Desktop Docker mode gateway image."});r&&(o[r.id]=r)}if(!o[s.whisperModelTiny]&&t.whisperModel&&typeof t.whisperModel=="object"){let r=x(t.whisperModel,{id:s.whisperModelTiny,title:"Whisper Tiny Model",kind:"model",delivery:"remote",platform:"any",description:"Shared whisper.cpp tiny model asset for embedded desktop speech recognition."});r&&(o[r.id]=r)}let p={...N()},n=t.profiles&&typeof t.profiles=="object"?t.profiles:{};for(let[r,a]of Object.entries(n)){if(!a||typeof a!="object")continue;let l=a;!l.id||!Array.isArray(l.assetIds)||(p[r]=Ee(l))}return U({schemaVersion:typeof t.schemaVersion=="number"?t.schemaVersion:2,channel:typeof t.channel=="string"?t.channel:void 0,publishedAt:typeof t.publishedAt=="string"?t.publishedAt:void 0,minElectronVersion:typeof t.minElectronVersion=="string"?t.minElectronVersion:void 0,releaseNotes:typeof t.releaseNotes=="string"?t.releaseNotes:void 0,assets:o,profiles:p})}var Pe=["pending","captured","failed","restored"],Te=["file","directory","missing"],Ce=["metadata-only","workspace-copy","shadow-git"];var be=["api-key","oauth","token","aws-sdk"],Ie=["rate_limit","auth","server_error","timeout","network","unknown"],ve=["requiresOpenAiAnthropicToolPayload"];function Me(e,t){return!e||typeof e!="object"||Array.isArray(e)?!1:e[t]===!0}var L="openai-codex";function f(e){let t=e.trim().toLowerCase();return t==="z.ai"||t==="z-ai"?"zai":t==="opencode-zen"?"opencode":t==="kimi-code"?"kimi-coding":t==="bedrock"||t==="aws-bedrock"?"amazon-bedrock":t==="bytedance"||t==="doubao"?"volcengine":t}function K(e){let t=f(e);return t==="volcengine-plan"?"volcengine":t==="byteplus-plan"?"byteplus":t}var he=K,ke={anthropicToolSchemaMode:"native",anthropicToolChoiceMode:"native",providerFamily:"default",preserveAnthropicThinkingSignatures:!0,openAiCompatTurnValidation:!0,providerThoughtSignatureSanitization:!1,transcriptToolCallIdMode:"default",transcriptToolCallIdModelHints:[],providerThoughtSignatureModelHints:[],dropThinkingBlockModelHints:[]},xe={anthropic:{providerFamily:"anthropic"},"amazon-bedrock":{providerFamily:"anthropic"},"kimi-coding":{anthropicToolSchemaMode:"openai-functions",anthropicToolChoiceMode:"openai-string-modes",preserveAnthropicThinkingSignatures:!1},mistral:{transcriptToolCallIdMode:"strict9",transcriptToolCallIdModelHints:["mistral","mixtral","codestral","pixtral","devstral","ministral","mistralai"]},openai:{providerFamily:"openai"},[L]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};function R(e,t){let o=(e??"").toLowerCase();return!!o&&t.some(i=>o.includes(i))}function c(e){let t=f(e??"");return{...ke,...xe[t]}}function Oe(e){return c(e).preserveAnthropicThinkingSignatures}function Ne(e){let t=c(e);return t.anthropicToolSchemaMode!=="native"||t.anthropicToolChoiceMode!=="native"}function De(e){return c(e).anthropicToolSchemaMode==="openai-functions"}function we(e){return c(e).anthropicToolChoiceMode==="openai-string-modes"}function Ue(e){return c(e).openAiCompatTurnValidation}function Le(e){return c(e).providerFamily==="openai"}function Ke(e){return c(e).providerFamily==="anthropic"}function Ve(e){return R(e.modelId,c(e.provider).dropThinkingBlockModelHints)}function We(e){let t=c(e.provider);return t.providerThoughtSignatureSanitization&&R(e.modelId,t.providerThoughtSignatureModelHints)}function Fe(e,t){let o=c(e),i=o.transcriptToolCallIdMode;if(i==="strict9")return i;if(R(t,o.transcriptToolCallIdModelHints))return"strict9"}var _={anthropic:["ANTHROPIC_OAUTH_TOKEN","ANTHROPIC_API_KEY"],chutes:["CHUTES_OAUTH_TOKEN","CHUTES_API_KEY"],zai:["ZAI_API_KEY","Z_AI_API_KEY"],opencode:["OPENCODE_API_KEY","OPENCODE_ZEN_API_KEY"],volcengine:["VOLCANO_ENGINE_API_KEY"],"volcengine-plan":["VOLCANO_ENGINE_API_KEY"],byteplus:["BYTEPLUS_API_KEY"],"byteplus-plan":["BYTEPLUS_API_KEY"],"kimi-coding":["KIMI_API_KEY","KIMICODE_API_KEY"],huggingface:["HUGGINGFACE_HUB_TOKEN","HF_TOKEN"],openai:["OPENAI_API_KEY"],voyage:["VOYAGE_API_KEY"],groq:["GROQ_API_KEY"],deepgram:["DEEPGRAM_API_KEY"],cerebras:["CEREBRAS_API_KEY"],xai:["XAI_API_KEY"],openrouter:["OPENROUTER_API_KEY"],litellm:["LITELLM_API_KEY"],"vercel-ai-gateway":["AI_GATEWAY_API_KEY"],"cloudflare-ai-gateway":["CLOUDFLARE_AI_GATEWAY_API_KEY"],moonshot:["MOONSHOT_API_KEY"],minimax:["MINIMAX_API_KEY"],"minimax-cn":["MINIMAX_CN_API_KEY","MINIMAX_API_KEY"],nvidia:["NVIDIA_API_KEY"],xiaomi:["XIAOMI_API_KEY"],synthetic:["SYNTHETIC_API_KEY"],venice:["VENICE_API_KEY"],mistral:["MISTRAL_API_KEY"],together:["TOGETHER_API_KEY"],qianfan:["QIANFAN_API_KEY"],ollama:["OLLAMA_API_KEY"],vllm:["VLLM_API_KEY"],kilocode:["KILOCODE_API_KEY"]};function Be(){return[...new Set(Object.values(_).flat())]}function je(e){let t=f(e.provider),o=e.env??process.env,i=new Set(e.appliedEnvKeys??[]),u=r=>{let a=o[r]?.trim();if(!a)return null;let l=i.has(r)?`shell env: ${r}`:`env: ${r}`;return{apiKey:a,source:l}},p=e.resolveSpecialApiKey?.(t,o,i);if(p)return p;let n=_[t];if(!n||n.length===0)return null;for(let r of n){let a=u(r);if(a)return a}return null}export{G as ACP_EXTENDED_METHODS,q as ACP_EXTENDED_SESSION_UPDATE_TYPES,H as ACP_METHODS,X as ACP_PROTOCOL_VERSION,I as ACP_SESSION_UPDATE_TYPES,F as AGENT_RPC_APPROVAL_METHODS,W as AGENT_RPC_ERROR_CODES,V as AGENT_RPC_PROTOCOL_VERSION,b as AGENT_TEAM_WS_EVENT_NAMES,C as AGENT_WS_EVENT_NAMES,Y as ALL_AGENT_WS_EVENT_NAMES,A as CAPABILITY_MANIFEST_DIFF_SECTIONS,j as GATEWAY_RPC_METHODS,ye as MEMORY_OBSERVATION_HOOK_VALUES,fe as MEMORY_OBSERVATION_SOURCE_VALUES,Ae as MEMORY_WRITE_ACCESS_VALUES,Ce as MUTATION_CHECKPOINT_BACKEND_VALUES,Te as MUTATION_CHECKPOINT_ENTRY_KIND_VALUES,Pe as MUTATION_CHECKPOINT_PHASE_VALUES,be as PROVIDER_RUNTIME_AUTH_MODE_VALUES,ve as PROVIDER_RUNTIME_COMPAT_FLAG_VALUES,_ as PROVIDER_RUNTIME_ENV_API_KEY_CANDIDATES,L as PROVIDER_RUNTIME_OPENAI_CODEX_PROVIDER_ID,Ie as PROVIDER_RUNTIME_VAULT_ERROR_TYPE_VALUES,me as RESOURCE_MANIFEST_SCHEMA_VERSION,s as RUNTIME_ASSET_IDS,y as RUNTIME_PROFILE_IDS,le as WEB_ACTION_SCOPE_VALUES,pe as WEB_APPROVAL_DEFAULT_VALUES,ie as WEB_CAPABILITY_FAMILY_VALUES,re as WEB_CAPABILITY_ID_VALUES,de as WEB_DEGRADATION_TARGET_VALUES,ue as WEB_ESCALATION_REASON_VALUES,se as WEB_EXECUTION_MODE_VALUES,ce as WEB_POLICY_RISK_CLASS_VALUES,ge as WEB_RETRY_POLICY_VALUES,ae as WEB_STATEFULNESS_VALUES,ne as WEB_TASK_MODE_VALUES,g as cloneCapabilityManifestSnapshot,oe as createCapabilityManifestDiffPayload,N as createDefaultRuntimeResourceProfiles,ee as deriveCapabilityToolNamespaces,te as deriveCapabilityWorkspaceIds,E as getManifestShortcutEntry,D as getRuntimeResourceAsset,w as getRuntimeResourceProfile,Re as getRuntimeResourceProfileAssets,M as isAcpJsonRpcNotification,v as isAcpJsonRpcRequest,h as isAcpJsonRpcResponse,T as isAgentRpcNotification,S as isAgentRpcRequest,P as isAgentRpcResponse,Ke as isAnthropicProviderRuntimeFamily,$ as isExtendedSessionUpdateType,Le as isOpenAiProviderRuntimeFamily,J as isStandardSessionUpdateType,Be as listProviderRuntimeEnvApiKeyNames,Z as mergeCapabilityManifestSnapshot,f as normalizeProviderRuntimeId,K as normalizeProviderRuntimeIdForAuth,Se as normalizeRuntimeResourceManifest,z as parseAcpMessage,B as parseAgentRpcMessage,Oe as preservesProviderRuntimeAnthropicThinkingSignatures,Me as readProviderRuntimeCompatFlag,Ne as requiresOpenAiCompatibleAnthropicToolPayloadForProviderRuntime,c as resolveProviderRuntimeCapabilities,je as resolveProviderRuntimeEnvApiKey,he as resolveProviderRuntimeKeyFamily,Fe as resolveProviderRuntimeTranscriptToolCallIdMode,Ve as shouldDropThinkingBlocksForProviderRuntimeModel,We as shouldSanitizeProviderRuntimeThoughtSignaturesForModel,Ue as supportsOpenAiCompatTurnValidationForProviderRuntime,_e as upsertRuntimeResourceAsset,De as usesOpenAiFunctionAnthropicToolSchemaForProviderRuntime,we as usesOpenAiStringModeAnthropicToolChoiceForProviderRuntime};
|
|
1
|
+
var V="1.0.0",W={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TURN_ABORTED:-32e3,TURN_TIMEOUT:-32001,LLM_ERROR:-32010,LLM_AUTH_ERROR:-32011,LLM_RATE_LIMIT:-32012,LLM_QUOTA_EXHAUSTED:-32013,LLM_MODEL_NOT_FOUND:-32014,TOOL_INVOKE_FAILED:-32020,TOOL_TIMEOUT:-32021,PROTOCOL_MISMATCH:-32030},F={REQUEST:"tool.approval.request",RESPONSE:"tool.approval.response"};function _(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&t.method.length>0}function P(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&(typeof t.id=="string"||typeof t.id=="number")&&!("method"in t)}function T(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function B(e){let t;try{t=JSON.parse(e)}catch{return null}return P(t)||_(t)||T(t)?t:null}var j=["session.list","session.get","session.create","session.update","session.delete","session.deleteAll","session.archive","session.moveToProject","session.getState","session.switchProject","session.getMessages","project.list","project.create","project.delete","project.rename","project.archive","project.unarchive","project.update","project.archiveByGroup","project.purgeAll","instructions.list","instructions.read","instructions.write","instructions.delete","files.list","files.read","files.create","files.rename","files.delete","files.gitStatus","skills.list","memory.list-files","memory.atlas","memory.activity"];var C=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.approval_request","turn.skill_instruction","turn.ask_user","turn.media_result","turn.media_progress","turn.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_delta","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.usage_update","team.member.notification","session.info","memory.updated","skills.updated","pet.soul_ready","pet.reaction","pet.growth","pet.state","pet.confirm","pet.forged","system.activity"],b=["solo.progress","solo.agentDelta","solo.agentUsage","solo.agentDiff","solo.evaluation","product.taskStarted","product.taskOutput","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.checkpointed","product.dagTopology","plan.interrupted"],Y=[...C,...b];var X=1,H={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_END:"session/end",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",SESSION_UPDATE:"session/update",SESSION_REQUEST_PERMISSION:"session/request_permission",FS_READ_TEXT_FILE:"fs/read_text_file",FS_WRITE_TEXT_FILE:"fs/write_text_file"},G={ABORT:"x/abort",DREAM:"x/dream",AGENTS_LIST:"x/agents.list",SOLO_START:"x/solo.start",SOLO_STATUS:"x/solo.status",SOLO_SELECT:"x/solo.select",SOLO_CANCEL:"x/solo.cancel",PRODUCT_CREATE:"x/product.create",PRODUCT_PLAN:"x/product.plan",PRODUCT_CONFIRM:"x/product.confirm",PRODUCT_MESSAGE:"x/product.message",PRODUCT_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_STATUS:"x/product.status",SOLO_SUBSCRIBE:"x/solo.subscribe",SOLO_MESSAGE:"x/solo.message",SOLO_EVALUATE:"x/solo.evaluate",PRODUCT_SUBSCRIBE:"x/product.subscribe",TEAM_DELEGATE:"x/team.delegate"},I={AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",USAGE_UPDATE:"usage_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",AVAILABLE_COMMANDS_UPDATE:"available_commands_update"},q={X_SUBAGENT_STARTED:"x_subagent_started",X_SUBAGENT_DELTA:"x_subagent_delta",X_SUBAGENT_ENDED:"x_subagent_ended",X_MEDIA_RESULT:"x_media_result",X_MEDIA_PROGRESS:"x_media_progress",X_SKILL_INSTRUCTION:"x_skill_instruction",X_RECOVERY:"x_recovery",X_SIDECHAIN_STARTED:"x_sidechain_started",X_SIDECHAIN_COMPLETED:"x_sidechain_completed",X_SUGGESTIONS:"x_suggestions",X_ASK_USER:"x_ask_user",X_SESSION_INFO:"x_session_info",X_MEMORY_UPDATED:"x_memory_updated",X_TEAM_MEMBER_UPDATE:"x_team_member_update",X_SOLO_STARTED:"x_solo_started",X_SOLO_AGENT_FINISHED:"x_solo_agent_finished",X_SOLO_SELECTED:"x_solo_selected",X_PRODUCT_TASK_STARTED:"x_product_task_started",X_PRODUCT_TASK_COMPLETED:"x_product_task_completed",X_PRODUCT_CHECKPOINT:"x_product_checkpoint"};function v(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&"id"in t}function M(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function h(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&"id"in t&&!("method"in t)}function z(e){let t;try{t=JSON.parse(e)}catch{return null}return h(t)||v(t)||M(t)?t:null}function J(e){return Object.values(I).includes(e)}function $(e){return e.startsWith("x_")}var f=["gatewayVersion","toolNamespaces","workspaceIds","installedCapabilities","enabledCapabilities","features","approvalMode","toolManifests","skillManifests","pluginManifests","mcpManifests","approvalPolicy","workspaceSummaries"];function d(e){return e?e.map(t=>({...t})):void 0}function A(e){return e?e.map(t=>({...t})):void 0}function Q(e){return e?[...e]:void 0}function k(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort((t,r)=>t.localeCompare(r))}function g(e){return{...e,toolNamespaces:[...e.toolNamespaces],workspaceIds:[...e.workspaceIds],...e.changedSections?{changedSections:[...e.changedSections]}:{},...e.installedCapabilities?{installedCapabilities:[...e.installedCapabilities]}:{},...e.enabledCapabilities?{enabledCapabilities:[...e.enabledCapabilities]}:{},...e.features?{features:[...e.features]}:{},...e.toolManifests?{toolManifests:d(e.toolManifests)}:{},...e.skillManifests?{skillManifests:d(e.skillManifests)}:{},...e.pluginManifests?{pluginManifests:d(e.pluginManifests)}:{},...e.mcpManifests?{mcpManifests:d(e.mcpManifests)}:{},...e.approvalPolicy?{approvalPolicy:{...e.approvalPolicy}}:{},...e.workspaceSummaries?{workspaceSummaries:A(e.workspaceSummaries)}:{}}}function Z(e){let{previous:t,update:r}=e;return!(r.syncMode==="diff"&&t&&(!r.baseSnapshotVersion||t.snapshotVersion===r.baseSnapshotVersion))||!t?g(r):{...g(t),snapshotVersion:r.snapshotVersion,updatedAt:r.updatedAt,...r.gatewayVersion!==void 0?{gatewayVersion:r.gatewayVersion}:{},...r.syncMode?{syncMode:r.syncMode}:{},...r.baseSnapshotVersion?{baseSnapshotVersion:r.baseSnapshotVersion}:{},...r.changedSections?{changedSections:[...r.changedSections]}:{},...r.toolNamespaces?{toolNamespaces:[...r.toolNamespaces]}:{},...r.workspaceIds?{workspaceIds:[...r.workspaceIds]}:{},...r.installedCapabilities?{installedCapabilities:[...r.installedCapabilities]}:{},...r.enabledCapabilities?{enabledCapabilities:[...r.enabledCapabilities]}:{},...r.features?{features:[...r.features]}:{},...r.approvalMode?{approvalMode:r.approvalMode}:{},...r.toolManifests?{toolManifests:d(r.toolManifests)}:{},...r.skillManifests?{skillManifests:d(r.skillManifests)}:{},...r.pluginManifests?{pluginManifests:d(r.pluginManifests)}:{},...r.mcpManifests?{mcpManifests:d(r.mcpManifests)}:{},...r.approvalPolicy?{approvalPolicy:{...r.approvalPolicy}}:{},...r.workspaceSummaries?{workspaceSummaries:A(r.workspaceSummaries)}:{}}}function ee(e){return k(e.map(t=>t.name.split(".")[0]??"").filter(Boolean))}function te(e){return k(e.map(t=>t.id))}function re(e){let{previous:t,current:r}=e;if(!t)return{...g(r),syncMode:"full"};if(t.snapshotVersion===r.snapshotVersion)return null;let i=f.filter(n=>JSON.stringify(t[n])!==JSON.stringify(r[n]));if(i.length===f.length)return{...g(r),syncMode:"full"};let u={snapshotVersion:r.snapshotVersion,updatedAt:r.updatedAt,syncMode:"diff",baseSnapshotVersion:t.snapshotVersion,changedSections:i,toolNamespaces:[...r.toolNamespaces],workspaceIds:[...r.workspaceIds]},p=u;for(let n of i){let o=r[n];if(o!==void 0)switch(n){case"toolNamespaces":case"workspaceIds":case"installedCapabilities":case"enabledCapabilities":case"features":p[n]=Q(o);break;case"approvalPolicy":p[n]={...o};break;case"workspaceSummaries":p[n]=A(o);break;case"toolManifests":case"skillManifests":case"pluginManifests":case"mcpManifests":p[n]=d(o);break;default:p[n]=o;break}}return u}var oe=["web_search","web_fetch","deep_research","browser_execution"],ie=["web-intelligence","browser-execution"],ne=["discovery","read-url","multi-source-research","interactive-browser"],se=["stateless","render-backend","interactive-session"],ae=["stateless","stateless-single-step","stateful-session-required"],pe=["required","conditional","none"],ce=["browser-read","browser-authenticated-read","browser-state-changing"],le=["read-page","read-authenticated-page","fill-form","submit-form","download-file","reuse-session"],de=["web_search","web_fetch","deep_research","blocked"],ue=["requires-interaction","requires-login-state","requires-rendered-dom","requires-persistent-session","requires-state-changing-action"],ge=["none","same-capability-once","degrade-only"];var ye=["prefetch","sync_turn","on_pre_compress","on_session_end","on_delegation","on_memory_write"],me=["turn","sidechain","compress","session-end","agent-remember","auto-extract","implicit-extract","profile-extraction","dream"],fe=["observe-only","parent-write","deny"];var Ae=2,s={gatewayImage:"gateway.image.desktop-slim",whisperModelTiny:"speech.whisper.model.tiny",ffmpegWin32X64:"runtime.ffmpeg.win32-x64",nodeWin32X64:"runtime.node.win32-x64",dockerDesktopWin32X64:"runtime.docker-desktop.win32-x64",dockerDesktopDarwinX64:"runtime.docker-desktop.darwin-x64",dockerDesktopDarwinArm64:"runtime.docker-desktop.darwin-arm64"},y={desktopDockerBridge:"desktop.docker-bridge",desktopEmbeddedWin32X64:"desktop.embedded.win32-x64"};function O(e){return{...e,artifacts:e.artifacts.map(t=>({...t}))}}function Re(e){return{...e,assetIds:[...e.assetIds]}}function N(){return{[y.desktopDockerBridge]:{id:y.desktopDockerBridge,title:"Desktop Docker Bridge",platform:"any",assetIds:[s.gatewayImage,s.dockerDesktopWin32X64,s.dockerDesktopDarwinX64,s.dockerDesktopDarwinArm64],description:"Docker bridge mode downloads the desktop slim gateway image on demand."},[y.desktopEmbeddedWin32X64]:{id:y.desktopEmbeddedWin32X64,title:"Desktop Embedded Win32 x64",platform:"win32-x64",assetIds:[s.nodeWin32X64,s.ffmpegWin32X64,s.whisperModelTiny],description:"Embedded desktop mode requires the bundled Node/FFmpeg runtimes and the whisper model asset."}}}function D(e,t){return e.assets[t]}function w(e,t){return e.profiles[t]}function Ee(e,t){let r=w(e,t);return r?r.assetIds.map(i=>D(e,i)).filter(i=>!!i):[]}function Se(e,t){return e.assets[t.id]=O(t),U(e)}function R(e){if(!e)return;let t=e.artifacts[0];if(!(!t?.url||!t.sha256||typeof t.size!="number"))return{version:e.version,sha256:t.sha256,size:t.size,url:t.url}}function U(e){let t=R(e.assets[s.gatewayImage]),r=R(e.assets[s.whisperModelTiny]);return{...e,gateway:t,whisperModel:r}}function x(e,t){if(!(typeof e.version!="string"||typeof e.url!="string"))return{...t,version:e.version,artifacts:[{fileName:e.url.split("/").pop()||`${t.id}.bin`,url:e.url,sha256:typeof e.sha256=="string"?e.sha256:void 0,size:typeof e.size=="number"?e.size:void 0}]}}function _e(e){let t=e&&typeof e=="object"?e:{},r={},i=t.assets&&typeof t.assets=="object"?t.assets:{};for(let[o,a]of Object.entries(i)){if(!a||typeof a!="object")continue;let l=a;!l.id||!Array.isArray(l.artifacts)||(r[o]=O(l))}if(!r[s.gatewayImage]&&t.gateway&&typeof t.gateway=="object"){let o=x(t.gateway,{id:s.gatewayImage,title:"OpenClaw Gateway Image (Desktop Slim)",kind:"container-image",delivery:"remote",platform:"any",description:"Desktop Docker mode gateway image."});o&&(r[o.id]=o)}if(!r[s.whisperModelTiny]&&t.whisperModel&&typeof t.whisperModel=="object"){let o=x(t.whisperModel,{id:s.whisperModelTiny,title:"Whisper Tiny Model",kind:"model",delivery:"remote",platform:"any",description:"Shared whisper.cpp tiny model asset for embedded desktop speech recognition."});o&&(r[o.id]=o)}let p={...N()},n=t.profiles&&typeof t.profiles=="object"?t.profiles:{};for(let[o,a]of Object.entries(n)){if(!a||typeof a!="object")continue;let l=a;!l.id||!Array.isArray(l.assetIds)||(p[o]=Re(l))}return U({schemaVersion:typeof t.schemaVersion=="number"?t.schemaVersion:2,channel:typeof t.channel=="string"?t.channel:void 0,publishedAt:typeof t.publishedAt=="string"?t.publishedAt:void 0,minElectronVersion:typeof t.minElectronVersion=="string"?t.minElectronVersion:void 0,releaseNotes:typeof t.releaseNotes=="string"?t.releaseNotes:void 0,assets:r,profiles:p})}var Pe=["pending","captured","failed","restored"],Te=["file","directory","missing"],Ce=["metadata-only","workspace-copy","shadow-git"];var be=["api-key","oauth","token","aws-sdk"],Ie=["rate_limit","auth","server_error","timeout","network","unknown"],ve=["requiresOpenAiAnthropicToolPayload"];function Me(e,t){return!e||typeof e!="object"||Array.isArray(e)?!1:e[t]===!0}var L="openai-codex";function m(e){let t=e.trim().toLowerCase();return t==="z.ai"||t==="z-ai"?"zai":t==="opencode-zen"?"opencode":t==="kimi-code"?"kimi-coding":t==="bedrock"||t==="aws-bedrock"?"amazon-bedrock":t==="bytedance"||t==="doubao"?"volcengine":t}function K(e){let t=m(e);return t==="volcengine-plan"?"volcengine":t==="byteplus-plan"?"byteplus":t}var he=K,ke={anthropicToolSchemaMode:"native",anthropicToolChoiceMode:"native",providerFamily:"default",preserveAnthropicThinkingSignatures:!0,openAiCompatTurnValidation:!0,providerThoughtSignatureSanitization:!1,transcriptToolCallIdMode:"default",transcriptToolCallIdModelHints:[],providerThoughtSignatureModelHints:[],dropThinkingBlockModelHints:[]},xe={anthropic:{providerFamily:"anthropic"},"amazon-bedrock":{providerFamily:"anthropic"},"kimi-coding":{anthropicToolSchemaMode:"openai-functions",anthropicToolChoiceMode:"openai-string-modes",preserveAnthropicThinkingSignatures:!1},mistral:{transcriptToolCallIdMode:"strict9",transcriptToolCallIdModelHints:["mistral","mixtral","codestral","pixtral","devstral","ministral","mistralai"]},openai:{providerFamily:"openai"},[L]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};function E(e,t){let r=(e??"").toLowerCase();return!!r&&t.some(i=>r.includes(i))}function c(e){let t=m(e??"");return{...ke,...xe[t]}}function Oe(e){return c(e).preserveAnthropicThinkingSignatures}function Ne(e){let t=c(e);return t.anthropicToolSchemaMode!=="native"||t.anthropicToolChoiceMode!=="native"}function De(e){return c(e).anthropicToolSchemaMode==="openai-functions"}function we(e){return c(e).anthropicToolChoiceMode==="openai-string-modes"}function Ue(e){return c(e).openAiCompatTurnValidation}function Le(e){return c(e).providerFamily==="openai"}function Ke(e){return c(e).providerFamily==="anthropic"}function Ve(e){return E(e.modelId,c(e.provider).dropThinkingBlockModelHints)}function We(e){let t=c(e.provider);return t.providerThoughtSignatureSanitization&&E(e.modelId,t.providerThoughtSignatureModelHints)}function Fe(e,t){let r=c(e),i=r.transcriptToolCallIdMode;if(i==="strict9")return i;if(E(t,r.transcriptToolCallIdModelHints))return"strict9"}var S={anthropic:["ANTHROPIC_OAUTH_TOKEN","ANTHROPIC_API_KEY"],chutes:["CHUTES_OAUTH_TOKEN","CHUTES_API_KEY"],zai:["ZAI_API_KEY","Z_AI_API_KEY"],opencode:["OPENCODE_API_KEY","OPENCODE_ZEN_API_KEY"],volcengine:["VOLCANO_ENGINE_API_KEY"],"volcengine-plan":["VOLCANO_ENGINE_API_KEY"],byteplus:["BYTEPLUS_API_KEY"],"byteplus-plan":["BYTEPLUS_API_KEY"],"kimi-coding":["KIMI_API_KEY","KIMICODE_API_KEY"],huggingface:["HUGGINGFACE_HUB_TOKEN","HF_TOKEN"],openai:["OPENAI_API_KEY"],voyage:["VOYAGE_API_KEY"],groq:["GROQ_API_KEY"],deepgram:["DEEPGRAM_API_KEY"],cerebras:["CEREBRAS_API_KEY"],xai:["XAI_API_KEY"],openrouter:["OPENROUTER_API_KEY"],litellm:["LITELLM_API_KEY"],"vercel-ai-gateway":["AI_GATEWAY_API_KEY"],"cloudflare-ai-gateway":["CLOUDFLARE_AI_GATEWAY_API_KEY"],moonshot:["MOONSHOT_API_KEY"],minimax:["MINIMAX_API_KEY"],"minimax-cn":["MINIMAX_CN_API_KEY","MINIMAX_API_KEY"],nvidia:["NVIDIA_API_KEY"],xiaomi:["XIAOMI_API_KEY"],synthetic:["SYNTHETIC_API_KEY"],venice:["VENICE_API_KEY"],mistral:["MISTRAL_API_KEY"],together:["TOGETHER_API_KEY"],qianfan:["QIANFAN_API_KEY"],ollama:["OLLAMA_API_KEY"],vllm:["VLLM_API_KEY"],kilocode:["KILOCODE_API_KEY"]};function Be(){return[...new Set(Object.values(S).flat())]}function je(e){let t=m(e.provider),r=e.env??process.env,i=new Set(e.appliedEnvKeys??[]),u=o=>{let a=r[o]?.trim();if(!a)return null;let l=i.has(o)?`shell env: ${o}`:`env: ${o}`;return{apiKey:a,source:l}},p=e.resolveSpecialApiKey?.(t,r,i);if(p)return p;let n=S[t];if(!n||n.length===0)return null;for(let o of n){let a=u(o);if(a)return a}return null}export{G as ACP_EXTENDED_METHODS,q as ACP_EXTENDED_SESSION_UPDATE_TYPES,H as ACP_METHODS,X as ACP_PROTOCOL_VERSION,I as ACP_SESSION_UPDATE_TYPES,F as AGENT_RPC_APPROVAL_METHODS,W as AGENT_RPC_ERROR_CODES,V as AGENT_RPC_PROTOCOL_VERSION,b as AGENT_TEAM_WS_EVENT_NAMES,C as AGENT_WS_EVENT_NAMES,Y as ALL_AGENT_WS_EVENT_NAMES,f as CAPABILITY_MANIFEST_DIFF_SECTIONS,j as GATEWAY_RPC_METHODS,ye as MEMORY_OBSERVATION_HOOK_VALUES,me as MEMORY_OBSERVATION_SOURCE_VALUES,fe as MEMORY_WRITE_ACCESS_VALUES,Ce as MUTATION_CHECKPOINT_BACKEND_VALUES,Te as MUTATION_CHECKPOINT_ENTRY_KIND_VALUES,Pe as MUTATION_CHECKPOINT_PHASE_VALUES,be as PROVIDER_RUNTIME_AUTH_MODE_VALUES,ve as PROVIDER_RUNTIME_COMPAT_FLAG_VALUES,S as PROVIDER_RUNTIME_ENV_API_KEY_CANDIDATES,L as PROVIDER_RUNTIME_OPENAI_CODEX_PROVIDER_ID,Ie as PROVIDER_RUNTIME_VAULT_ERROR_TYPE_VALUES,Ae as RESOURCE_MANIFEST_SCHEMA_VERSION,s as RUNTIME_ASSET_IDS,y as RUNTIME_PROFILE_IDS,le as WEB_ACTION_SCOPE_VALUES,pe as WEB_APPROVAL_DEFAULT_VALUES,ie as WEB_CAPABILITY_FAMILY_VALUES,oe as WEB_CAPABILITY_ID_VALUES,de as WEB_DEGRADATION_TARGET_VALUES,ue as WEB_ESCALATION_REASON_VALUES,se as WEB_EXECUTION_MODE_VALUES,ce as WEB_POLICY_RISK_CLASS_VALUES,ge as WEB_RETRY_POLICY_VALUES,ae as WEB_STATEFULNESS_VALUES,ne as WEB_TASK_MODE_VALUES,g as cloneCapabilityManifestSnapshot,re as createCapabilityManifestDiffPayload,N as createDefaultRuntimeResourceProfiles,ee as deriveCapabilityToolNamespaces,te as deriveCapabilityWorkspaceIds,R as getManifestShortcutEntry,D as getRuntimeResourceAsset,w as getRuntimeResourceProfile,Ee as getRuntimeResourceProfileAssets,M as isAcpJsonRpcNotification,v as isAcpJsonRpcRequest,h as isAcpJsonRpcResponse,T as isAgentRpcNotification,_ as isAgentRpcRequest,P as isAgentRpcResponse,Ke as isAnthropicProviderRuntimeFamily,$ as isExtendedSessionUpdateType,Le as isOpenAiProviderRuntimeFamily,J as isStandardSessionUpdateType,Be as listProviderRuntimeEnvApiKeyNames,Z as mergeCapabilityManifestSnapshot,m as normalizeProviderRuntimeId,K as normalizeProviderRuntimeIdForAuth,_e as normalizeRuntimeResourceManifest,z as parseAcpMessage,B as parseAgentRpcMessage,Oe as preservesProviderRuntimeAnthropicThinkingSignatures,Me as readProviderRuntimeCompatFlag,Ne as requiresOpenAiCompatibleAnthropicToolPayloadForProviderRuntime,c as resolveProviderRuntimeCapabilities,je as resolveProviderRuntimeEnvApiKey,he as resolveProviderRuntimeKeyFamily,Fe as resolveProviderRuntimeTranscriptToolCallIdMode,Ve as shouldDropThinkingBlocksForProviderRuntimeModel,We as shouldSanitizeProviderRuntimeThoughtSignaturesForModel,Ue as supportsOpenAiCompatTurnValidationForProviderRuntime,Se as upsertRuntimeResourceAsset,De as usesOpenAiFunctionAnthropicToolSchemaForProviderRuntime,we as usesOpenAiStringModeAnthropicToolChoiceForProviderRuntime};
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* Zero imports from express/pg/ioredis/ws.
|
|
14
14
|
*/
|
|
15
15
|
import type { AgentLogger, ToolInvoker, TurnEvent, TurnRequest, HookRegistry } from "./types.js";
|
|
16
|
-
import type { LLMTransport } from "
|
|
16
|
+
import type { LLMTransport } from "@qlogic/provider-core";
|
|
17
17
|
export interface AgentConfig {
|
|
18
18
|
llmTransport: LLMTransport;
|
|
19
19
|
apiKey: string;
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
* Zero imports from express/pg/ioredis/ws.
|
|
20
20
|
*/
|
|
21
21
|
import type { AgentLogger, ChatMessage, ToolDefinition, ToolInvoker, TurnEvent, HookRegistry } from "./types.js";
|
|
22
|
-
import type { LLMTransport } from "
|
|
22
|
+
import type { LLMTransport } from "@qlogic/provider-core";
|
|
23
23
|
export interface ToolLoopParams {
|
|
24
24
|
turnId: string;
|
|
25
25
|
sessionId: string;
|
|
@@ -118,6 +118,10 @@ export declare const MAX_SESSIONS = 50;
|
|
|
118
118
|
export declare const TASK_SUMMARY_TURN_THRESHOLD = 50;
|
|
119
119
|
/** Interval (turns) between summary regeneration. */
|
|
120
120
|
export declare const TASK_SUMMARY_REGEN_INTERVAL = 30;
|
|
121
|
+
/** Idle duration (ms) before a group session is auto-split into a new session. Default: 1 hour. */
|
|
122
|
+
export declare const GROUP_SESSION_IDLE_THRESHOLD_MS: number;
|
|
123
|
+
/** Hard limit: max turns in a single group session before soft-split. Default: 200 turns. */
|
|
124
|
+
export declare const GROUP_SESSION_MAX_TURNS = 200;
|
|
121
125
|
/** Max include nesting depth in instruction files. */
|
|
122
126
|
export declare const MAX_INCLUDE_DEPTH = 5;
|
|
123
127
|
/** Max total chars loaded from instruction files. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Pure agent
|
|
2
|
+
* Pure agent typeszero I/O framework dependencies.
|
|
3
3
|
*
|
|
4
4
|
* Wire-level types (ChatMessage, ToolDefinition) are canonical in
|
|
5
5
|
* protocol/wire/. This file re-exports them and adds
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import type { SkillInstruction } from "../orchestration/index.js";
|
|
9
9
|
import type { HookRegistry } from "../contracts/hooks.js";
|
|
10
|
-
import type { MediaCapability } from "
|
|
10
|
+
import type { MediaCapability } from "@qlogic/provider-core";
|
|
11
11
|
import type { ChatMessage as WireChatMessage, ChatMessageRole as WireChatMessageRole, ThinkingBlock as WireThinkingBlock, ToolCallMessage as WireToolCallMessage, ToolDefinition as WireToolDefinition, WireTokenUsage } from "../protocol/wire/index.js";
|
|
12
12
|
export type ChatMessageRole = WireChatMessageRole;
|
|
13
13
|
export type ThinkingBlock = WireThinkingBlock;
|
|
@@ -18,18 +18,18 @@ export interface ToolDefinition extends WireToolDefinition {
|
|
|
18
18
|
* Backfill derived/legacy fields onto a shallow copy of the tool input
|
|
19
19
|
* before hooks and observers see it (CC backfillObservableInput parity).
|
|
20
20
|
* The original API-bound input is never modified.
|
|
21
|
-
* Internal-
|
|
21
|
+
* Internal-onlynever serialized over JSON-RPC.
|
|
22
22
|
*/
|
|
23
23
|
backfillObservableInput?: (input: Record<string, unknown>) => void;
|
|
24
24
|
}
|
|
25
25
|
/**
|
|
26
|
-
* Token
|
|
26
|
+
* Token usageunified with WireTokenUsage from contracts.
|
|
27
27
|
* No more internal/wire split: all code uses the same field names
|
|
28
28
|
* (inputTokens, outputTokens, reasoningTokens, cacheRead, cacheWrite).
|
|
29
29
|
*/
|
|
30
30
|
export type TokenUsage = WireTokenUsage;
|
|
31
31
|
/**
|
|
32
|
-
* Why the previous iteration
|
|
32
|
+
* Why the previous iteration continuedeach variant corresponds to one of
|
|
33
33
|
* the 7 `continue` sites in the main while(true) loop.
|
|
34
34
|
* Tests can assert recovery paths fired without inspecting message contents.
|
|
35
35
|
*/
|
|
@@ -110,20 +110,9 @@ export interface TurnConfig {
|
|
|
110
110
|
fallbackModel?: string;
|
|
111
111
|
/** Max turns (tool loop iterations). 0 or undefined = use maxRounds. */
|
|
112
112
|
maxTurns?: number;
|
|
113
|
-
/** Model for generating tool use summaries (CC parity: Haiku). If set, enables summary generation. */
|
|
114
|
-
summaryModel?: string;
|
|
115
|
-
/** Cheap model for background tasks: implicit extraction, dream consolidation. */
|
|
116
|
-
backgroundModel?: string;
|
|
117
|
-
/** Embedding model config for semantic memory. Omit to use default ONNX or FTS-only. */
|
|
118
|
-
embeddingModel?: {
|
|
119
|
-
provider?: string;
|
|
120
|
-
model?: string;
|
|
121
|
-
apiKey?: string;
|
|
122
|
-
baseUrl?: string;
|
|
123
|
-
};
|
|
124
113
|
/** Max concurrent tool executions (0 = unlimited). */
|
|
125
114
|
maxConcurrentTools?: number;
|
|
126
|
-
/** Model requires
|
|
115
|
+
/** Model requires streamingdisable non-streaming fallback. */
|
|
127
116
|
streamRequired?: boolean;
|
|
128
117
|
/** Reasoning effort for models that support it (GPT-5.x, o-series). */
|
|
129
118
|
reasoning?: {
|
|
@@ -150,7 +139,7 @@ export interface TurnConfig {
|
|
|
150
139
|
/**
|
|
151
140
|
* User-designated provider+model per media category.
|
|
152
141
|
* Each entry maps a media type (image/video/music/tts/3d/...) to
|
|
153
|
-
* the specific provider and model the user chose. No failover
|
|
142
|
+
* the specific provider and model the user chose. No failover
|
|
154
143
|
* if the designated provider fails, the error propagates directly.
|
|
155
144
|
*/
|
|
156
145
|
mediaProviders?: Partial<Record<MediaCapability, {
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agents scan/config/gateway/processes/kill handlers — extracted from StdioServer.
|
|
3
|
+
* Handles: agents.scan, agents.list, agents.config, agents.setConfig, agents.getConfig,
|
|
4
|
+
* agents.removeConfig, agents.setGateway, agents.getGateway, agents.processes,
|
|
5
|
+
* agents.kill, agents.listConfigured, agents.getLog, agents.testConnection
|
|
6
|
+
*/
|
|
7
|
+
export declare function handleAgentsScan(this: any, msg: any): Promise<void>;
|
|
8
|
+
export declare function handleAgentsList(this: any, msg: any): Promise<void>;
|
|
9
|
+
export declare function handleAgentsConfig(this: any, msg: any): Promise<void>;
|
|
10
|
+
export declare function handleAgentsSetConfig(this: any, msg: any): Promise<void>;
|
|
11
|
+
export declare function handleAgentsGetConfig(this: any, msg: any): Promise<void>;
|
|
12
|
+
export declare function handleAgentsRemoveConfig(this: any, msg: any): Promise<void>;
|
|
13
|
+
export declare function handleAgentsSetGateway(this: any, msg: any): Promise<void>;
|
|
14
|
+
export declare function handleAgentsGetGateway(this: any, msg: any): Promise<void>;
|
|
15
|
+
export declare function handleAgentsListConfigured(this: any, msg: any): Promise<void>;
|
|
16
|
+
export declare function handleAgentsProcesses(this: any, msg: any): void;
|
|
17
|
+
export declare function handleAgentsKill(this: any, msg: any): void;
|
|
18
|
+
export declare function handleAgentsGetLog(this: any, msg: any): Promise<void>;
|
|
19
|
+
export declare function handleAgentsTestConnection(this: any, msg: any): Promise<void>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Config + tunables handlers — extracted from StdioServer.
|
|
3
|
+
* Handles: config.get, config.update, config.tunables, config.updateTunable,
|
|
4
|
+
* provider.list, tools.list, todos.list, tasks.list, tasks.cancel
|
|
5
|
+
*
|
|
6
|
+
* NOTE: Provider/model/key management is handled by settings-handler.ts (settings.* RPC).
|
|
7
|
+
* config.get/config.update only operate on tunables and non-model settings.
|
|
8
|
+
*/
|
|
9
|
+
export declare function handleToolsList(this: any, msg: any): void;
|
|
10
|
+
export declare function handleProviderList(this: any, msg: any): void;
|
|
11
|
+
export declare function handleConfigGet(this: any, msg: any): void;
|
|
12
|
+
export declare function handleConfigUpdate(this: any, msg: any): Promise<void>;
|
|
13
|
+
export declare function handleConfigTunables(this: any, msg: any): void;
|
|
14
|
+
export declare function handleConfigUpdateTunable(this: any, msg: any): Promise<void>;
|
|
15
|
+
export declare function handleTodosList(this: any, msg: any): Promise<void>;
|
|
16
|
+
export declare function handleTasksList(this: any, msg: any): void;
|
|
17
|
+
export declare function handleTasksCancel(this: any, msg: any): void;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Files + Instructions handlers — extracted from StdioServer.
|
|
3
|
+
* Handles: files.list, files.create, files.rename, files.delete, files.gitStatus,
|
|
4
|
+
* instructions.list, instructions.read, instructions.write, instructions.delete
|
|
5
|
+
*/
|
|
6
|
+
export declare function resolveProjectDir(projectId: string): string | null;
|
|
7
|
+
export declare function handleFilesList(this: any, msg: any): Promise<void>;
|
|
8
|
+
export declare function handleFilesCreate(this: any, msg: any): Promise<void>;
|
|
9
|
+
export declare function handleFilesRename(this: any, msg: any): Promise<void>;
|
|
10
|
+
export declare function handleFilesDelete(this: any, msg: any): Promise<void>;
|
|
11
|
+
export declare function handleFilesGitStatus(this: any, msg: any): Promise<void>;
|
|
12
|
+
export declare function handleInstructionsList(this: any, msg: any): void;
|
|
13
|
+
export declare function handleInstructionsRead(this: any, msg: any): void;
|
|
14
|
+
export declare function handleInstructionsWrite(this: any, msg: any): void;
|
|
15
|
+
export declare function handleInstructionsDelete(this: any, msg: any): void;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Media handlers — extracted from StdioServer.
|
|
3
|
+
* Handles: media.listModels, media.cancel, media.status, media.stt
|
|
4
|
+
*/
|
|
5
|
+
export declare function handleMediaListModels(this: any, msg: any): Promise<void>;
|
|
6
|
+
export declare function handleMediaCancel(this: any, msg: any): Promise<void>;
|
|
7
|
+
export declare function handleMediaStatus(this: any, msg: any): Promise<void>;
|
|
8
|
+
/**
|
|
9
|
+
* `media.stt` — Speech-to-text transcription.
|
|
10
|
+
* Accepts base64-encoded audio, calls the designated STT provider (zhipu GLM-ASR-2512).
|
|
11
|
+
* This is a non-session utility: no turn/session is created.
|
|
12
|
+
*/
|
|
13
|
+
export declare function handleMediaStt(this: any, msg: any): Promise<void>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory CRUD + search handlers — extracted from StdioServer.
|
|
3
|
+
* Handles: memory.list, memory.read, memory.write, memory.search, memory.delete
|
|
4
|
+
*/
|
|
5
|
+
export declare function handleMemoryList(this: any, msg: any): Promise<void>;
|
|
6
|
+
/** memory.list-files — Returns actual topic files from memdir. */
|
|
7
|
+
export declare function handleMemoryListFiles(this: any, msg: any): Promise<void>;
|
|
8
|
+
/**
|
|
9
|
+
* memory.atlas — Returns full L2 vector-memory records (wire-safe, no embedding
|
|
10
|
+
* blob) plus category roll-ups, for the 3D memory atlas visualization.
|
|
11
|
+
*/
|
|
12
|
+
export declare function handleMemoryAtlas(this: any, msg: any): Promise<void>;
|
|
13
|
+
/**
|
|
14
|
+
* memory.activity — Daily activity counts + highlights over the recent window,
|
|
15
|
+
* powering the atlas timeline ticks and the "memory digest" panel.
|
|
16
|
+
*/
|
|
17
|
+
export declare function handleMemoryActivity(this: any, msg: any): Promise<void>;
|
|
18
|
+
export declare function handleMemoryRead(this: any, msg: any): Promise<void>;
|
|
19
|
+
export declare function handleMemoryWrite(this: any, msg: any): Promise<void>;
|
|
20
|
+
export declare function handleMemorySearch(this: any, msg: any): Promise<void>;
|
|
21
|
+
export declare function handleMemoryDelete(this: any, msg: any): Promise<void>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pet Handler — RPC methods for pet system.
|
|
3
|
+
*
|
|
4
|
+
* Methods:
|
|
5
|
+
* - pet.hatch: Hatch a new pet (first time) or return existing soul
|
|
6
|
+
* - pet.interact: Handle user interaction (pat/feed/poke)
|
|
7
|
+
* - pet.status: Get current pet soul + stats
|
|
8
|
+
* - pet.forge: Generate a custom .pet file from image/text (P4)
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Mixin: call with `this` bound to the TurnHandler (StdioServer) instance.
|
|
12
|
+
* Assumes `this.sendNotification(method, params)` and `this.sendResponse(id, result)` exist.
|
|
13
|
+
*/
|
|
14
|
+
export declare function handlePetHatch(this: any, msg: any): Promise<void>;
|
|
15
|
+
export declare function handlePetInteract(this: any, msg: any): Promise<void>;
|
|
16
|
+
export declare function handlePetStatus(this: any, msg: any): Promise<void>;
|
|
17
|
+
/**
|
|
18
|
+
* P4: Pet Forge — generate a custom .pet file from image/text description.
|
|
19
|
+
*
|
|
20
|
+
* Pipeline (design §14.3 Plan A + §14.4):
|
|
21
|
+
* 1. Analyze image (if provided) → character description
|
|
22
|
+
* 2. Generate ONE base skeleton SVG (with labeled parts)
|
|
23
|
+
* 3. Validate skeleton structure (required IDs/classes)
|
|
24
|
+
* 4. For each state: renderState() injects CSS animations + effects
|
|
25
|
+
* 5. Structural consistency check; retry skeleton if score too low
|
|
26
|
+
* 6. Package and emit pet.forged
|
|
27
|
+
*/
|
|
28
|
+
export declare function handlePetForge(this: any, msg: any): Promise<void>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Product mode handlers — extracted from StdioServer.
|
|
3
|
+
* Handles: product.plan/confirm/message/create/resume/pause/checkpoint/status/list/delete/cancel/rollback
|
|
4
|
+
*/
|
|
5
|
+
import { ProductOrchestrator } from "../../orchestration/agent-instance.js";
|
|
6
|
+
import { ProductPlanner } from "../../orchestration/product-planner.js";
|
|
7
|
+
export declare function ensureProductOrchestrator(this: any): ProductOrchestrator;
|
|
8
|
+
/** Ensure ProductPlanner is initialized. */
|
|
9
|
+
export declare function ensureProductPlanner(this: any): ProductPlanner;
|
|
10
|
+
/** `product.plan` — Start interactive planning with leader agent. */
|
|
11
|
+
export declare function handleProductPlan(this: any, msg: AgentRpcRequest): Promise<void>;
|
|
12
|
+
/** `product.confirm` — User confirms the plan, transition to execution. */
|
|
13
|
+
export declare function handleProductConfirm(this: any, msg: AgentRpcRequest): Promise<void>;
|
|
14
|
+
/** `product.message` — User sends message to leader (multi-turn planning or execution intervention). */
|
|
15
|
+
export declare function handleProductMessage(this: any, msg: AgentRpcRequest): Promise<void>;
|
|
16
|
+
/** `product.create` — Create a new Product Mode session. */
|
|
17
|
+
export declare function handleProductCreate(this: any, msg: AgentRpcRequest): Promise<void>;
|
|
18
|
+
/** `product.resume` — Resume a paused product. */
|
|
19
|
+
export declare function handleProductResume(this: any, msg: AgentRpcRequest): Promise<void>;
|
|
20
|
+
/** `product.pause` — Pause a running product. */
|
|
21
|
+
export declare function handleProductPause(this: any, msg: AgentRpcRequest): Promise<void>;
|
|
22
|
+
/** `product.checkpoint` — Manual checkpoint. */
|
|
23
|
+
export declare function handleProductCheckpoint(this: any, msg: AgentRpcRequest): Promise<void>;
|
|
24
|
+
/** `product.status` — Query product status. */
|
|
25
|
+
export declare function handleProductStatus(this: any, msg: AgentRpcRequest): Promise<void>;
|
|
26
|
+
/** `product.list` — List all products. */
|
|
27
|
+
export declare function handleProductList(this: any, msg: AgentRpcRequest): Promise<void>;
|
|
28
|
+
export declare function handleProductDelete(this: any, msg: AgentRpcRequest): Promise<void>;
|
|
29
|
+
/** `product.cancel` — Cancel a running product. */
|
|
30
|
+
export declare function handleProductCancel(this: any, msg: AgentRpcRequest): Promise<void>;
|
|
31
|
+
/** `product.rollback` — Rollback a product to a checkpoint. */
|
|
32
|
+
export declare function handleProductRollback(this: any, msg: AgentRpcRequest): Promise<void>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Project CRUD handlers — extracted from StdioServer.
|
|
3
|
+
* Handles: project.create, project.list, project.delete, project.rename,
|
|
4
|
+
* project.archive, project.unarchive, project.archiveByGroup
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Copy global template files (~/.qlogicagent/INSTRUCTIONS.md + rules/) into a new project's
|
|
8
|
+
* .qlogicagent/ directory. Only copies if the target does NOT already exist.
|
|
9
|
+
*/
|
|
10
|
+
export declare function seedProjectFromGlobalTemplates(workspaceDir: string): void;
|
|
11
|
+
export declare function handleProjectCreate(this: any, msg: any): void;
|
|
12
|
+
export declare function handleProjectList(this: any, msg: any): void;
|
|
13
|
+
export declare function handleProjectDelete(this: any, msg: any): void;
|
|
14
|
+
export declare function handleProjectPurgeAll(this: any, msg: any): void;
|
|
15
|
+
export declare function handleProjectRename(this: any, msg: any): void;
|
|
16
|
+
export declare function handleProjectArchive(this: any, msg: any): void;
|
|
17
|
+
export declare function handleProjectUnarchive(this: any, msg: any): void;
|
|
18
|
+
export declare function handleProjectArchiveByGroup(this: any, msg: any): void;
|
|
19
|
+
export declare function handleProjectUpdate(this: any, msg: any): void;
|