qlogicagent 2.13.9 → 2.13.11
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 +9 -6
- package/dist/cli.js +350 -344
- package/dist/index.js +349 -343
- package/dist/orchestration.js +14 -14
- package/dist/types/agent/agent.d.ts +1 -0
- package/dist/types/agent/tool-loop/completion-action-policy.d.ts +24 -1
- package/dist/types/agent/tool-loop/loop-helpers.d.ts +2 -1
- package/dist/types/agent/types.d.ts +7 -0
- package/dist/types/cli/base-tool-bootstrap.d.ts +2 -0
- package/dist/types/cli/handlers/turn-handler.d.ts +6 -0
- package/dist/types/cli/session-query-service.d.ts +3 -0
- package/dist/types/cli/tool-bootstrap-community-registration.d.ts +6 -0
- package/dist/types/cli/tool-bootstrap-core-registration.d.ts +2 -0
- package/dist/types/cli/tool-bootstrap-media-registration.d.ts +2 -0
- package/dist/types/cli/tool-bootstrap.d.ts +2 -0
- package/dist/types/protocol/wire/gateway-rpc.d.ts +2 -0
- package/dist/types/runtime/community/activity-event-emitter.d.ts +7 -0
- package/dist/types/runtime/community/activity-event.d.ts +3 -1
- package/dist/types/runtime/community/community-consent-client.d.ts +14 -0
- package/dist/types/runtime/community/pet-activity-sink.d.ts +36 -0
- package/dist/types/runtime/config/tunable-defaults.d.ts +3 -0
- package/dist/types/runtime/execution/streaming-tool-executor.d.ts +3 -0
- package/dist/types/runtime/infra/media-persistence.d.ts +17 -0
- package/dist/types/runtime/ports/agent-runtime-ports.d.ts +1 -0
- package/dist/types/runtime/ports/tool-contracts.d.ts +2 -0
- package/dist/types/runtime/prompt/fresh-workspace-evidence.d.ts +1 -0
- package/dist/types/runtime/session/session-transcript-store.d.ts +1 -0
- package/dist/types/runtime/session/session-write-queue.d.ts +1 -0
- package/dist/types/skills/tools/community-seek-tool.d.ts +9 -0
- package/dist/types/skills/tools/file-tool-arguments.d.ts +5 -0
- package/dist/types/skills/tools/image-generate-tool.d.ts +24 -0
- package/dist/types/skills/tools/read-tool.d.ts +2 -0
- package/dist/types/skills/tools/shell/host-paths.d.ts +2 -0
- package/dist/types/skills/tools/team-tool.d.ts +0 -4
- package/dist/vendor/hatch-pet/scripts/prepare_pet_run.py +8 -4
- package/package.json +4 -3
package/dist/orchestration.js
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
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,
|
|
2
|
-
${
|
|
1
|
+
function Ae(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Me(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var Ee=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,y={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Ie=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,ve=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Le=512,Oe=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var we=new Set([500,502,503,504,521,522,523,524,529]),Pe=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ne=["upgrade your plan","upgrade plan","current plan","subscription"],De=["daily","weekly","monthly"],Fe=["try again","retry","temporary","cooldown"],Be=["usage limit","rate limit","organization usage"],Ue=["organization","workspace"],je=["billing period","exceeded","reached","exhausted"],Ge=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,He=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function h(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function $e(e){return h(e,y.format)}function W(e){return h(e,y.rateLimit)}function ze(e){return h(e,y.timeout)}function qe(e){return Ee.test(e)}function E(e){let t=e.toLowerCase();return t?e.length>Le?ve.test(t):h(t,y.billing)?!0:Ie.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function V(e){return h(e,y.authPermanent)}function Ke(e){return h(e,y.auth)}function J(e){return h(e,y.overloaded)}function T(e,t){return t.some(n=>e.includes(n))}function Xe(e){return T(e,Pe)||T(e,Ne)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ye(e){let t=T(e,De),n=e.includes("spend limit")||e.includes("spending limit"),o=T(e,Ue);return T(e,Fe)&&T(e,Be)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||T(e,je))}function We(e){return e.trim().toLowerCase().replace(He,"").trim()}function Z(e){let t=We(e);return!t||Xe(t)?"billing":W(t)||Ye(t)?"rate_limit":"billing"}function Ve(e){return Ge.test(e)?Z(e):null}function Q(e){let t=e.match(Oe);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Je(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Ze(e){let t=e.trim();if(!t)return!1;let n=Q(t);return n?we.has(n.code):!1}function ee(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?Z(t):"billing":e===429?"rate_limit":e===401||e===403?t&&V(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&J(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&E(t)?"billing":"format":null}function Qe(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function et(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function te(e){if(et(e))return"session_expired";if(Qe(e))return"model_not_found";let t=Ve(e);return t||(qe(e)?E(e)?"billing":"rate_limit":W(e)?"rate_limit":J(e)?"overloaded":Ze(e)?Q(e.trim())?.code===529?"overloaded":"timeout":Je(e)?"timeout":$e(e)?"format":E(e)?"billing":ze(e)?"timeout":V(e)?"auth_permanent":Ke(e)?"auth":null)}var tt={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"},nt=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ot(e,t){let n=ee(e,t)??(t?te(t):null);return n?tt[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function rt(e){return nt.has(e)}function B(e){return typeof e.compressAsync=="function"}var ne=4,I=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let u of t)u.role==="system"?o.push(u):r.push(u);let s=n;for(let u of o)s-=this.estimateTokens(u);let i;for(let u of r)if(u.role==="user"){i=u;break}if(i&&(s-=this.estimateTokens(i)),s<=0)return{messages:i?[...o,i]:o,droppedCount:r.length-(i?1:0),strategy:"sliding-window"};let a=[],l=0;for(let u=r.length-1;u>=0;u--){let d=r[u];if(d===i)continue;let p=this.estimateTokens(d);if(s-p<0&&l>=ne)break;if(s-p<0&&l<ne){a.unshift(d),l++;continue}s-=p,a.unshift(d),l++}let c=[...o];return i&&!a.includes(i)&&c.push(i),c.push(...a),{messages:c,droppedCount:r.length-(a.length+(i&&!a.includes(i)?1:0)),strategy:"sliding-window"}}},v=class{constructor(t,n){this.recentCount=t;this.summarize=n}recentCount;summarize;compress(t,n){let o=t.filter(l=>l.role==="system"),r=t.filter(l=>l.role!=="system");if(r.length<=this.recentCount)return{messages:t,droppedCount:0,strategy:"summarize-old"};let s=r.slice(0,r.length-this.recentCount),i=r.slice(r.length-this.recentCount),a=this.summarize(s);return{messages:[...o,{role:"system",content:`[Conversation summary]
|
|
2
|
+
${a}`},...i],droppedCount:s.length,strategy:"summarize-old"}}},L=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(s=>s.role!=="tool"||typeof s.content!="string"||s.content.length<=this.maxToolResultChars?s:(o++,{...s,content:st(s.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function st(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let s=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
|
|
3
3
|
`),n.lastIndexOf(`]
|
|
4
|
-
`));if(
|
|
5
|
-
[...truncated: ${e.length-
|
|
4
|
+
`));if(s>t*.5)return n.slice(0,s+1)+`
|
|
5
|
+
[...truncated: ${e.length-s-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 it(...e){return{compress(t,n){let o=t,r=0,
|
|
9
|
-
`)}var
|
|
8
|
+
[...truncated: ${e.length-t} chars omitted]`}function it(...e){return{compress(t,n){let o=t,r=0,s=[];for(let i of e){let a=i.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}}}}function at(...e){return{compress(t,n){let o=t,r=0,s=[];for(let i of e){let a=i.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&s.push(a.strategy)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none"}},async compressAsync(t,n){let o=t,r=0,s=[],i=0,a=!1,l=!1;for(let c of e){let u=B(c)?await c.compressAsync(o,n):c.compress(o,n);o=u.messages,r+=u.droppedCount,u.droppedCount>0&&s.push(u.strategy),u.metrics&&(i+=u.metrics.latencyMs,a=a||u.metrics.usedLlm,l=l||!!u.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:s.length>0?s.join("+"):"none",metrics:i>0||a?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:i,usedLlm:a,cacheInvalidated:l}:void 0}}}}function U(e,t){let n=e.filter(i=>i.role==="user"),o=e.filter(i=>i.tool_calls!=null),r=e.filter(i=>i.role==="tool"),s=["You are a conversation summarizer. Produce a structured summary of the conversation history below.","","## Instructions","Analyze the conversation and produce a summary with these sections:","","### 1. Primary Objective","What is the user's main goal or task? State it in one sentence.","","### 2. Key Decisions Made","List the important decisions, choices, or conclusions reached during the conversation.","","### 3. Current Progress",`Describe the current state. ${o.length>0?`${o.length} tool calls and ${r.length} tool results were exchanged.`:"No tools were used."}`,"","### 4. Pending Tasks","List any tasks that are in-progress or planned but not yet completed.","","### 5. Important Context","MUST preserve verbatim: IP addresses, file paths, URLs, port numbers, credentials/tokens, specific numeric values, version numbers, proper nouns, identifiers, and any user-provided data points. These MUST appear exactly as stated in the original conversation.","","### 6. All User Messages",`List ALL ${n.length} user messages chronologically, each as 1-2 sentences capturing the core request. Include exact values, identifiers, keywords, or secrets the user mentioned or asked you to remember. Do NOT omit any user message \u2014 every user request must be traceable in this summary.`,"","### 7. Error & Recovery History","Summarize any errors encountered and how they were resolved.","","### 8. User Preferences Expressed","Note any stated preferences about style, approach, or constraints.","","### 9. Technical State","Note file paths, variable names, API endpoints, or configuration values that were discussed.","","### 10. Conversation Flow","Briefly describe the overall flow: what happened first, what changed, where we are now."];return t?.taskContext&&s.push("","## Additional Context",t.taskContext),s.push("","## Conversation to Summarize","",...e.map(i=>{let a=typeof i.content=="string"?i.content:JSON.stringify(i.content??""),l=i.role==="user"?a:a.length>2e3?a.slice(0,2e3)+"...":a;return`[${i.role}]: ${l}`}),"","## Output Format","Respond with a concise summary covering all 10 sections above. Use markdown headers.","Keep the total summary under 1000 words. Focus on actionable information and exact user requests."),s.join(`
|
|
9
|
+
`)}var O=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??S,taskContext:t.taskContext}}compress(t,n){return{messages:t,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:s}=re(t),i=t.reduce((m,g)=>m+this.config.estimateTokens(g),0);if(i<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let a=0,l=0;for(let m=0;m<s.length&&(s[m].role==="user"&&l++,!(l>this.config.protectedHeadExchanges));m++)a=m+1;let c=Math.max(this.config.protectedTailMessages,Math.floor(s.length*.4)),u=Math.max(a,s.length-c);if(u<=a)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let d=s.slice(0,a),p=s.slice(a,u),f=s.slice(u),C=U(p,{taskContext:this.config.taskContext}),k=await this.config.summarize(p,C),A={role:"system",content:`[Conversation summary \u2014 ${p.length} messages compressed]
|
|
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:
|
|
12
|
-
${
|
|
11
|
+
${k}`},_=[...r,...d,A,...f],M=Date.now()-o,b=_.reduce((m,g)=>m+this.config.estimateTokens(g),0);return{messages:_,droppedCount:p.length,strategy:"head-tail-protected",metrics:{tokensBefore:i,tokensAfter:b,compressionRatio:i>0?b/i:1,latencyMs:M,usedLlm:!0,cacheInvalidated:!0}}}},w=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??S}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:s}=re(t),i=r.findIndex(m=>typeof m.content=="string"&&m.content.startsWith("[Conversation summary")),a=i>=0?r[i]:void 0,l=i>=0?[...r.slice(0,i),...r.slice(i+1)]:r,c=Math.max(0,s.length-this.config.preserveRecentCount);if(c<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let u=t.reduce((m,g)=>m+this.config.estimateTokens(g),0);if(u<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=s.slice(0,c),p=s.slice(c),f=a&&typeof a.content=="string"?`Previous summary:
|
|
12
|
+
${a.content}
|
|
13
13
|
|
|
14
14
|
New messages to integrate:`:void 0,C=U(d,{taskContext:f}),k=await this.config.summarize(d,C),A={role:"system",content:`[Conversation summary \u2014 ${d.length} messages compressed]
|
|
15
15
|
|
|
16
|
-
${k}`},_=[...l,A,...p],M=Date.now()-o,b=_.reduce((m,g)=>m+this.config.estimateTokens(g),0);return{messages:_,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:
|
|
17
|
-
`),
|
|
16
|
+
${k}`},_=[...l,A,...p],M=Date.now()-o,b=_.reduce((m,g)=>m+this.config.estimateTokens(g),0);return{messages:_,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:u,tokensAfter:b,compressionRatio:u>0?b/u:1,latencyMs:M,usedLlm:!0,cacheInvalidated:!0}}}},P=class{config;constructor(t){this.config=t}compress(t,n){let o=R(t),r=this.config.inner.compress(t,n),s=R(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}async compressAsync(t,n){let o=R(t),r=B(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),s=R(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}},oe={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function lt(e={}){let t={...oe,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function ct(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var N=class{events=[];maxEvents;constructor(t=100){this.maxEvents=t}record(t){this.events.push(t),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let t=this.events.length;if(t===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let n=0,o=0,r=0,s=0,i=0;for(let a of this.events)n+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,o+=a.latencyMs,r+=Math.max(0,a.tokensBefore-a.tokensAfter),a.usedLlm&&s++,a.cacheInvalidated&&i++;return{totalCompressions:t,totalLlmCalls:s,totalCacheInvalidations:i,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},D=class{engines=new Map;activeId;register(t){this.engines.set(t.id,t)}activate(t){return this.engines.has(t)?(this.activeId=t,!0):!1}getActive(){return this.activeId?this.engines.get(this.activeId):void 0}listEngines(){return Array.from(this.engines.values()).map(t=>({id:t.id,label:t.label,active:t.id===this.activeId}))}};function re(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function S(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function R(e){let t=Math.min(e.length,5),n=[];for(let o=0;o<t;o++){let r=e[o],s=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${s}`)}return n.join("|")}var ut=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),F=class{constructor(t=20,n=S){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=t.length-this.preserveRecentCount,r=0,s=0;return{messages:t.map((a,l)=>{if(l>=o||a.role!=="tool"||typeof a.content!="string"||!a.name||!ut.has(a.name)||a.content.length<=200)return a;let c=this.estimateTokens(a);return s+=c,r++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function pt(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let s=r.function?.name??"";if(/read|edit|write|file/i.test(s)&&r.function?.arguments)try{let i=JSON.parse(r.function.arguments),a=i.path??i.filePath??i.file_path??i.file;a&&typeof a=="string"&&t.set(a,n)}catch{}}o.role==="tool"&&o.name&&/read|edit|write|file/i.test(o.name)}return[...t.entries()].sort((n,o)=>o[1]-n[1]).map(([n])=>n)}async function dt(e,t,n){let o=n.estimateTokens??(p=>Math.ceil(p.length/4)),r=pt(t);if(r.length===0)return e;let s=e.map(p=>typeof p.content=="string"?p.content:"").join(`
|
|
17
|
+
`),i=r.filter(p=>!s.includes(p));if(i.length===0)return e;let a=n.maxTokenBudget,l=[],c=0;for(let p of i){if(c>=n.maxFiles||a<=0)break;let f=await n.readFile(p);if(!f)continue;let C=o(f);C>a||(a-=C,c++,l.push({role:"system",content:`[Post-compact file recovery: ${p}]
|
|
18
18
|
|
|
19
|
-
${f}`}))}if(l.length===0)return e;let
|
|
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(H(e,t.name,"SKILL.md"))).length}catch{return 0}}function At(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<le||e.distinctToolCount<ce||Date.now()-ye<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)?(ye=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function _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 Dt(e,t){return{...e,content:[...be(e.content),...be(t.content)]}}function Ft(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 $(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=>Ft(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]=Dt(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=$(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 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 $t(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 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 Xt(e){let t=[],n=$(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=z(n,e.options);o.some((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:Ht(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:$t(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 Qn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Qt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var K=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var X="<fork-child-context>",ke="Fork started \u2014 processing in background";function en(e){return JSON.stringify(e).includes(X)}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 u=[...e],d=-1;for(let p=0;p<u.length;p++)u[p].role==="system"&&(d=p);return u.splice(d+1,0,...l),u}function mt(e,t,n=S){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of e){let l=a.tool_call_id??"";if(l&&t.has(l)){o+=n(a),r++,t.delete(l);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}function ft(){return{stages:[]}}function gt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=se(e,t),i=yt(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=se(e,t),{messages:s,stagedCount:i.length}}function Tt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:ie(e,t),committed:n}}function se(e,t){return t.stages.filter(o=>o.committed).length===0?e:ie(e,t)}function ie(e,t){let n=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),o=[...e];for(let r of n){let[s,i]=r.range;if(s>=o.length)continue;let a=Math.min(i,o.length),l={role:"system",content:r.summary};o.splice(s,a-s,l)}return o}function yt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,a=0;for(let l=0;l<o;l++){let c=e[l];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")i<0&&(i=l),a++;else{if(a>=3){let d=`${i}-${i+a}`;s.has(d)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let l=`${i}-${i+a}`;s.has(l)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{existsSync as G,readFileSync as fe,writeFileSync as ht,readdirSync as ge,mkdirSync as Ct}from"node:fs";import{join as H,dirname as _t}from"node:path";var Fn=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Bn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var ae=20;var le=3,ce=2,ue=300*1e3,pe=3,de=720*60*60*1e3;var Un=300*1e3,j=4;var jn=3600*1e3;var Gn=50*1024,Hn=500*1024,$n=500*1024*1024,zn=50*1024*1024;var qn=60*1024;var Te=0;var bt="skill-patterns.json";function ye(e){return H(e,".qlogicagent",bt)}function he(e){let t=ye(e);try{return JSON.parse(fe(t,"utf8"))}catch{return{version:1,patterns:{}}}}function me(e,t){let n=ye(e);Ct(_t(n),{recursive:!0}),ht(n,JSON.stringify(t,null,2),"utf8")}function Rt(e){let t=Date.now()-de;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function Ce(e,t){if(t.length===0)return!1;let n=x(t),o=he(e);Rt(o);let r=new Date().toISOString(),s=o.patterns[n];if(s||(s={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=s),s.promoted)return me(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=pe;return i&&(s.promoted=!0),me(e,o),i}function St(e){let t=he(e);return Object.values(t.patterns)}function x(e){return[...e].sort().join("+")}function xt(e,t){if(!G(t))return null;let n=x(e);try{let o=ge(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let s=H(t,r.name,"SKILL.md");try{let a=fe(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let l=a[1].split(`
|
|
20
|
+
`).map(c=>c.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(x(l)===n)return r.name}}catch{}}}catch{}return null}function kt(e){if(!G(e))return 0;try{return ge(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&G(H(e,t.name,"SKILL.md"))).length}catch{return 0}}function At(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<le||e.distinctToolCount<ce||Date.now()-Te<ue||t?.projectSkillsDir&&(kt(t.projectSkillsDir)>=ae||t.tools.length>0&&xt(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Ce(t.projectRoot,t.tools))}function Mt(e){return e.existingSkillName?e.feedback==="negative":!1}function Et(e,t){return Mt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:At(e,t)?(Te=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function _e(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function It(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function vt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Lt(e){if(!e.eligibility?.length)return[...e.tools];let t=vt(e.eligibility);return e.tools.filter(n=>{let o=_e(n);if(!o)return!1;let r=t.get(o);return!r||It(r.status)})}function Ot(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function wt(e){let t=Ot({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Lt({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(l=>_e(l)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Pt=["stop","aborted","timeout","cancelled","interrupted","error"],Nt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function be(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Dt(e,t){return{...e,content:[...be(e.content),...be(t.content)]}}function Ft(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function Bt(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let s=Ft(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(n.push(a),t.add(i))}}return n}function Ut(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function jt(e){return new Set((e??Pt).map(t=>t.trim().toLowerCase()))}function Re(e,t){return e?jt(t).has(e.trim().toLowerCase()):!1}function Gt(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function $(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(l=>{if(l.role==="assistant"&&Array.isArray(l.tool_calls)){let c=l.tool_calls.filter(u=>Ut(u));return{...l,...c.length>0?{tool_calls:c}:{tool_calls:void 0}}}return{...l}}),n=new Set;for(let l of t)if(!(l.role!=="assistant"||!Array.isArray(l.tool_calls)))for(let c of l.tool_calls)typeof c.id=="string"&&c.id&&n.add(c.id);let o=t.filter(l=>l.role!=="tool"?!0:!!(l.tool_call_id&&n.has(l.tool_call_id))),r=new Set;for(let l of o)l.role==="tool"&&typeof l.tool_call_id=="string"&&l.tool_call_id&&r.add(l.tool_call_id);let s=[];for(let l of o){if(l.role==="assistant"&&Array.isArray(l.tool_calls)&&l.tool_calls.length>0){let c=l.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(c.length===0){let{tool_calls:u,...d}=l;d.content!=null&&d.content!==""&&s.push(d);continue}if(c.length<l.tool_calls.length){s.push({...l,tool_calls:c});continue}}s.push(l)}let i=Bt(s),a=[];for(let l of i){let c=a.length>0?a[a.length-1]:void 0;if(l.role==="user"&&c?.role==="user"){a[a.length-1]=Dt(c,l);continue}a.push(l)}return a}function z(e,t){return Re(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Nt)delete o[r];return o}):[...e]}function q(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function Ht(e,t){let n=$(e),o=z(n,t);return q(o,t)}function Se(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=Re(t?.stopReason,t?.forcedStopReasons),r=[];for(let c=0;c<e.length;c+=1){let u=e[c];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(c+1).some(f=>f&&typeof f=="object"&&f.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let d={...u};if(typeof d.id=="string"){let p=Gt(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let s=new Set,i=new Map;for(let c of r){if(c.type!=="function_call")continue;let u=typeof c.call_id=="string"&&c.call_id?c.call_id:typeof c.id=="string"?c.id:void 0;u&&(s.add(u),i.set(u,c))}let a=new Set,l=[];for(let c of r)if(!(o&&c.type==="function_call")){if(c.type==="function_call_output"){let u=typeof c.call_id=="string"?c.call_id:"";if(!u||!s.has(u))continue;a.add(u)}l.push(c)}for(let[c]of i)a.has(c)||o||l.push({type:"function_call_output",call_id:c,output:n});return l}function $t(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function zt(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function qt(e){let t=new Set,n=new Set;for(let o of e){if(o.type==="function_call"){let r=typeof o.call_id=="string"&&o.call_id?o.call_id:typeof o.id=="string"?o.id:"";r&&t.add(r)}o.type==="function_call_output"&&typeof o.call_id=="string"&&o.call_id&&n.add(o.call_id)}return[...t].filter(o=>!n.has(o))}function Kt(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function xe(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Xt(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Yt(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Wt(e){let t=[],n=$(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=z(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=q(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:$t(r),completedToolCallIds:zt(r)}),recoveryActions:t}}function Vt(e){let t=Se(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:xe({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:qt(t),completedToolCallIds:Kt(t)}),recoveryActions:n}}var Jt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Zt(e){return e?Jt.has(e):!0}function Qt(e){return e===429||e===529}function en(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var no={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function tn(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var K=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var X="<fork-child-context>",ke="Fork started \u2014 processing in background";function nn(e){return JSON.stringify(e).includes(X)}function on(e){return e<j}function rn(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
|
|
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:`${X}
|
|
24
24
|
|
|
25
25
|
You are the "${t.agent.name}" agent.${o}
|
|
26
26
|
|
|
27
|
-
${t.taskPrompt}`}]};return n.push(r),n}function
|
|
27
|
+
${t.taskPrompt}`}]};return n.push(r),n}function sn(e){return e.map(t=>({role:"tool",tool_call_id:t,content:ke}))}function an(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolCapabilityProfile==="no_tools")return[];if(t.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent"&&n!=="team")}function ln(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var cn={name:"general",label:"General Purpose",description:"A general-purpose sub-agent that can perform any task with full tool access.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!1},un={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolCapabilityProfile:"read_tools",allowedTools:["read_file","search","web_search","web_fetch","memory","tool_search"],canFork:!1,systemPromptSuffix:"You are READ-ONLY: never attempt to modify files or run mutating commands. Locate and understand code, then report concrete findings with file:line references. Read excerpts rather than whole files; surface conclusions, not raw dumps."},pn={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolCapabilityProfile:"read_tools",allowedTools:["read_file","search","web_search","web_fetch","memory","task","tool_search"],canFork:!1,systemPromptSuffix:"You PLAN but do not execute: never write files or run commands. Investigate enough to ground the plan in the real code, then return a concrete, step-by-step implementation plan naming the specific files and changes involved."},dn={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!0,systemPromptSuffix:"Implement the task directly by editing files. Read existing code before changing it, match the surrounding conventions, and verify your change compiles/passes where possible."},mn={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolCapabilityProfile:"read_tools",allowedTools:["web_search","web_fetch","read_file","search","memory"],canFork:!1,systemPromptSuffix:"Gather information from multiple sources before concluding. Distinguish facts from inferences, cite where each claim comes from, and synthesize \u2014 do not just dump search results."},fn={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolCapabilityProfile:"all_tools",allowedTools:["exec","read_file","search"],canFork:!1,systemPromptSuffix:"Verify by RUNNING things (tests, builds, type-checks) and reading the actual output \u2014 do not assume. Report a clear verdict (pass/fail) with the evidence that supports it."},Y=[cn,un,pn,dn,mn,fn];function gn(){return[...Y]}function Tn(e){return Y.find(t=>t.name===e)}function yn(e){return Y.some(t=>t.name===e)}function hn(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolCapabilityProfile==="no_tools")return[];if(e.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(o=>!n.has(o))}return e.canFork?[...t]:t.filter(n=>n!=="agent"&&n!=="team")}var Cn=new Set(["agent_tool","team","fork_agent"]);function _n(e,t){switch(e){case"worker":return t.filter(n=>!Cn.has(n));case"coordinator":return[...t];default:return[...t]}}function bn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function Rn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Sn(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function xn(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function kn(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function An(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Mn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function En(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
|
|
28
28
|
${n.join(`
|
|
29
29
|
`)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
|
|
30
30
|
Step ${e.activeSkillContext.step}:
|
|
@@ -35,4 +35,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
|
|
|
35
35
|
|
|
36
36
|
${t.join(`
|
|
37
37
|
|
|
38
|
-
`)}`}function
|
|
38
|
+
`)}`}function In(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function vn(e,t=Mn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}export{P as CacheAwareCompressionStrategy,N as CompressionMetricsCollector,D as ContextEngineRegistry,oe as DEFAULT_ADAPTIVE_BUDGET_CONFIG,ke as FORK_PLACEHOLDER_RESULT,X as FORK_SENTINEL_TAG,K as FallbackTriggeredError,O as HeadTailProtectedStrategy,w as IncrementalCompactStrategy,j as MAX_FORK_DEPTH,F as MicroCompactStrategy,I as SlidingWindowStrategy,v as SummarizeOldStrategy,L as ToolResultTrimStrategy,Xt as advanceToolLoopState,gt as applyContextCollapsesIfNeeded,wt as applyToolChoicePolicy,Ae as buildAssistantToolCallMessage,sn as buildForkPlaceholderResults,rn as buildForkedMessages,En as buildPostCompactRestorationMessage,Et as buildSkillInstruction,U as buildStructuredSummaryPrompt,Me as buildToolResultMessage,x as buildToolSignature,Sn as calculateTokenWarningState,on as canForkAtDepth,ot as classifyError,at as composeAsyncStrategies,it as composeStrategies,lt as computeAdaptiveBudget,en as computeRetryBackoff,ft as createCollapseStore,In as createReactiveCompactState,bn as createTaskState,Rn as createTurnLoopGuardState,_n as filterToolsByRole,ln as generateForkChildAgentId,Tn as getBuiltInAgent,gn as getBuiltInAgents,St as getPatternStats,B as isAsyncCompressionStrategy,yn as isBuiltInAgent,Zt as isForegroundSource,nn as isInForkChild,tn as isPersistentRetryEnabled,rt as isRetryableCategory,Qt as isTransientCapacityError,dt as postCompactFileRecovery,Ce as recordPatternAndCheckThreshold,Tt as recoverContextCollapseFromOverflow,Wt as recoverToolLoopStateFromChatConversation,Vt as recoverToolLoopStateFromResponsesItems,Ht as repairOpenAiChatConversation,hn as resolveAgentToolSet,xn as resolveApiErrorRecovery,an as resolveForkChildTools,kn as resolveOutputTokenEscalation,ct as selectCompressionTier,Yt as settleToolLoopState,An as shouldAbortTurn,vn as shouldAttemptReactiveCompact,mt as snipCompactIfNeeded};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AgentLogger, ChatMessage, ThinkingBlock, ToolLoopTransition } from "../types.js";
|
|
2
|
-
export type CompletionActionPolicyReason = "file_action_verification" | "multi_file_skeleton_verification";
|
|
2
|
+
export type CompletionActionPolicyReason = "file_action_verification" | "explicit_required_file_verification" | "final_marker_verification" | "multi_file_skeleton_verification";
|
|
3
3
|
export interface CompletionActionPolicyInput {
|
|
4
4
|
inputMessages: readonly ChatMessage[];
|
|
5
5
|
messages: unknown[];
|
|
@@ -16,4 +16,27 @@ export interface CompletionActionPolicyDecision {
|
|
|
16
16
|
stopHookActive: true;
|
|
17
17
|
transition: ToolLoopTransition;
|
|
18
18
|
}
|
|
19
|
+
export declare function findMissingExplicitRequiredFiles(inputMessages: readonly ChatMessage[], messages: unknown[]): string[];
|
|
20
|
+
export declare function buildExplicitRequiredFilesFailureContent(input: {
|
|
21
|
+
inputMessages: readonly ChatMessage[];
|
|
22
|
+
messages: unknown[];
|
|
23
|
+
reason: string;
|
|
24
|
+
}): string | undefined;
|
|
25
|
+
export declare function buildMissingFinalMarkerFailureContent(input: {
|
|
26
|
+
inputMessages: readonly ChatMessage[];
|
|
27
|
+
reason: string;
|
|
28
|
+
}): string | undefined;
|
|
29
|
+
type CandidateToolCall = {
|
|
30
|
+
id: string;
|
|
31
|
+
function: {
|
|
32
|
+
name: string;
|
|
33
|
+
arguments: string;
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
export declare function buildPrematureCompletionArtifactBlock(input: {
|
|
37
|
+
inputMessages: readonly ChatMessage[];
|
|
38
|
+
messages: unknown[];
|
|
39
|
+
toolCall: CandidateToolCall;
|
|
40
|
+
}): string | undefined;
|
|
19
41
|
export declare function resolveCompletionActionPolicy(input: CompletionActionPolicyInput): CompletionActionPolicyDecision | null;
|
|
42
|
+
export {};
|
|
@@ -4,7 +4,8 @@ export declare function isEmptyToolResult(r: {
|
|
|
4
4
|
message: unknown;
|
|
5
5
|
}): boolean;
|
|
6
6
|
export declare function findLastToolError(messages: unknown[], _toolName: string): string | undefined;
|
|
7
|
-
export declare function resolveToolLoopBudget(requested?: number): number;
|
|
7
|
+
export declare function resolveToolLoopBudget(requested?: number, messages?: readonly ChatMessage[]): number;
|
|
8
|
+
export declare function resolveTotalToolCallBudget(requested?: number, messages?: readonly ChatMessage[]): number;
|
|
8
9
|
export declare function filterWhitespaceOnlyAssistant<T extends {
|
|
9
10
|
role: string;
|
|
10
11
|
content?: unknown;
|
|
@@ -84,6 +84,13 @@ export interface TurnRequest {
|
|
|
84
84
|
config?: TurnConfig;
|
|
85
85
|
}
|
|
86
86
|
export interface TurnConfig {
|
|
87
|
+
/**
|
|
88
|
+
* Model purpose to resolve from the registry for this turn.
|
|
89
|
+
* Defaults to textGeneration. Focused media-understanding turns can override
|
|
90
|
+
* this so the main loop uses a vision/video model instead of a text model
|
|
91
|
+
* trying to fetch media URLs as plain text.
|
|
92
|
+
*/
|
|
93
|
+
modelPurpose?: "textGeneration" | "imageUnderstanding" | "videoUnderstanding";
|
|
87
94
|
/** LLM provider id, e.g. "deepseek" */
|
|
88
95
|
provider?: string;
|
|
89
96
|
/** Model id, e.g. "deepseek-v4-flash" */
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import type { NotificationMethod, NotificationMethodMap } from "../protocol/notifications.js";
|
|
2
2
|
import type { ToolBootstrap } from "../runtime/ports/index.js";
|
|
3
|
+
import type { MediaPersistence } from "../runtime/infra/media-persistence.js";
|
|
3
4
|
import type { ModelPurpose } from "../runtime/infra/model-registry.js";
|
|
4
5
|
import type { LLMTransport } from "./provider-core-facade.js";
|
|
5
6
|
export interface BaseToolBootstrapDeps {
|
|
6
7
|
verbose: boolean;
|
|
7
8
|
toolBootstrap: ToolBootstrap;
|
|
9
|
+
mediaPersistence?: MediaPersistence;
|
|
8
10
|
log(message: string): void;
|
|
9
11
|
sendNotification<M extends NotificationMethod>(method: M, params: NotificationMethodMap[M]): void;
|
|
10
12
|
resolveClientForPurpose?(purpose: ModelPurpose): {
|
|
@@ -17,6 +17,12 @@ export interface TurnControlHandlerHost {
|
|
|
17
17
|
log(message: string): void;
|
|
18
18
|
sendResponse(id: string | number, result?: unknown, error?: unknown): void;
|
|
19
19
|
}
|
|
20
|
+
export declare function hydrateAttachmentReferenceUrlsForTurn(messages: ChatMessage[]): ChatMessage[];
|
|
21
|
+
export declare function activateAttachmentToolsForTurn(toolCatalog: ToolCatalog, messages: ChatMessage[]): string[];
|
|
22
|
+
export declare function getFocusedAttachmentToolNamesForTurn(messages: ChatMessage[]): Set<string> | null;
|
|
23
|
+
type FocusedAttachmentModelPurpose = "imageUnderstanding" | "videoUnderstanding";
|
|
24
|
+
export declare function getFocusedAttachmentUnsupportedContentForTurn(messages: ChatMessage[], purpose: FocusedAttachmentModelPurpose): string | null;
|
|
25
|
+
export declare function getFocusedAttachmentModelPurposeForTurn(messages: ChatMessage[]): FocusedAttachmentModelPurpose | null;
|
|
20
26
|
export declare function refreshPermissionCheckerToolMeta(permissionChecker: PermissionMetadataResolver | null | undefined, tools: ToolDefinition[]): void;
|
|
21
27
|
export declare function handleUserResponse(this: TurnControlHandlerHost, msg: AgentRpcRequest): void;
|
|
22
28
|
export interface TurnPipelineInput {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { SessionLocator } from "../runtime/session/session-locator.js";
|
|
2
|
+
import type { SessionListEntry } from "../runtime/session/session-types.js";
|
|
2
3
|
export interface SessionWorkspaceHost {
|
|
3
4
|
getActiveProjectRoot(): string;
|
|
4
5
|
}
|
|
@@ -19,6 +20,8 @@ export declare class SessionQueryService {
|
|
|
19
20
|
getProjectWorkspaceDir(projectId: string): string;
|
|
20
21
|
resolveWorkspaceDir(sessionId: string, projectId?: string): string;
|
|
21
22
|
listThreads(limit: number, projectId?: string): Promise<ThreadListItem[]>;
|
|
23
|
+
getHostSessionWorkspaceDirs(host: SessionWorkspaceHost, excludedDirs?: string[]): string[];
|
|
24
|
+
listHostWorkspaceSessions(host: SessionWorkspaceHost, limit: number, excludedDirs?: string[]): Promise<SessionListEntry[]>;
|
|
22
25
|
resolveSessionWorkspaceDir(host: SessionWorkspaceHost, sessionId: string, projectId?: string): string;
|
|
23
26
|
}
|
|
24
27
|
export declare function safeSessionId(sessionId: string): string;
|
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
import type { PortableTool } from "../skills/portable-tool.js";
|
|
2
|
+
import { type CommunitySeekAnswerCandidate } from "../skills/tools/community-seek-tool.js";
|
|
2
3
|
import { type CommunityDiscoveryResult } from "../runtime/community/community-discovery-coordinator.js";
|
|
4
|
+
import { type PetActivitySink } from "../runtime/community/pet-activity-sink.js";
|
|
3
5
|
export interface LocalCommunityToolRegistrationContext {
|
|
4
6
|
tools: PortableTool<any>[];
|
|
5
7
|
/** 测试可注入的发现实现;默认从 env consent client 构造协调器。 */
|
|
6
8
|
discover?: (intent: string) => Promise<CommunityDiscoveryResult>;
|
|
9
|
+
/** 测试可注入的经验答案源;默认经 consent client 调 hub /reviews/search(bge-m3 语义检索)。 */
|
|
10
|
+
findAnswers?: (intent: string, topK: number) => Promise<CommunitySeekAnswerCandidate[]>;
|
|
11
|
+
/** 测试可注入的活动发射 sink;默认从 env 解析 actorPetId 构造(无身份→null,不发)。 */
|
|
12
|
+
petActivitySink?: PetActivitySink | null;
|
|
7
13
|
}
|
|
8
14
|
export declare const localCommunityToolRegistrationModule: import("../runtime/ports/tool-contracts.js").ToolRegistrationModule<LocalCommunityToolRegistrationContext>;
|
|
9
15
|
export declare function registerLocalCommunityTools(context: LocalCommunityToolRegistrationContext): void;
|
|
@@ -9,7 +9,9 @@ export interface LocalCoreToolRegistrationContext {
|
|
|
9
9
|
tools: PortableTool<any>[];
|
|
10
10
|
taskToolHooks?: TaskToolHooks;
|
|
11
11
|
backgroundTaskRuntime: BackgroundTaskManager | null;
|
|
12
|
+
getBackgroundTaskRuntime?: () => BackgroundTaskManager | null;
|
|
12
13
|
askUserCallback: ((questions: AskUserQuestion[]) => Promise<Record<string, string> | null>) | null;
|
|
14
|
+
getAskUserCallback?: () => ((questions: AskUserQuestion[]) => Promise<Record<string, string> | null>) | null;
|
|
13
15
|
onExecProgress?: (progress: ExecProgress) => void;
|
|
14
16
|
getCwd(): string;
|
|
15
17
|
activeProjectRoot(): string;
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import type { PortableTool } from "../skills/portable-tool.js";
|
|
2
|
+
import type { MediaPersistence } from "../runtime/infra/media-persistence.js";
|
|
2
3
|
export interface LocalMediaToolRegistrationContext {
|
|
3
4
|
tools: PortableTool<any>[];
|
|
4
5
|
getCwd(): string;
|
|
5
6
|
activeProjectRoot(): string;
|
|
7
|
+
mediaPersistence?: MediaPersistence;
|
|
6
8
|
}
|
|
7
9
|
export declare const localMediaToolRegistrationModule: import("../runtime/ports/tool-contracts.js").ToolRegistrationModule<LocalMediaToolRegistrationContext>;
|
|
8
10
|
export declare function registerLocalMediaTools(context: LocalMediaToolRegistrationContext): void;
|
|
@@ -4,6 +4,7 @@ import type { TaskToolHooks } from "../skills/tools/task-tool.js";
|
|
|
4
4
|
import type { ExecProgress } from "../skills/tools/exec-tool.js";
|
|
5
5
|
import type { BackgroundTaskManager } from "../runtime/infra/background-tasks.js";
|
|
6
6
|
import type { ModelPurpose } from "../runtime/infra/model-registry.js";
|
|
7
|
+
import type { MediaPersistence } from "../runtime/infra/media-persistence.js";
|
|
7
8
|
import type { LLMTransport } from "./provider-core-facade.js";
|
|
8
9
|
import type { AgentLogger } from "../agent/types.js";
|
|
9
10
|
import type { AskUserQuestion } from "../skills/tools/ask-user-tool.js";
|
|
@@ -42,6 +43,7 @@ export interface BootstrapConfig {
|
|
|
42
43
|
workdir?: string;
|
|
43
44
|
toolCatalog?: ToolCatalog;
|
|
44
45
|
pathService?: PathService;
|
|
46
|
+
mediaPersistence?: MediaPersistence;
|
|
45
47
|
log?: AgentLogger;
|
|
46
48
|
/** Called during foreground shell execution with incremental progress. */
|
|
47
49
|
onExecProgress?(progress: ExecProgress): void;
|
|
@@ -124,6 +124,7 @@ export interface GatewayRpcMethodMap {
|
|
|
124
124
|
groupKey?: string;
|
|
125
125
|
groupPlatform?: string;
|
|
126
126
|
lastActiveAt?: string;
|
|
127
|
+
messageCount: number;
|
|
127
128
|
pinnedAt?: string | null;
|
|
128
129
|
archivedAt?: string | null;
|
|
129
130
|
projectId: string;
|
|
@@ -142,6 +143,7 @@ export interface GatewayRpcMethodMap {
|
|
|
142
143
|
groupKey?: string;
|
|
143
144
|
groupPlatform?: string;
|
|
144
145
|
lastActiveAt?: string;
|
|
146
|
+
messageCount?: number;
|
|
145
147
|
pinnedAt?: string | null;
|
|
146
148
|
archivedAt?: string | null;
|
|
147
149
|
} | null;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type ActivityEvent, type CreateActivityEventInput } from "./activity-event.js";
|
|
2
2
|
import { type CommunityConsentClient } from "./community-consent-client.js";
|
|
3
|
+
import type { ConfigPort } from "../ports/index.js";
|
|
3
4
|
export type ActivityEmitStatus = "emitted" | "disabled" | "consent-blocked" | "failed";
|
|
4
5
|
/** 活动事件出口:真实实现把事件写入 community-service(社交通道,非权威)。 */
|
|
5
6
|
export interface ActivityEventTransport {
|
|
@@ -22,3 +23,9 @@ export declare function createHubActivityTransport(client: Pick<CommunityConsent
|
|
|
22
23
|
* 无 token(dev)→ client null → transport null(emit 返回 "disabled",fail-safe)。
|
|
23
24
|
*/
|
|
24
25
|
export declare function createDefaultActivityEventEmitter(): ActivityEventEmitter;
|
|
26
|
+
/**
|
|
27
|
+
* 解析本 agent 自己的 actorPetId = derivePetKey(owner, device)(Cut7/#1)。
|
|
28
|
+
* owner=QLOGIC_LLMROUTER_USER_ID、device=QLOGIC_LLMROUTER_DEVICE_ID(gateway 经 buildQlogicagentLlmrouterEnv 注入)。
|
|
29
|
+
* 缺料(未登录/dev)→ null:调用方应跳过发射(fail-soft,绝不因社交写挂任务)。
|
|
30
|
+
*/
|
|
31
|
+
export declare function resolveSelfActorPetId(configPort?: ConfigPort): string | null;
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
export type TrustSignalEventType = "installed" | "success" | "fail" | "error" | "kept" | "uninstalled" | "endorse";
|
|
2
2
|
export type ExperientialEventType = "acquire" | "ask" | "answer" | "encounter" | "review";
|
|
3
3
|
export type FlauntEventType = "unlock" | "flaunt";
|
|
4
|
-
|
|
4
|
+
/** 浏览/搜索族(Cut7/M5:agent 搜资源 → 宠物到该区"逛")。非 trust-signal;community 可见走 encounter 闸。 */
|
|
5
|
+
export type BrowseEventType = "search";
|
|
6
|
+
export type ActivityEventType = TrustSignalEventType | ExperientialEventType | FlauntEventType | BrowseEventType;
|
|
5
7
|
/**
|
|
6
8
|
* 空间锚点:agent 发射时本就持有 resourceId 与其 category,事件自带锚点让集市
|
|
7
9
|
* 端零反查地把微动画钉到正确街区 / 店铺。**只允许 districtId / shopId。**
|
|
@@ -42,6 +42,8 @@ export interface CommunityConsentClient {
|
|
|
42
42
|
emitActivity?(event: ActivityEvent): Promise<void>;
|
|
43
43
|
/** Cut4: author an agent review for a resource (social channel). Optional for mocks. */
|
|
44
44
|
recordCommunityReview?(input: CommunityReviewInput): Promise<void>;
|
|
45
|
+
/** Cut4: semantic-search peer agent experiences (bge-m3 over community_review) → community_seek answer family. Optional for mocks. */
|
|
46
|
+
findReviewAnswers?(query: string, topK?: number): Promise<CommunityReviewAnswer[]>;
|
|
45
47
|
/** Cut4: post a help request to the community (social channel). Optional for mocks. */
|
|
46
48
|
recordCommunityAsk?(input: CommunityAskInput): Promise<void>;
|
|
47
49
|
/** Cut4: answer a peer's help request (social channel). Optional for mocks. */
|
|
@@ -89,6 +91,8 @@ export interface CommunityRegistryMatchResult {
|
|
|
89
91
|
type: string;
|
|
90
92
|
title: string;
|
|
91
93
|
summary: string;
|
|
94
|
+
/** RESOURCE_CATEGORIES key(search 表演锚点;hub match 返回 ResourceView.category)。 */
|
|
95
|
+
category: string | null;
|
|
92
96
|
capabilityTags: string[];
|
|
93
97
|
sourceTier: CommunityInstallSourceTier;
|
|
94
98
|
trustStage: CommunityInstallTrustStage;
|
|
@@ -134,6 +138,16 @@ export interface CommunityReviewInput {
|
|
|
134
138
|
contextCategory?: string;
|
|
135
139
|
ts: number;
|
|
136
140
|
}
|
|
141
|
+
/** Cut4 经验答案(community_seek 答案族源):hub /reviews/search 的 bge-m3 语义检索结果。 */
|
|
142
|
+
export interface CommunityReviewAnswer {
|
|
143
|
+
id: string;
|
|
144
|
+
resourceId: string;
|
|
145
|
+
actorPetId: string;
|
|
146
|
+
experience: string;
|
|
147
|
+
outcome: "success" | "fail" | "neutral";
|
|
148
|
+
contextCategory: string | null;
|
|
149
|
+
ts: number;
|
|
150
|
+
}
|
|
137
151
|
/** Cut4 求助频道:agent 发求助帖。question 须已脱敏(R24)。 */
|
|
138
152
|
export interface CommunityAskInput {
|
|
139
153
|
id: string;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type ActivityEventType, type ActivitySpatialAnchor } from "./activity-event.js";
|
|
2
|
+
import { type ActivityEmitStatus, type ActivityEventEmitter } from "./activity-event-emitter.js";
|
|
3
|
+
import { type CommunityConsentClient } from "./community-consent-client.js";
|
|
4
|
+
import type { ConfigPort } from "../ports/config-port.js";
|
|
5
|
+
/** 一条要发射的活动:类型 + 空间锚点(街区/店铺)+ 可选对端 + 敏感度。actorPetId/ts/id 由 sink 注入。 */
|
|
6
|
+
export interface PetActivityInput {
|
|
7
|
+
type: ActivityEventType;
|
|
8
|
+
anchor?: ActivitySpatialAnchor;
|
|
9
|
+
peerRef?: string;
|
|
10
|
+
/** 高敏感内容 → 升级问人,不自动外发(DR3);默认 false。 */
|
|
11
|
+
highSensitivity?: boolean;
|
|
12
|
+
}
|
|
13
|
+
export type PetActivityEmitStatus = ActivityEmitStatus | "escalate";
|
|
14
|
+
export interface PetActivitySink {
|
|
15
|
+
/** 发一条活动事件。绝不抛(任何失败都 best-effort 吞掉)。 */
|
|
16
|
+
emit(input: PetActivityInput): Promise<PetActivityEmitStatus>;
|
|
17
|
+
}
|
|
18
|
+
export interface PetActivitySinkDeps {
|
|
19
|
+
actorPetId: string;
|
|
20
|
+
consent: Pick<CommunityConsentClient, "getConsent">;
|
|
21
|
+
emitter: ActivityEventEmitter;
|
|
22
|
+
now: () => number;
|
|
23
|
+
newId: () => string;
|
|
24
|
+
}
|
|
25
|
+
/** 纯逻辑 sink(可注入,供测试)。游历闸定 visibility,emitter 落库。 */
|
|
26
|
+
export declare function createPetActivitySink(deps: PetActivitySinkDeps): PetActivitySink;
|
|
27
|
+
/**
|
|
28
|
+
* 由 (owner,device) 派生本 agent 自家宠物的 actorPetId。env 由 gateway 注入。
|
|
29
|
+
* 缺 owner/device(dev / 未登录)→ null(无身份不发,fail-safe)。
|
|
30
|
+
*/
|
|
31
|
+
export declare function resolveActorPetId(configPort?: ConfigPort): string | null;
|
|
32
|
+
/**
|
|
33
|
+
* 默认 sink:从 env 解析 actorPetId + 构造 consent/transport。
|
|
34
|
+
* 无身份 / 无 token(dev)→ null(调用方 ?.emit 即 no-op,fail-safe 不发)。
|
|
35
|
+
*/
|
|
36
|
+
export declare function createDefaultPetActivitySink(configPort?: ConfigPort): PetActivitySink | null;
|
|
@@ -23,6 +23,8 @@ export declare const DEFAULT_TEMPERATURE = 0;
|
|
|
23
23
|
export declare const MAX_TOOL_BUDGET_CAP = 100;
|
|
24
24
|
/** Default tool budget per round. Overridable via TOOL_LOOP_DEFAULT_BUDGET env. */
|
|
25
25
|
export declare const DEFAULT_TOOL_BUDGET: number;
|
|
26
|
+
/** Foreground tool execution deadline in ms. Long jobs should use background tasks. */
|
|
27
|
+
export declare const DEFAULT_TOOL_EXECUTION_TIMEOUT_MS: number;
|
|
26
28
|
/** Max consecutive tool call failures before early exit. */
|
|
27
29
|
export declare const MAX_CONSECUTIVE_FAILURES = 3;
|
|
28
30
|
/** Max times the exact same (tool_name, arguments) pair can repeat. */
|
|
@@ -179,6 +181,7 @@ export interface TunableDefaults {
|
|
|
179
181
|
defaultTemperature: number;
|
|
180
182
|
maxToolBudgetCap: number;
|
|
181
183
|
defaultToolBudget: number;
|
|
184
|
+
defaultToolExecutionTimeoutMs: number;
|
|
182
185
|
maxConsecutiveFailures: number;
|
|
183
186
|
maxIdenticalCallRepeats: number;
|
|
184
187
|
defaultContextWindowTokens: number;
|
|
@@ -35,6 +35,8 @@ export interface StreamingToolExecutorConfig {
|
|
|
35
35
|
concurrencySafeTools?: Set<string>;
|
|
36
36
|
/** Hard ceiling on simultaneous tool executions (0 = unlimited). CC parity. */
|
|
37
37
|
maxConcurrentTools?: number;
|
|
38
|
+
/** Per foreground tool deadline. 0 or undefined means no executor deadline. */
|
|
39
|
+
maxExecutionMs?: number;
|
|
38
40
|
}
|
|
39
41
|
/**
|
|
40
42
|
* Executes tools with concurrency control and streaming progress.
|
|
@@ -99,4 +101,5 @@ export declare class StreamingToolExecutor {
|
|
|
99
101
|
private hasCompletedResults;
|
|
100
102
|
private hasExecutingTools;
|
|
101
103
|
private hasUnfinishedTools;
|
|
104
|
+
private invokeToolWithDeadline;
|
|
102
105
|
}
|