qlogicagent 2.0.0 → 2.2.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/README.md +8 -8
- package/dist/agent.js +8 -8
- package/dist/cli.js +250 -203
- package/dist/contracts.js +1 -1
- package/dist/index.js +249 -202
- package/dist/orchestration.js +6 -6
- package/dist/types/agent/types.d.ts +3 -1
- package/dist/types/cli/stdio-server.d.ts +27 -8
- package/dist/types/cli/tool-bootstrap.d.ts +8 -0
- package/dist/types/contracts/hooks.d.ts +3 -0
- package/dist/types/contracts/index.d.ts +0 -1
- package/dist/types/contracts/todo.d.ts +8 -21
- package/dist/types/llm/adapters/aliyun-oss-file-upload-adapter.d.ts +44 -0
- package/dist/types/llm/adapters/gemini-file-upload-adapter.d.ts +26 -0
- package/dist/types/llm/adapters/hub-oss-file-upload-adapter.d.ts +29 -0
- package/dist/types/llm/adapters/index.d.ts +10 -0
- package/dist/types/llm/adapters/openai-file-upload-adapter.d.ts +38 -0
- package/dist/types/llm/adapters/volcengine-file-upload-adapter.d.ts +24 -0
- package/dist/types/llm/file-upload-service.d.ts +68 -0
- package/dist/types/llm/transports/anthropic-messages.d.ts +4 -0
- package/dist/types/llm/transports/gemini-generatecontent.d.ts +4 -0
- package/dist/types/llm/transports/media-resolve.d.ts +50 -0
- package/dist/types/llm/transports/openai-chat.d.ts +4 -0
- package/dist/types/llm/transports/openai-responses.d.ts +3 -0
- package/dist/types/llm/transports/volcengine-responses.d.ts +4 -0
- package/dist/types/orchestration/tool-loop/tool-schema.d.ts +1 -0
- package/dist/types/protocol/methods.d.ts +70 -0
- package/dist/types/protocol/notifications.d.ts +42 -0
- package/dist/types/runtime/execution/dream-agent.d.ts +2 -0
- package/dist/types/runtime/execution/dream-category-context.d.ts +47 -0
- package/dist/types/runtime/execution/dream-category-context.test.d.ts +1 -0
- package/dist/types/runtime/execution/index.d.ts +1 -0
- package/dist/types/runtime/execution/memory-decay.d.ts +57 -0
- package/dist/types/runtime/execution/memory-decay.test.d.ts +1 -0
- package/dist/types/runtime/hooks/index.d.ts +1 -0
- package/dist/types/runtime/hooks/memory-hooks.d.ts +20 -0
- package/dist/types/runtime/hooks/skill-recall-hooks.d.ts +36 -0
- package/dist/types/runtime/infra/agent-paths.d.ts +20 -2
- package/dist/types/runtime/infra/disk-storage.d.ts +0 -16
- package/dist/types/runtime/infra/index.d.ts +4 -2
- package/dist/types/runtime/infra/media-persistence.d.ts +71 -0
- package/dist/types/runtime/infra/project-instructions-store.d.ts +30 -0
- package/dist/types/runtime/infra/project-plan-store.d.ts +27 -0
- package/dist/types/runtime/infra/project-store.d.ts +30 -0
- package/dist/types/runtime/session/session-persistence.d.ts +3 -1
- package/dist/types/skills/index.d.ts +7 -9
- package/dist/types/skills/memory/categories.d.ts +5 -0
- package/dist/types/skills/memory/find-relevant-memories.d.ts +70 -0
- package/dist/types/skills/memory/memdir.d.ts +85 -0
- package/dist/types/skills/memory/memory-tool.d.ts +16 -44
- package/dist/types/skills/memory/qmemory-adapter.d.ts +12 -0
- package/dist/types/skills/memory/recall-category-filter.d.ts +54 -0
- package/dist/types/skills/permissions/group-security-policy.d.ts +15 -0
- package/dist/types/skills/permissions/index.d.ts +1 -0
- package/dist/types/skills/plugins/plugin-loader.d.ts +5 -0
- package/dist/types/skills/portable-tool.d.ts +13 -2
- package/dist/types/skills/tools/plan-mode-tool.d.ts +1 -1
- package/dist/types/skills/tools/read-tool.d.ts +2 -2
- package/dist/types/skills/tools/skill-tool.d.ts +16 -3
- package/dist/types/skills/tools/task-tool.d.ts +64 -75
- package/package.json +1 -1
- package/dist/types/contracts/planner.d.ts +0 -35
- package/dist/types/orchestration/error-handling/failover-error.d.ts +0 -33
- package/dist/types/skills/memory/memory-store.d.ts +0 -86
- package/dist/types/skills/todo-tool.d.ts +0 -72
- package/dist/types/skills/tools/skill-invoke-tool.d.ts +0 -46
- package/dist/types/skills/tools/skill-list-tool.d.ts +0 -33
- package/dist/types/skills/tools/skill-manage-tool.d.ts +0 -73
- package/dist/types/skills/tools/skill-view-tool.d.ts +0 -37
package/dist/orchestration.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
function ce(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function ue(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.toolReferences?.length?{toolReferences:t.toolReferences}:{}}}var pe=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,h={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]},de=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,me=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,fe=512,ge=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var ye=new Set([500,502,503,504,521,522,523,524,529]),he=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ce=["upgrade your plan","upgrade plan","current plan","subscription"],Te=["daily","weekly","monthly"],be=["try again","retry","temporary","cooldown"],ke=["usage limit","rate limit","organization usage"],_e=["organization","workspace"],Re=["billing period","exceeded","reached","exhausted"],xe=/["']?(?: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,Ae=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function C(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Se(e){return C(e,h.format)}function H(e){return C(e,h.rateLimit)}function ve(e){return C(e,h.timeout)}function Me(e){return pe.test(e)}function v(e){let t=e.toLowerCase();return t?e.length>fe?me.test(t):C(t,h.billing)?!0:de.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Y(e){return C(e,h.authPermanent)}function we(e){return C(e,h.auth)}function W(e){return C(e,h.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function Ee(e){return y(e,he)||y(e,Ce)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ie(e){let t=y(e,Te),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,_e);return y(e,be)&&y(e,ke)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,Re))}function Le(e){return e.trim().toLowerCase().replace(Ae,"").trim()}function K(e){let t=Le(e);return!t||Ee(t)?"billing":H(t)||Ie(t)?"rate_limit":"billing"}function Oe(e){return xe.test(e)?K(e):null}function J(e){let t=e.match(ge);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Pe(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Fe(e){let t=e.trim();if(!t)return!1;let n=J(t);return n?ye.has(n.code):!1}function V(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?K(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Y(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&W(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&v(t)?"billing":"format":null}function Ne(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 Be(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 X(e){if(Be(e))return"session_expired";if(Ne(e))return"model_not_found";let t=Oe(e);return t||(Me(e)?v(e)?"billing":"rate_limit":H(e)?"rate_limit":W(e)?"overloaded":Fe(e)?J(e.trim())?.code===529?"overloaded":"timeout":Pe(e)?"timeout":Se(e)?"format":v(e)?"billing":ve(e)?"timeout":Y(e)?"auth_permanent":we(e)?"auth":null)}var De={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"},je=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function $e(e,t){let n=V(e,t)??(t?X(t):null);return n?De[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function qe(e){return je.has(e)}function B(e){return typeof e.compressAsync=="function"}var Q=4,M=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 a=n;for(let c of o)a-=this.estimateTokens(c);let i;for(let c of r)if(c.role==="user"){i=c;break}if(i&&(a-=this.estimateTokens(i)),a<=0)return{messages:i?[...o,i]:o,droppedCount:r.length-(i?1:0),strategy:"sliding-window"};let s=[],l=0;for(let c=r.length-1;c>=0;c--){let d=r[c];if(d===i)continue;let p=this.estimateTokens(d);if(a-p<0&&l>=Q)break;if(a-p<0&&l<Q){s.unshift(d),l++;continue}a-=p,s.unshift(d),l++}let u=[...o];return i&&!s.includes(i)&&u.push(i),u.push(...s),{messages:u,droppedCount:r.length-(s.length+(i&&!s.includes(i)?1:0)),strategy:"sliding-window"}}},w=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 a=r.slice(0,r.length-this.recentCount),i=r.slice(r.length-this.recentCount),s=this.summarize(a);return{messages:[...o,{role:"system",content:`[Conversation summary]
|
|
1
|
+
function ce(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function ue(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.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var pe=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,h={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]},de=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,me=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,fe=512,ge=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var ye=new Set([500,502,503,504,521,522,523,524,529]),he=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ce=["upgrade your plan","upgrade plan","current plan","subscription"],Te=["daily","weekly","monthly"],be=["try again","retry","temporary","cooldown"],ke=["usage limit","rate limit","organization usage"],_e=["organization","workspace"],Re=["billing period","exceeded","reached","exhausted"],xe=/["']?(?: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,Ae=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function C(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Se(e){return C(e,h.format)}function H(e){return C(e,h.rateLimit)}function ve(e){return C(e,h.timeout)}function Me(e){return pe.test(e)}function v(e){let t=e.toLowerCase();return t?e.length>fe?me.test(t):C(t,h.billing)?!0:de.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Y(e){return C(e,h.authPermanent)}function we(e){return C(e,h.auth)}function W(e){return C(e,h.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function Ee(e){return y(e,he)||y(e,Ce)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ie(e){let t=y(e,Te),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,_e);return y(e,be)&&y(e,ke)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,Re))}function Le(e){return e.trim().toLowerCase().replace(Ae,"").trim()}function K(e){let t=Le(e);return!t||Ee(t)?"billing":H(t)||Ie(t)?"rate_limit":"billing"}function Oe(e){return xe.test(e)?K(e):null}function J(e){let t=e.match(ge);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Pe(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Fe(e){let t=e.trim();if(!t)return!1;let n=J(t);return n?ye.has(n.code):!1}function V(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?K(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Y(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&W(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&v(t)?"billing":"format":null}function Ne(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 Be(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 X(e){if(Be(e))return"session_expired";if(Ne(e))return"model_not_found";let t=Oe(e);return t||(Me(e)?v(e)?"billing":"rate_limit":H(e)?"rate_limit":W(e)?"overloaded":Fe(e)?J(e.trim())?.code===529?"overloaded":"timeout":Pe(e)?"timeout":Se(e)?"format":v(e)?"billing":ve(e)?"timeout":Y(e)?"auth_permanent":we(e)?"auth":null)}var De={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"},je=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function $e(e,t){let n=V(e,t)??(t?X(t):null);return n?De[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function qe(e){return je.has(e)}function B(e){return typeof e.compressAsync=="function"}var Q=4,M=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 a=n;for(let c of o)a-=this.estimateTokens(c);let i;for(let c of r)if(c.role==="user"){i=c;break}if(i&&(a-=this.estimateTokens(i)),a<=0)return{messages:i?[...o,i]:o,droppedCount:r.length-(i?1:0),strategy:"sliding-window"};let s=[],l=0;for(let c=r.length-1;c>=0;c--){let d=r[c];if(d===i)continue;let p=this.estimateTokens(d);if(a-p<0&&l>=Q)break;if(a-p<0&&l<Q){s.unshift(d),l++;continue}a-=p,s.unshift(d),l++}let u=[...o];return i&&!s.includes(i)&&u.push(i),u.push(...s),{messages:u,droppedCount:r.length-(s.length+(i&&!s.includes(i)?1:0)),strategy:"sliding-window"}}},w=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 a=r.slice(0,r.length-this.recentCount),i=r.slice(r.length-this.recentCount),s=this.summarize(a);return{messages:[...o,{role:"system",content:`[Conversation summary]
|
|
2
2
|
${s}`},...i],droppedCount:a.length,strategy:"summarize-old"}}},E=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(a=>a.role!=="tool"||typeof a.content!="string"||a.content.length<=this.maxToolResultChars?a:(o++,{...a,content:Ge(a.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function Ge(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let a=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
|
|
3
3
|
`),n.lastIndexOf(`]
|
|
4
4
|
`));if(a>t*.5)return n.slice(0,a+1)+`
|
|
5
5
|
[...truncated: ${e.length-a-1} chars omitted]`}let r=n.lastIndexOf(`
|
|
6
6
|
`);return r>t*.7?n.slice(0,r)+`
|
|
7
7
|
[...truncated: ${e.length-r} chars omitted]`:n+`
|
|
8
|
-
[...truncated: ${e.length-t} chars omitted]`}function
|
|
8
|
+
[...truncated: ${e.length-t} chars omitted]`}function Ue(...e){return{compress(t,n){let o=t,r=0,a=[];for(let i of e){let s=i.compress(o,n);o=s.messages,r+=s.droppedCount,s.droppedCount>0&&a.push(s.strategy)}return{messages:o,droppedCount:r,strategy:a.length>0?a.join("+"):"none"}}}}function ze(...e){return{compress(t,n){let o=t,r=0,a=[];for(let i of e){let s=i.compress(o,n);o=s.messages,r+=s.droppedCount,s.droppedCount>0&&a.push(s.strategy)}return{messages:o,droppedCount:r,strategy:a.length>0?a.join("+"):"none"}},async compressAsync(t,n){let o=t,r=0,a=[],i=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&&a.push(c.strategy),c.metrics&&(i+=c.metrics.latencyMs,s=s||c.metrics.usedLlm,l=l||!!c.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:a.length>0?a.join("+"):"none",metrics:i>0||s?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:i,usedLlm:s,cacheInvalidated:l}:void 0}}}}function D(e,t){let n=e.filter(i=>i.role==="user"),o=e.filter(i=>i.tool_calls!=null),r=e.filter(i=>i.role==="tool"),a=["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. Error & Recovery History","Summarize any errors encountered and how they were resolved.","","### 7. User Preferences Expressed",`The user sent ${n.length} messages. Note any stated preferences about style, approach, or constraints.`,"","### 8. Technical State","Note file paths, variable names, API endpoints, or configuration values that were discussed.","","### 9. Conversation Flow","Briefly describe the overall flow: what happened first, what changed, where we are now."];return t?.taskContext&&a.push("","## Additional Context",t.taskContext),a.push("","## Conversation to Summarize","",...e.map(i=>{let s=typeof i.content=="string"?i.content:JSON.stringify(i.content??""),l=i.role==="user"?s:s.length>2e3?s.slice(0,2e3)+"...":s;return`[${i.role}]: ${l}`}),"","## Output Format","Respond with a concise summary covering all 9 sections above. Use markdown headers.","Keep the total summary under 800 words. Focus on actionable information."),a.join(`
|
|
9
9
|
`)}var I=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??R,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:a}=ee(t),i=t.reduce((m,g)=>m+this.config.estimateTokens(g),0);if(i<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let s=0,l=0;for(let m=0;m<a.length&&(a[m].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));m++)s=m+1;let u=Math.max(this.config.protectedTailMessages,Math.floor(a.length*.4)),c=Math.max(s,a.length-u);if(c<=s)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let d=a.slice(0,s),p=a.slice(s,c),f=a.slice(c),T=D(p,{taskContext:this.config.taskContext}),x=await this.config.summarize(p,T),A={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
|
|
10
10
|
|
|
11
11
|
${x}`},b=[...r,...d,A,...f],S=Date.now()-o,k=b.reduce((m,g)=>m+this.config.estimateTokens(g),0);return{messages:b,droppedCount:p.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:k,compressionRatio:i>0?k/i:1,latencyMs:S,usedLlm:!0,cacheInvalidated:!0}}}},L=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??R}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:a}=ee(t),i=r.findIndex(m=>typeof m.content=="string"&&m.content.startsWith("[Conversation summary")),s=i>=0?r[i]:void 0,l=i>=0?[...r.slice(0,i),...r.slice(i+1)]:r,u=Math.max(0,a.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=a.slice(0,u),p=a.slice(u),f=s&&typeof s.content=="string"?`Previous summary:
|
|
@@ -16,14 +16,14 @@ New messages to integrate:`:void 0,T=D(d,{taskContext:f}),x=await this.config.su
|
|
|
16
16
|
${x}`},b=[...l,A,...p],S=Date.now()-o,k=b.reduce((m,g)=>m+this.config.estimateTokens(g),0);return{messages:b,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:c,tokensAfter:k,compressionRatio:c>0?k/c:1,latencyMs:S,usedLlm:!0,cacheInvalidated:!0}}}},O=class{config;constructor(t){this.config=t}compress(t,n){let o=_(t),r=this.config.inner.compress(t,n),a=_(r.messages),i=o!==a&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}async compressAsync(t,n){let o=_(t),r=B(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),a=_(r.messages),i=o!==a&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}},Z={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function He(e={}){let t={...Z,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function Ye(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var P=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,a=0,i=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&&a++,s.cacheInvalidated&&i++;return{totalCompressions:t,totalLlmCalls:a,totalCacheInvalidations:i,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},F=class{engines=new Map;activeId;register(t){this.engines.set(t.id,t)}activate(t){return this.engines.has(t)?(this.activeId=t,!0):!1}getActive(){return this.activeId?this.engines.get(this.activeId):void 0}listEngines(){return Array.from(this.engines.values()).map(t=>({id:t.id,label:t.label,active:t.id===this.activeId}))}};function ee(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function R(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function _(e){let t=Math.min(e.length,5),n=[];for(let o=0;o<t;o++){let r=e[o],a=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${a}`)}return n.join("|")}var We=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"]),N=class{constructor(t=20,n=R){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,a=0;return{messages:t.map((s,l)=>{if(l>=o||s.role!=="tool"||typeof s.content!="string"||!s.name||!We.has(s.name)||s.content.length<=200)return s;let u=this.estimateTokens(s);return a+=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 Ke(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 a=r.function?.name??"";if(/read|edit|write|file/i.test(a)&&r.function?.arguments)try{let i=JSON.parse(r.function.arguments),s=i.path??i.filePath??i.file_path??i.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 Je(e,t,n){let o=n.estimateTokens??(p=>Math.ceil(p.length/4)),r=Ke(t);if(r.length===0)return e;let a=e.map(p=>typeof p.content=="string"?p.content:"").join(`
|
|
17
17
|
`),i=r.filter(p=>!a.includes(p));if(i.length===0)return e;let s=n.maxTokenBudget,l=[],u=0;for(let p of i){if(u>=n.maxFiles||s<=0)break;let f=await n.readFile(p);if(!f)continue;let T=o(f);T>s||(s-=T,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 Ve(e,t,n=R){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,a=[];for(let s of e){let l=s.tool_call_id??"";if(l&&t.has(l)){o+=n(s),r++,t.delete(l);continue}a.push(s)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:a,tokensFreed:o,removedCount:r,boundaryMessage:i}}function Xe(){return{stages:[]}}function Qe(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let a=te(e,t),i=et(a,t,o);if(i.length===0)return{messages:a,stagedCount:0};for(let s of i)t.stages.push(s);return a=te(e,t),{messages:a,stagedCount:i.length}}function Ze(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:ne(e,t),committed:n}}function te(e,t){return t.stages.filter(o=>o.committed).length===0?e:ne(e,t)}function ne(e,t){let n=t.stages.filter(r=>r.committed).sort((r,a)=>a.range[0]-r.range[0]),o=[...e];for(let r of n){let[a,i]=r.range;if(a>=o.length)continue;let s=Math.min(i,o.length),l={role:"system",content:r.summary};o.splice(a,s-a,l)}return o}function et(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],a=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-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==="")i<0&&(i=l),s++;else{if(s>=3){let d=`${i}-${i+s}`;a.has(d)||r.push({id:`collapse_${i}_${i+s}`,range:[i,i+s],summary:`[${s} tool results collapsed]`,committed:!1})}i=-1,s=0}}if(s>=3){let l=`${i}-${i+s}`;a.has(l)||r.push({id:`collapse_${i}_${i+s}`,range:[i,i+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}function tt(e){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<3||e.distinctToolCount<2)}function nt(e){return e.existingSkillName?e.feedback==="negative":!1}function ot(e,t){return nt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:tt(e)?{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 oe(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 rt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function st(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function it(e){if(!e.eligibility?.length)return[...e.tools];let t=st(e.eligibility);return e.tools.filter(n=>{let o=oe(n);if(!o)return!1;let r=t.get(o);return!r||rt(r.status)})}function at(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 lt(e){let t=at({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=it({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,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 a=n.function??void 0,i=typeof a?.name=="string"?a.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let s=r.filter(l=>oe(l)===i);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var ct=["stop","aborted","timeout","cancelled","interrupted","error"],ut=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function re(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function pt(e,t){return{...e,content:[...re(e.content),...re(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 mt(e){return new Set((e??ct).map(t=>t.trim().toLowerCase()))}function se(e,t){return e?mt(t).has(e.trim().toLowerCase()):!1}function ft(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function j(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(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 a=[];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!==""&&a.push(c);continue}if(l.length<s.tool_calls.length){a.push({...s,tool_calls:l});continue}}a.push(s)}let i=[];for(let s of a){let l=i.length>0?i[i.length-1]:void 0;if(s.role==="user"&&l?.role==="user"){i[i.length-1]=pt(l,s);continue}i.push(s)}return i}function $(e,t){return se(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of ut)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 a of e)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&o.add(a.tool_call_id);let r=[];for(let a of e)if(r.push({...a}),!(a.role!=="assistant"||!Array.isArray(a.tool_calls)||a.tool_calls.length===0))for(let i of a.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function gt(e,t){let n=j(e),o=$(n,t);return q(o,t)}function ie(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=se(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=ft(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let a=new Set,i=new Map;for(let u of r){if(u.type!=="function_call")continue;let c=typeof u.call_id=="string"&&u.call_id?u.call_id:typeof u.id=="string"?u.id:void 0;c&&(a.add(c),i.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||!a.has(c))continue;s.add(c)}l.push(u)}for(let[u]of i)s.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function yt(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function ht(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function Ct(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 Tt(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 ae(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function bt(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 kt(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 _t(e){let t=[],n=j(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=$(n,e.options);o.some((a,i)=>a!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=q(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:ae({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:yt(r),completedToolCallIds:ht(r)}),recoveryActions:t}}function Rt(e){let t=ie(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:ae({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:Ct(t),completedToolCallIds:Tt(t)}),recoveryActions:n}}var xt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function At(e){return e?xt.has(e):!0}function St(e){return e===429||e===529}function vt(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 Tn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Mt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var G=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var z="<fork-child-context>",le="Fork started \u2014 processing in background",wt=4;function Et(e){return JSON.stringify(e).includes(z)}function It(e){return e<4}function Lt(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 Ve(e,t,n=R){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,a=[];for(let s of e){let l=s.tool_call_id??"";if(l&&t.has(l)){o+=n(s),r++,t.delete(l);continue}a.push(s)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:a,tokensFreed:o,removedCount:r,boundaryMessage:i}}function Xe(){return{stages:[]}}function Qe(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let a=te(e,t),i=et(a,t,o);if(i.length===0)return{messages:a,stagedCount:0};for(let s of i)t.stages.push(s);return a=te(e,t),{messages:a,stagedCount:i.length}}function Ze(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:ne(e,t),committed:n}}function te(e,t){return t.stages.filter(o=>o.committed).length===0?e:ne(e,t)}function ne(e,t){let n=t.stages.filter(r=>r.committed).sort((r,a)=>a.range[0]-r.range[0]),o=[...e];for(let r of n){let[a,i]=r.range;if(a>=o.length)continue;let s=Math.min(i,o.length),l={role:"system",content:r.summary};o.splice(a,s-a,l)}return o}function et(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],a=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-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==="")i<0&&(i=l),s++;else{if(s>=3){let d=`${i}-${i+s}`;a.has(d)||r.push({id:`collapse_${i}_${i+s}`,range:[i,i+s],summary:`[${s} tool results collapsed]`,committed:!1})}i=-1,s=0}}if(s>=3){let l=`${i}-${i+s}`;a.has(l)||r.push({id:`collapse_${i}_${i+s}`,range:[i,i+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}function tt(e){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<3||e.distinctToolCount<2)}function nt(e){return e.existingSkillName?e.feedback==="negative":!1}function ot(e,t){return nt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:tt(e)?{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 oe(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 rt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function st(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function it(e){if(!e.eligibility?.length)return[...e.tools];let t=st(e.eligibility);return e.tools.filter(n=>{let o=oe(n);if(!o)return!1;let r=t.get(o);return!r||rt(r.status)})}function at(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 lt(e){let t=at({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=it({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,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 a=n.function??void 0,i=typeof a?.name=="string"?a.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let s=r.filter(l=>oe(l)===i);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var ct=["stop","aborted","timeout","cancelled","interrupted","error"],ut=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function re(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function pt(e,t){return{...e,content:[...re(e.content),...re(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 mt(e){return new Set((e??ct).map(t=>t.trim().toLowerCase()))}function se(e,t){return e?mt(t).has(e.trim().toLowerCase()):!1}function ft(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function j(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(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 a=[];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!==""&&a.push(c);continue}if(l.length<s.tool_calls.length){a.push({...s,tool_calls:l});continue}}a.push(s)}let i=[];for(let s of a){let l=i.length>0?i[i.length-1]:void 0;if(s.role==="user"&&l?.role==="user"){i[i.length-1]=pt(l,s);continue}i.push(s)}return i}function $(e,t){return se(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of ut)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 a of e)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&o.add(a.tool_call_id);let r=[];for(let a of e)if(r.push({...a}),!(a.role!=="assistant"||!Array.isArray(a.tool_calls)||a.tool_calls.length===0))for(let i of a.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function gt(e,t){let n=j(e),o=$(n,t);return q(o,t)}function ie(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=se(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=ft(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let a=new Set,i=new Map;for(let u of r){if(u.type!=="function_call")continue;let c=typeof u.call_id=="string"&&u.call_id?u.call_id:typeof u.id=="string"?u.id:void 0;c&&(a.add(c),i.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||!a.has(c))continue;s.add(c)}l.push(u)}for(let[u]of i)s.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function yt(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function ht(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function Ct(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 Tt(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 ae(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function bt(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 kt(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 _t(e){let t=[],n=j(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=$(n,e.options);o.some((a,i)=>a!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=q(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:ae({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:yt(r),completedToolCallIds:ht(r)}),recoveryActions:t}}function Rt(e){let t=ie(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:ae({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:Ct(t),completedToolCallIds:Tt(t)}),recoveryActions:n}}var xt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function At(e){return e?xt.has(e):!0}function St(e){return e===429||e===529}function vt(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 Tn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Mt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var G=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var U="<fork-child-context>",le="Fork started \u2014 processing in background",wt=4;function Et(e){return JSON.stringify(e).includes(U)}function It(e){return e<4}function Lt(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
|
|
20
20
|
|
|
21
21
|
Your working directory is: ${e.worktreePath}
|
|
22
|
-
All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${
|
|
22
|
+
All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${U}
|
|
23
23
|
|
|
24
24
|
You are the "${t.agent.name}" agent.${o}
|
|
25
25
|
|
|
26
|
-
${t.taskPrompt}`}]};return n.push(r),n}function Ot(e){return e.map(t=>({role:"tool",tool_call_id:t,content:le}))}function Pt(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolAccessMode==="none")return[];if(t.toolAccessMode==="read-only"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent")}function Ft(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var Nt={name:"general",label:"General Purpose",description:"A general-purpose sub-agent that can perform any task with full tool access.",maxTurns:200,toolAccessMode:"full",canFork:!1},Bt={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","tool_search"],canFork:!1},Dt={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","
|
|
26
|
+
${t.taskPrompt}`}]};return n.push(r),n}function Ot(e){return e.map(t=>({role:"tool",tool_call_id:t,content:le}))}function Pt(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolAccessMode==="none")return[];if(t.toolAccessMode==="read-only"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent")}function Ft(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var Nt={name:"general",label:"General Purpose",description:"A general-purpose sub-agent that can perform any task with full tool access.",maxTurns:200,toolAccessMode:"full",canFork:!1},Bt={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","tool_search"],canFork:!1},Dt={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","task","tool_search"],canFork:!1},jt={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},$t={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolAccessMode:"read-only",allowedTools:["web_search","web_fetch","read_file","search","think","memory"],canFork:!1},qt={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolAccessMode:"full",allowedTools:["exec","read_file","search","think"],canFork:!1},z=[Nt,Bt,Dt,jt,$t,qt];function Gt(){return[...z]}function Ut(e){return z.find(t=>t.name===e)}function zt(e){return z.some(t=>t.name===e)}function Ht(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolAccessMode==="none")return[];if(e.toolAccessMode==="read-only"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(o=>!n.has(o))}return e.canFork?[...t]:t.filter(n=>n!=="agent_tool"&&n!=="team_create")}var Yt=new Set(["agent_tool","team_create","fork_agent","send_message"]);function Wt(e,t){switch(e){case"worker":return t.filter(n=>!Yt.has(n));case"coordinator":return[...t];default:return[...t]}}function Kt(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function Jt(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Vt(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function Xt(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function Qt(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function Zt(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var en={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function tn(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
|
|
27
27
|
${n.join(`
|
|
28
28
|
`)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
|
|
29
29
|
Step ${e.activeSkillContext.step}:
|
|
@@ -34,4 +34,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
|
|
|
34
34
|
|
|
35
35
|
${t.join(`
|
|
36
36
|
|
|
37
|
-
`)}`}function nn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function on(e,t=en){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{O as CacheAwareCompressionStrategy,P as CompressionMetricsCollector,F as ContextEngineRegistry,Z as DEFAULT_ADAPTIVE_BUDGET_CONFIG,le as FORK_PLACEHOLDER_RESULT,
|
|
37
|
+
`)}`}function nn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function on(e,t=en){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{O as CacheAwareCompressionStrategy,P as CompressionMetricsCollector,F as ContextEngineRegistry,Z as DEFAULT_ADAPTIVE_BUDGET_CONFIG,le as FORK_PLACEHOLDER_RESULT,U as FORK_SENTINEL_TAG,G as FallbackTriggeredError,I as HeadTailProtectedStrategy,L as IncrementalCompactStrategy,wt as MAX_FORK_DEPTH,N as MicroCompactStrategy,M as SlidingWindowStrategy,w as SummarizeOldStrategy,E as ToolResultTrimStrategy,bt as advanceToolLoopState,Qe as applyContextCollapsesIfNeeded,lt as applyToolChoicePolicy,ce as buildAssistantToolCallMessage,Ot as buildForkPlaceholderResults,Lt as buildForkedMessages,tn as buildPostCompactRestorationMessage,ot as buildSkillInstruction,D as buildStructuredSummaryPrompt,ue as buildToolResultMessage,Vt as calculateTokenWarningState,It as canForkAtDepth,$e as classifyError,ze as composeAsyncStrategies,Ue as composeStrategies,He as computeAdaptiveBudget,vt as computeRetryBackoff,Xe as createCollapseStore,nn as createReactiveCompactState,Kt as createTaskState,Jt as createTurnLoopGuardState,Wt as filterToolsByRole,Ft as generateForkChildAgentId,Ut as getBuiltInAgent,Gt as getBuiltInAgents,B as isAsyncCompressionStrategy,zt as isBuiltInAgent,At as isForegroundSource,Et as isInForkChild,Mt as isPersistentRetryEnabled,qe as isRetryableCategory,St as isTransientCapacityError,Je as postCompactFileRecovery,Ze as recoverContextCollapseFromOverflow,_t as recoverToolLoopStateFromChatConversation,Rt as recoverToolLoopStateFromResponsesItems,gt as repairOpenAiChatConversation,Ht as resolveAgentToolSet,Xt as resolveApiErrorRecovery,Pt as resolveForkChildTools,Qt as resolveOutputTokenEscalation,Ye as selectCompressionTier,kt as settleToolLoopState,Zt as shouldAbortTurn,on as shouldAttemptReactiveCompact,Ve as snipCompactIfNeeded};
|
|
@@ -36,7 +36,8 @@ export interface ChatMessage {
|
|
|
36
36
|
* Transports convert these into the provider's native content block format:
|
|
37
37
|
* - OpenAI-chat: [{type:"text",text:...},{type:"image_url",image_url:{url:...}}]
|
|
38
38
|
* - Anthropic: [{type:"text",text:...},{type:"image",source:{type:"url",url:...}}]
|
|
39
|
-
*
|
|
39
|
+
* Valid on role="user" and role="tool" messages.
|
|
40
|
+
* For tool results, images are resolved via FileUploadAdapter before sending to LLM.
|
|
40
41
|
*/
|
|
41
42
|
imageUrls?: string[];
|
|
42
43
|
/** Image detail level for vision understanding: 'auto' | 'low' | 'high' | 'xhigh' */
|
|
@@ -361,6 +362,7 @@ export interface ToolInvoker {
|
|
|
361
362
|
result: string;
|
|
362
363
|
error?: string;
|
|
363
364
|
toolReferences?: string[];
|
|
365
|
+
imageUrls?: string[];
|
|
364
366
|
}>;
|
|
365
367
|
}
|
|
366
368
|
/**
|
|
@@ -41,13 +41,16 @@ export declare class StdioServer {
|
|
|
41
41
|
private sessionState;
|
|
42
42
|
private currentMediaApiKeys;
|
|
43
43
|
private taskStore;
|
|
44
|
+
/** Media auto-download service — persists generated media files locally. */
|
|
45
|
+
private mediaPersistence;
|
|
44
46
|
/** Session-scoped memory prefetch state (LRU dedup + byte limit). */
|
|
45
47
|
private memoryPrefetchState;
|
|
46
48
|
/** QMemory adapter (when QMEMORY_BASE_URL env is set). Used by Dream hippocampus bridge. */
|
|
47
49
|
private qmemoryAdapter;
|
|
48
50
|
private qmemoryUserId;
|
|
49
|
-
/**
|
|
50
|
-
private
|
|
51
|
+
/** MEMDIR file-based memory (CC memdir parity). */
|
|
52
|
+
private memdir;
|
|
53
|
+
/** Memory write gate state (P2+P3: category gate + supersedes). */
|
|
51
54
|
private fileWatcher;
|
|
52
55
|
/** Pending ask_user requests waiting for host response */
|
|
53
56
|
private pendingAskUser;
|
|
@@ -123,15 +126,15 @@ export declare class StdioServer {
|
|
|
123
126
|
*/
|
|
124
127
|
private handleSessionGetInfo;
|
|
125
128
|
/**
|
|
126
|
-
* `memory.list` — Enumerate available memory sources (
|
|
129
|
+
* `memory.list` — Enumerate available memory sources (memdir + qmemory).
|
|
127
130
|
*/
|
|
128
131
|
private handleMemoryList;
|
|
129
132
|
/**
|
|
130
|
-
* `memory.read` — Read memory content from
|
|
133
|
+
* `memory.read` — Read memory content from memdir (INDEX.md or topic file).
|
|
131
134
|
*/
|
|
132
135
|
private handleMemoryRead;
|
|
133
136
|
/**
|
|
134
|
-
* `memory.write` — Write memory content to
|
|
137
|
+
* `memory.write` — Write memory content to memdir (INDEX.md or topic file).
|
|
135
138
|
*/
|
|
136
139
|
private handleMemoryWrite;
|
|
137
140
|
/**
|
|
@@ -176,12 +179,11 @@ export declare class StdioServer {
|
|
|
176
179
|
*/
|
|
177
180
|
private handleTodosList;
|
|
178
181
|
/**
|
|
179
|
-
* `memory.search` —
|
|
180
|
-
* Powers the memory page's search feature.
|
|
182
|
+
* `memory.search` — Search memory via QMemory (vector) or memdir (local keyword).
|
|
181
183
|
*/
|
|
182
184
|
private handleMemorySearch;
|
|
183
185
|
/**
|
|
184
|
-
* `memory.delete` — Remove
|
|
186
|
+
* `memory.delete` — Remove memory entry from memdir (INDEX.md line) or QMemory (by ID).
|
|
185
187
|
*/
|
|
186
188
|
private handleMemoryDelete;
|
|
187
189
|
/**
|
|
@@ -298,4 +300,21 @@ export declare class StdioServer {
|
|
|
298
300
|
private acpHandleProductResume;
|
|
299
301
|
private acpHandleProductStatus;
|
|
300
302
|
private acpHandleTeamDelegate;
|
|
303
|
+
private handleProjectCreate;
|
|
304
|
+
private handleProjectList;
|
|
305
|
+
private handleProjectDelete;
|
|
306
|
+
private handleProjectArchiveByGroup;
|
|
307
|
+
private handleSessionSwitchProject;
|
|
308
|
+
private handleSessionGetState;
|
|
309
|
+
private getProjectInstructionsStore;
|
|
310
|
+
private handleInstructionsList;
|
|
311
|
+
private handleInstructionsRead;
|
|
312
|
+
private handleInstructionsWrite;
|
|
313
|
+
private handleInstructionsDelete;
|
|
314
|
+
private handleSkillsList;
|
|
315
|
+
private handleSkillsActivate;
|
|
316
|
+
private handleSkillsDeactivate;
|
|
317
|
+
private getProjectPlanStore;
|
|
318
|
+
private handlePlansList;
|
|
319
|
+
private handlePlansGet;
|
|
301
320
|
}
|
|
@@ -1,16 +1,24 @@
|
|
|
1
1
|
import type { PortableTool } from "../skills/portable-tool.js";
|
|
2
|
+
import { type TaskToolHooks } from "../skills/tools/task-tool.js";
|
|
2
3
|
import { type ExecProgress } from "../skills/tools/exec-tool.js";
|
|
3
4
|
import type { AgentLogger } from "../agent/types.js";
|
|
4
5
|
import { type AskUserQuestion } from "../skills/tools/ask-user-tool.js";
|
|
5
6
|
import type { MediaClient } from "../llm/media-client.js";
|
|
6
7
|
import type { MediaCapability } from "../llm/provider-def.js";
|
|
7
8
|
import type { ProviderToolAPI } from "../llm/provider-tool-api.js";
|
|
9
|
+
/** Enable or disable group security mode (blocks sensitive file access). */
|
|
10
|
+
export declare function setGroupSecurityMode(enabled: boolean): void;
|
|
8
11
|
/**
|
|
9
12
|
* Set the provider's tool API for C-level cascade.
|
|
10
13
|
* When set, web_search tool will try provider-native search first,
|
|
11
14
|
* falling back to SearXNG. Called from stdio-server per session.
|
|
12
15
|
*/
|
|
13
16
|
export declare function setProviderToolAPI(api: ProviderToolAPI | undefined): void;
|
|
17
|
+
/**
|
|
18
|
+
* Set task tool lifecycle hooks. Called from stdio-server when session starts.
|
|
19
|
+
* Connects planning-task events to the HookRegistry.
|
|
20
|
+
*/
|
|
21
|
+
export declare function setTaskToolHooks(hooks: TaskToolHooks | undefined): void;
|
|
14
22
|
/**
|
|
15
23
|
* Set the ask_user callback. The host (Electron / test harness) provides
|
|
16
24
|
* an implementation that presents questions to the user and returns answers.
|
|
@@ -114,7 +114,10 @@ export interface HookContextMap {
|
|
|
114
114
|
recalledMemories?: Array<{
|
|
115
115
|
text: string;
|
|
116
116
|
score?: number;
|
|
117
|
+
category?: string | null;
|
|
117
118
|
}>;
|
|
119
|
+
preferredCategories?: string[];
|
|
120
|
+
deprioritizedCategories?: string[];
|
|
118
121
|
};
|
|
119
122
|
"memory.after_recall": HookTurnContext & {
|
|
120
123
|
blockCount?: number;
|
|
@@ -1,23 +1,10 @@
|
|
|
1
|
+
import type { TaskItem, TaskListSummary } from "../skills/tools/task-tool.js";
|
|
2
|
+
import { summarizeTaskList } from "../skills/tools/task-tool.js";
|
|
1
3
|
export declare const TODO_ITEM_STATUS_VALUES: readonly ["not-started", "in-progress", "completed"];
|
|
2
4
|
export type TodoItemStatus = (typeof TODO_ITEM_STATUS_VALUES)[number];
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
/** Owner agent/subagent identifier for per-agent isolation (V2). */
|
|
10
|
-
owner?: string;
|
|
11
|
-
/** IDs of tasks that must complete before this one can start (V2). */
|
|
12
|
-
blockedBy?: number[];
|
|
13
|
-
/** IDs of tasks this one blocks from starting (V2). */
|
|
14
|
-
blocks?: number[];
|
|
15
|
-
}
|
|
16
|
-
export interface TodoListSummary {
|
|
17
|
-
total: number;
|
|
18
|
-
completed: number;
|
|
19
|
-
inProgress: number;
|
|
20
|
-
notStarted: number;
|
|
21
|
-
blocked: number;
|
|
22
|
-
}
|
|
23
|
-
export declare function summarizeTodoList(items: readonly TodoItem[]): TodoListSummary;
|
|
5
|
+
/** @deprecated Use TaskItem from task-tool.ts */
|
|
6
|
+
export type TodoItem = TaskItem;
|
|
7
|
+
/** @deprecated Use TaskListSummary from task-tool.ts */
|
|
8
|
+
export type TodoListSummary = TaskListSummary;
|
|
9
|
+
/** @deprecated Use summarizeTaskList from task-tool.ts */
|
|
10
|
+
export declare const summarizeTodoList: typeof summarizeTaskList;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Aliyun OSS File Upload Adapter — direct upload to Alibaba Cloud OSS.
|
|
3
|
+
*
|
|
4
|
+
* Uploads files directly to OSS bucket using V1 signature (HMAC-SHA1).
|
|
5
|
+
* No external dependencies — uses Node.js crypto + fetch.
|
|
6
|
+
*
|
|
7
|
+
* This is the **universal fallback adapter** for providers without a native
|
|
8
|
+
* File Upload API (e.g. Anthropic). Ensures ALL file handling goes through
|
|
9
|
+
* upload — never base64 inline.
|
|
10
|
+
*
|
|
11
|
+
* Environment variables:
|
|
12
|
+
* OSS_ACCESS_KEY_ID — Aliyun AccessKey ID
|
|
13
|
+
* OSS_ACCESS_KEY_SECRET — Aliyun AccessKey Secret
|
|
14
|
+
* OSS_BUCKET — Bucket name (default: "qlogicagent")
|
|
15
|
+
* OSS_REGION — Region (default: "cn-beijing")
|
|
16
|
+
* OSS_ENDPOINT — Custom endpoint (default: derived from region)
|
|
17
|
+
*/
|
|
18
|
+
import type { FileUploadAdapter, FileUploadResult } from "../file-upload-service.js";
|
|
19
|
+
export interface AliyunOSSFileUploadConfig {
|
|
20
|
+
/** Aliyun AccessKey ID. Required. */
|
|
21
|
+
accessKeyId: string;
|
|
22
|
+
/** Aliyun AccessKey Secret. Required. */
|
|
23
|
+
accessKeySecret: string;
|
|
24
|
+
/** OSS Bucket name. Default: "qlogicagent". */
|
|
25
|
+
bucket?: string;
|
|
26
|
+
/** OSS Region. Default: "cn-beijing". */
|
|
27
|
+
region?: string;
|
|
28
|
+
/** Custom OSS endpoint. Default: "{bucket}.oss-{region}.aliyuncs.com". */
|
|
29
|
+
endpoint?: string;
|
|
30
|
+
/** Upload path prefix. Default: "media". */
|
|
31
|
+
pathPrefix?: string;
|
|
32
|
+
/** Timeout ms. Default: 120_000. */
|
|
33
|
+
timeoutMs?: number;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Create an AliyunOSSFileUploadAdapter from environment variables.
|
|
37
|
+
* Returns undefined if required env vars (OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET) are missing.
|
|
38
|
+
*/
|
|
39
|
+
export declare function createAliyunOSSAdapterFromEnv(): AliyunOSSFileUploadAdapter | undefined;
|
|
40
|
+
export declare class AliyunOSSFileUploadAdapter implements FileUploadAdapter {
|
|
41
|
+
private readonly config;
|
|
42
|
+
constructor(config: AliyunOSSFileUploadConfig);
|
|
43
|
+
uploadFile(buffer: Buffer, filename: string, mimeType: string, _apiKey: string, signal?: AbortSignal): Promise<FileUploadResult>;
|
|
44
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gemini File Upload Adapter.
|
|
3
|
+
*
|
|
4
|
+
* Implements the Google Gemini 2-step resumable upload protocol
|
|
5
|
+
* into the unified FileUploadAdapter interface.
|
|
6
|
+
*
|
|
7
|
+
* Protocol:
|
|
8
|
+
* 1. POST /upload/v1beta/files — initiate, get upload URL
|
|
9
|
+
* 2. PUT {uploadUrl} — send bytes, finalize
|
|
10
|
+
*
|
|
11
|
+
* Returns a file URI (e.g. "files/abc123") that can be used in
|
|
12
|
+
* generateContent requests as a file reference.
|
|
13
|
+
*/
|
|
14
|
+
import type { FileUploadAdapter, FileUploadResult } from "../file-upload-service.js";
|
|
15
|
+
export interface GeminiFileUploadConfig {
|
|
16
|
+
/** Base URL (e.g. "https://generativelanguage.googleapis.com/v1beta") */
|
|
17
|
+
baseUrl: string;
|
|
18
|
+
/** Timeout ms. Default: 180_000. */
|
|
19
|
+
timeoutMs?: number;
|
|
20
|
+
}
|
|
21
|
+
export declare class GeminiFileUploadAdapter implements FileUploadAdapter {
|
|
22
|
+
private readonly config;
|
|
23
|
+
constructor(config: GeminiFileUploadConfig);
|
|
24
|
+
uploadFile(buffer: Buffer, filename: string, mimeType: string, apiKey: string, signal?: AbortSignal): Promise<FileUploadResult>;
|
|
25
|
+
private waitForProcessing;
|
|
26
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hub OSS File Upload Adapter — for providers without native File API (e.g. Anthropic).
|
|
3
|
+
*
|
|
4
|
+
* Uploads local files to the Hub's OSS relay endpoint, which stores them in
|
|
5
|
+
* cloud object storage (Aliyun OSS / Tencent COS) and returns a public URL.
|
|
6
|
+
* The LLM provider can then access the file via this public URL.
|
|
7
|
+
*
|
|
8
|
+
* This enables Anthropic (which only supports base64 inline or public URL)
|
|
9
|
+
* to handle large files that exceed the base64 size limit (20MB).
|
|
10
|
+
*
|
|
11
|
+
* Endpoint: POST {hubBaseUrl}/api/v1/files/upload
|
|
12
|
+
* Returns: { url: "https://oss-bucket.oss-cn-xxx.aliyuncs.com/..." }
|
|
13
|
+
*/
|
|
14
|
+
import type { FileUploadAdapter, FileUploadResult } from "../file-upload-service.js";
|
|
15
|
+
export interface HubOSSFileUploadConfig {
|
|
16
|
+
/** Hub API base URL (e.g. "https://hub.xiaozhiclaw.com" or from env). */
|
|
17
|
+
hubBaseUrl: string;
|
|
18
|
+
/** Hub API key for authentication. */
|
|
19
|
+
hubApiKey?: string;
|
|
20
|
+
/** Timeout ms. Default: 120_000. */
|
|
21
|
+
timeoutMs?: number;
|
|
22
|
+
/** Provider name for result metadata. Default: "hub-oss". */
|
|
23
|
+
provider?: string;
|
|
24
|
+
}
|
|
25
|
+
export declare class HubOSSFileUploadAdapter implements FileUploadAdapter {
|
|
26
|
+
private readonly config;
|
|
27
|
+
constructor(config: HubOSSFileUploadConfig);
|
|
28
|
+
uploadFile(buffer: Buffer, filename: string, mimeType: string, _apiKey: string, signal?: AbortSignal): Promise<FileUploadResult>;
|
|
29
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Upload Adapters — barrel export.
|
|
3
|
+
*
|
|
4
|
+
* Provider-specific implementations of the FileUploadAdapter interface.
|
|
5
|
+
*/
|
|
6
|
+
export { OpenAIFileUploadAdapter, type OpenAIFileUploadConfig } from "./openai-file-upload-adapter.js";
|
|
7
|
+
export { VolcengineFileUploadAdapter, type VolcengineFileUploadConfig } from "./volcengine-file-upload-adapter.js";
|
|
8
|
+
export { GeminiFileUploadAdapter, type GeminiFileUploadConfig } from "./gemini-file-upload-adapter.js";
|
|
9
|
+
export { HubOSSFileUploadAdapter, type HubOSSFileUploadConfig } from "./hub-oss-file-upload-adapter.js";
|
|
10
|
+
export { AliyunOSSFileUploadAdapter, type AliyunOSSFileUploadConfig, createAliyunOSSAdapterFromEnv } from "./aliyun-oss-file-upload-adapter.js";
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI-compatible File Upload Adapter.
|
|
3
|
+
*
|
|
4
|
+
* Implements FileUploadAdapter for providers using the standard
|
|
5
|
+
* POST /v1/files multipart upload endpoint:
|
|
6
|
+
* - OpenAI
|
|
7
|
+
* - Kimi (Moonshot)
|
|
8
|
+
* - Minimax
|
|
9
|
+
* - Qwen (via DashScope compatible endpoint)
|
|
10
|
+
* - GLM (Zhipu)
|
|
11
|
+
* - Any OpenAI-API-compatible provider
|
|
12
|
+
*
|
|
13
|
+
* The uploaded file gets a file_id which can be referenced in messages.
|
|
14
|
+
* Some providers also return a direct download URL.
|
|
15
|
+
*/
|
|
16
|
+
import type { FileUploadAdapter, FileUploadResult } from "../file-upload-service.js";
|
|
17
|
+
export interface OpenAIFileUploadConfig {
|
|
18
|
+
/** Base URL (e.g. "https://api.openai.com/v1" or "https://api.moonshot.cn/v1") */
|
|
19
|
+
baseUrl: string;
|
|
20
|
+
/** Provider name for result metadata. */
|
|
21
|
+
provider: string;
|
|
22
|
+
/** Extra headers to include (e.g. for Minimax group_id). */
|
|
23
|
+
extraHeaders?: Record<string, string>;
|
|
24
|
+
/** Upload purpose (default: "file-extract" for document understanding). */
|
|
25
|
+
defaultPurpose?: string;
|
|
26
|
+
/**
|
|
27
|
+
* Whether the provider returns a download URL in the upload response.
|
|
28
|
+
* If false, constructs URL from file_id (provider-specific).
|
|
29
|
+
*/
|
|
30
|
+
returnsUrl?: boolean;
|
|
31
|
+
/** Timeout for upload request (ms). Default: 120_000. */
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
}
|
|
34
|
+
export declare class OpenAIFileUploadAdapter implements FileUploadAdapter {
|
|
35
|
+
private readonly config;
|
|
36
|
+
constructor(config: OpenAIFileUploadConfig);
|
|
37
|
+
uploadFile(buffer: Buffer, filename: string, mimeType: string, apiKey: string, signal?: AbortSignal): Promise<FileUploadResult>;
|
|
38
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Volcengine File Upload Adapter.
|
|
3
|
+
*
|
|
4
|
+
* Wraps the Volcengine /v3/files endpoint into the unified
|
|
5
|
+
* FileUploadAdapter interface.
|
|
6
|
+
*
|
|
7
|
+
* Volcengine returns a file_id that can be used in API messages
|
|
8
|
+
* as a file reference. Files uploaded this way can be referenced in
|
|
9
|
+
* multimodal inputs via the file_id field.
|
|
10
|
+
*/
|
|
11
|
+
import type { FileUploadAdapter, FileUploadResult } from "../file-upload-service.js";
|
|
12
|
+
export interface VolcengineFileUploadConfig {
|
|
13
|
+
/** Base URL (e.g. "https://ark.cn-beijing.volces.com/api") */
|
|
14
|
+
baseUrl: string;
|
|
15
|
+
/** Upload purpose. Default: "user_data". */
|
|
16
|
+
defaultPurpose?: string;
|
|
17
|
+
/** Timeout ms. Default: 120_000. */
|
|
18
|
+
timeoutMs?: number;
|
|
19
|
+
}
|
|
20
|
+
export declare class VolcengineFileUploadAdapter implements FileUploadAdapter {
|
|
21
|
+
private readonly config;
|
|
22
|
+
constructor(config: VolcengineFileUploadConfig);
|
|
23
|
+
uploadFile(buffer: Buffer, filename: string, mimeType: string, apiKey: string, signal?: AbortSignal): Promise<FileUploadResult>;
|
|
24
|
+
}
|