qlogicagent 2.5.0 → 2.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.js +9 -9
- package/dist/cli.js +215 -215
- package/dist/contracts.js +0 -1
- package/dist/index.js +181 -181
- package/dist/types/agent/runtime-vars.d.ts +48 -0
- package/dist/types/cli/stdio-server.d.ts +1 -14
- package/dist/types/cli/tool-bootstrap.d.ts +0 -2
- package/dist/types/contracts/index.d.ts +1 -4
- package/dist/types/protocol/methods.d.ts +1 -1
- package/package.json +1 -1
- package/dist/types/agent/constants.d.ts +0 -8
- package/dist/types/contracts/todo.d.ts +0 -10
- package/dist/types/runtime/execution/dream-category-context.test.d.ts +0 -1
- package/dist/types/runtime/execution/memory-decay.test.d.ts +0 -1
- package/dist/types/runtime/infra/acp-detector.test.d.ts +0 -1
- package/dist/types/runtime/infra/acp-protocol-adapter.test.d.ts +0 -1
- package/dist/types/runtime/infra/acp-usage-tracker.test.d.ts +0 -1
- package/dist/types/runtime/infra/agent-config-store.test.d.ts +0 -1
- package/dist/types/runtime/infra/agent-process.test.d.ts +0 -1
- package/dist/types/runtime/infra/mcp-bridge.test.d.ts +0 -1
- package/dist/types/runtime/infra/model-id-translator.test.d.ts +0 -1
- package/dist/types/runtime/infra/skill-injector.test.d.ts +0 -1
package/dist/agent.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
var
|
|
1
|
+
var gn=Object.defineProperty;var fn=(e,t)=>()=>(e&&(t=e(e=0)),t);var yn=(e,t)=>{for(var o in t)gn(e,o,{get:t[o],enumerable:!0})};var nn={};yn(nn,{resolveToolEligibility:()=>Wo});function Go(e,t){if(zo.some(o=>o.test(e)))return!0;if(t)for(let o of t)try{if(new RegExp(o,"i").test(e))return!0}catch{}return!1}function Ho(e,t){let o=e.function.name,n=e.meta,r=[];return t.blockedToolNames?.includes(o)?(r.push("policy_blocked"),{level:5,reasons:r}):n?.isReadOnly?(r.push("always_allowed"),{level:1,reasons:r}):n?.requiresApproval?(r.push("approval_required"),{level:4,reasons:r}):n?.isDangerous||Go(o,t.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function qo(e){switch(e){case 1:return"eligible";case 2:return"eligible";case 3:return"dangerous-notify";case 4:return"approval-required";case 5:return"blocked-by-policy"}}function Wo(e,t={}){let o=new Map,n=[],r=[],a=[];for(let l of e){let s=l.function.name,{level:u,reasons:T}=Ho(l,t),d=qo(u),f={toolName:s,status:d,permissionLevel:u,approvalRequired:u===4,reasonCodes:T};o.set(s,f),u===5?r.push(f):(n.push(l),u===4&&a.push(f))}return{eligibleTools:n,blockedTools:r,approvalRequiredTools:a,eligibilityByName:o}}var zo,on=fn(()=>{"use strict";zo=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function be(e,t,o,n){return{role:"assistant",content:t||null,tool_calls:e,...o&&o.length>0?{thinkingBlocks:o}:{},...n?{reasoning_content:n}:{}}}function Q(e,t){let o=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:o,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var Tn=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,j={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]},hn=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Cn=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,bn=512,kn=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var _n=new Set([500,502,503,504,521,522,523,524,529]),Rn=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],xn=["upgrade your plan","upgrade plan","current plan","subscription"],Sn=["daily","weekly","monthly"],Mn=["try again","retry","temporary","cooldown"],An=["usage limit","rate limit","organization usage"],vn=["organization","workspace"],En=["billing period","exceeded","reached","exhausted"],wn=/["']?(?: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,In=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function z(e,t){if(!e)return!1;let o=e.toLowerCase();return t.some(n=>n instanceof RegExp?n.test(o):o.includes(n))}function Ln(e){return z(e,j.format)}function lt(e){return z(e,j.rateLimit)}function On(e){return z(e,j.timeout)}function Pn(e){return Tn.test(e)}function ke(e){let t=e.toLowerCase();return t?e.length>bn?Cn.test(t):z(t,j.billing)?!0:hn.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function ct(e){return z(e,j.authPermanent)}function Nn(e){return z(e,j.auth)}function ut(e){return z(e,j.overloaded)}function $(e,t){return t.some(o=>e.includes(o))}function Dn(e){return $(e,Rn)||$(e,xn)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Fn(e){let t=$(e,Sn),o=e.includes("spend limit")||e.includes("spending limit"),n=$(e,vn);return $(e,Mn)&&$(e,An)||t&&(e.includes("usage limit")||o)||t&&e.includes("limit")&&e.includes("reset")||n&&e.includes("limit")&&(o||$(e,En))}function Bn(e){return e.trim().toLowerCase().replace(In,"").trim()}function dt(e){let t=Bn(e);return!t||Dn(t)?"billing":lt(t)||Fn(t)?"rate_limit":"billing"}function Un(e){return wn.test(e)?dt(e):null}function pt(e){let t=e.match(kn);if(!t)return null;let o=Number(t[1]);return Number.isFinite(o)?{code:o,rest:(t[2]??"").trim()}:null}function $n(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function jn(e){let t=e.trim();if(!t)return!1;let o=pt(t);return o?_n.has(o.code):!1}function mt(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?dt(t):"billing":e===429?"rate_limit":e===401||e===403?t&&ct(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&ut(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&ke(t)?"billing":"format":null}function zn(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 Gn(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 gt(e){if(Gn(e))return"session_expired";if(zn(e))return"model_not_found";let t=Un(e);return t||(Pn(e)?ke(e)?"billing":"rate_limit":lt(e)?"rate_limit":ut(e)?"overloaded":jn(e)?pt(e.trim())?.code===529?"overloaded":"timeout":$n(e)?"timeout":Ln(e)?"format":ke(e)?"billing":On(e)?"timeout":ct(e)?"auth_permanent":Nn(e)?"auth":null)}var Hn={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"},qn=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function q(e,t){let o=mt(e,t)??(t?gt(t):null);return o?Hn[o]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function _e(e){return qn.has(e)}var ft=4,Z=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,o){let n=[],r=[];for(let d of t)d.role==="system"?n.push(d):r.push(d);let a=o;for(let d of n)a-=this.estimateTokens(d);let l;for(let d of r)if(d.role==="user"){l=d;break}if(l&&(a-=this.estimateTokens(l)),a<=0)return{messages:l?[...n,l]:n,droppedCount:r.length-(l?1:0),strategy:"sliding-window"};let s=[],u=0;for(let d=r.length-1;d>=0;d--){let f=r[d];if(f===l)continue;let M=this.estimateTokens(f);if(a-M<0&&u>=ft)break;if(a-M<0&&u<ft){s.unshift(f),u++;continue}a-=M,s.unshift(f),u++}let T=[...n];return l&&!s.includes(l)&&T.push(l),T.push(...s),{messages:T,droppedCount:r.length-(s.length+(l&&!s.includes(l)?1:0)),strategy:"sliding-window"}}};var ee=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,o){let n=0;return{messages:t.map(a=>a.role!=="tool"||typeof a.content!="string"||a.content.length<=this.maxToolResultChars?a:(n++,{...a,content:Wn(a.content,this.maxToolResultChars)})),droppedCount:n,strategy:"tool-result-trim"}}};function Wn(e,t){if(e.length<=t)return e;let o=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let a=Math.max(o.lastIndexOf("},"),o.lastIndexOf("],"),o.lastIndexOf(`}
|
|
2
2
|
`),o.lastIndexOf(`]
|
|
3
3
|
`));if(a>t*.5)return o.slice(0,a+1)+`
|
|
4
4
|
[...truncated: ${e.length-a-1} chars omitted]`}let r=o.lastIndexOf(`
|
|
5
5
|
`);return r>t*.7?o.slice(0,r)+`
|
|
6
6
|
[...truncated: ${e.length-r} chars omitted]`:o+`
|
|
7
|
-
[...truncated: ${e.length-t} chars omitted]`}function
|
|
8
|
-
`).map(T=>T.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(Bt(u)===o)return r.name}}catch{}}}catch{}return null}function eo(e){if(!Xe(e))return 0;try{return $t(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&Xe(jt(e,t.name,"SKILL.md"))).length}catch{return 0}}function to(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<Dt||e.distinctToolCount<Ft||Date.now()-zt<Ut||t?.projectSkillsDir&&(eo(t.projectSkillsDir)>=Nt||t.tools.length>0&&Zn(t.tools,t.projectSkillsDir)))}function no(e){return e.existingSkillName?e.feedback==="negative":!1}function me(e,t){return no(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:to(e,t)?(zt=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 Gt(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 oo(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function ro(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function so(e){if(!e.eligibility?.length)return[...e.tools];let t=ro(e.eligibility);return e.tools.filter(o=>{let n=Gt(o);if(!n)return!1;let r=t.get(n);return!r||oo(r.status)})}function io(e){let t=[],o=e.compatibility??{},n=e.toolChoice;if(e.thinkingEnabled&&o.requireAutoWhenThinking){let r=typeof n=="object"&&n&&!Array.isArray(n)?String(n.type??""):n;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),n="auto")}if(n==="required"&&o.allowRequiredToolChoice===!1){let r=o.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),n=r}if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&o.allowNamedToolChoice===!1){let r=o.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),n=r}return{normalizedToolChoice:n,warnings:t}}function Ke(e){let t=io({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),o=t.normalizedToolChoice,n=[...t.warnings],r=so({tools:e.tools,eligibility:e.eligibility});if(!o||o==="auto")return{tools:r,normalizedToolChoice:o,warnings:n};if(o==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(o==="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:n}}if(typeof o=="object"&&!Array.isArray(o)&&o.type==="function"){let a=o.function??void 0,l=typeof a?.name=="string"?a.name.trim():"";if(!l)throw new Error("tool_choice.function.name is required");let s=r.filter(u=>Gt(u)===l);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${l}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:l}},extraSystemPrompt:`You must call the ${l} tool before responding.`,warnings:n}}return{tools:r,normalizedToolChoice:o,warnings:n}}var ao=["stop","aborted","timeout","cancelled","interrupted","error"],lo=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Ht(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function co(e,t){return{...e,content:[...Ht(e.content),...Ht(t.content)]}}function uo(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 po(e){return new Set((e??ao).map(t=>t.trim().toLowerCase()))}function mo(e,t){return e?po(t).has(e.trim().toLowerCase()):!1}function We(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 u=s.tool_calls.filter(T=>uo(T));return{...s,...u.length>0?{tool_calls:u}:{tool_calls:void 0}}}return{...s}}),o=new Set;for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let u of s.tool_calls)typeof u.id=="string"&&u.id&&o.add(u.id);let n=t.filter(s=>s.role!=="tool"?!0:!!(s.tool_call_id&&o.has(s.tool_call_id))),r=new Set;for(let s of n)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 n){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let u=s.tool_calls.filter(T=>typeof T.id=="string"&&r.has(T.id));if(u.length===0){let{tool_calls:T,...d}=s;d.content!=null&&d.content!==""&&a.push(d);continue}if(u.length<s.tool_calls.length){a.push({...s,tool_calls:u});continue}}a.push(s)}let l=[];for(let s of a){let u=l.length>0?l[l.length-1]:void 0;if(s.role==="user"&&u?.role==="user"){l[l.length-1]=co(u,s);continue}l.push(s)}return l}function Ye(e,t){return mo(t?.stopReason,t?.forcedStopReasons)?e.map(o=>{if(o.role!=="assistant")return{...o};let n={...o};for(let r of lo)delete n[r];return n}):[...e]}function Ve(e,t){let o=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",n=new Set;for(let a of e)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&n.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 l of a.tool_calls)typeof l.id!="string"||!l.id||n.has(l.id)||(n.add(l.id),r.push({role:"tool",tool_call_id:l.id,content:o}));return r}function Je(e,t){let o=We(e),n=Ye(o,t);return Ve(n,t)}function go(e){let t=new Set,o=new Set;for(let n of e){if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let r of n.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&o.add(n.tool_call_id)}return[...t].filter(n=>!o.has(n))}function fo(e){let t=new Set;for(let o of e)o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&t.add(o.tool_call_id);return[...t]}function yo(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Qe(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 ge(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 fe(e){let t=[],o=We(e.replayMessages);o.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let n=Ye(o,e.options);n.some((a,l)=>a!==o[l])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=Ve(n,e.options);return r.length>n.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:yo({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:go(r),completedToolCallIds:fo(r)}),recoveryActions:t}}var To=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Ze(e){return e?To.has(e):!0}function et(e){return e===429||e===529}function ye(e,t=500,o=32e3){let n=Math.min(t*Math.pow(2,e-1),o);return n+Math.floor(Math.random()*n*.25)}var Nr={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function tt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var re=class extends Error{constructor(o,n){super(`Model fallback triggered: ${o} -> ${n}`);this.originalModel=o;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function nt(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function ot(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let o=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,n=o>0?e.promptTokens/o*100:100;return e.promptTokens>=o?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:n>=85?{level:"warning",usagePercent:n,remainingTokens:o-e.promptTokens}:{level:"ok"}}function rt(e,t,o){let n=e.message?.toLowerCase()??"",r=e.status??0;return r===413||n.includes("prompt_too_long")||n.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&o.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:n||"unknown_error"}}function st(e,t,o){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let n=Math.min(e.currentMaxOutputTokens*2,o);return n<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:n}}function it(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Co={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function at(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function K(e,t=Co){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function qt(e,t){let o=e.get(t.index);o||(o={id:"",name:"",arguments:""},e.set(t.index,o)),t.id&&(o.id=t.id),t.name&&(o.name+=t.name),o.arguments+=t.arguments}import{mkdir as Ao,writeFile as Mo}from"fs/promises";import{join as Yt}from"path";import{tmpdir as Eo}from"os";var vo="tool-results",Vt="<persisted-output>",Io="</persisted-output>";function Jt(){return{seenIds:new Set,replacements:new Map}}function Qt(e){return Yt(Eo(),"qlogicagent-sessions",e,vo)}async function wo(e){try{await Ao(Qt(e),{recursive:!0})}catch{}}function Lo(e,t){let o=t.replace(/[^a-zA-Z0-9_-]/g,"_");return Yt(Qt(e),`${o}.txt`)}function Oo(e,t){if(e.length<=t)return{preview:e,hasMore:!1};let n=e.slice(0,t).lastIndexOf(`
|
|
9
|
-
`),r=n>t*.5?n:t;return{preview:e.slice(0,r),hasMore:!0}}function
|
|
7
|
+
[...truncated: ${e.length-t} chars omitted]`}function Re(...e){return{compress(t,o){let n=t,r=0,a=[];for(let l of e){let s=l.compress(n,o);n=s.messages,r+=s.droppedCount,s.droppedCount>0&&a.push(s.strategy)}return{messages:n,droppedCount:r,strategy:a.length>0?a.join("+"):"none"}}}}var yt={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function xe(e={}){let t={...yt,...e},o=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(o,t.maxBudget))}function Se(e,t){let o=e/t;return o<=.8?"none":o<=1?"trim-only":o<=1.5?"sliding-window":"llm-summarize"}var te=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 o=0,n=0,r=0,a=0,l=0;for(let s of this.events)o+=s.tokensBefore>0?s.tokensAfter/s.tokensBefore:1,n+=s.latencyMs,r+=Math.max(0,s.tokensBefore-s.tokensAfter),s.usedLlm&&a++,s.cacheInvalidated&&l++;return{totalCompressions:t,totalLlmCalls:a,totalCacheInvalidations:l,averageCompressionRatio:o/t,averageLatencyMs:n/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},ne=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 Tt(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var Kn=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"]),G=class{constructor(t=20,o=Tt){this.preserveRecentCount=t;this.estimateTokens=o}preserveRecentCount;estimateTokens;compress(t,o){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let n=t.length-this.preserveRecentCount,r=0,a=0;return{messages:t.map((s,u)=>{if(u>=n||s.role!=="tool"||typeof s.content!="string"||!s.name||!Kn.has(s.name)||s.content.length<=200)return s;let T=this.estimateTokens(s);return a+=T,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 Me(e,t,o=Tt){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let n=0,r=0,a=[];for(let s of e){let u=s.tool_call_id??"";if(u&&t.has(u)){n+=o(s),r++,t.delete(u);continue}a.push(s)}let l=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:a,tokensFreed:n,removedCount:r,boundaryMessage:l}}function Ae(){return{stages:[]}}function ve(e,t,o){let n=o?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=n)return{messages:e,stagedCount:0};let a=ht(e,t),l=Xn(a,t,n);if(l.length===0)return{messages:a,stagedCount:0};for(let s of l)t.stages.push(s);return a=ht(e,t),{messages:a,stagedCount:l.length}}function Ee(e,t){let o=0;for(let n of t.stages)n.committed||(n.committed=!0,o++);return o===0?{messages:e,committed:0}:{messages:Ct(e,t),committed:o}}function ht(e,t){return t.stages.filter(n=>n.committed).length===0?e:Ct(e,t)}function Ct(e,t){let o=t.stages.filter(r=>r.committed).sort((r,a)=>a.range[0]-r.range[0]),n=[...e];for(let r of o){let[a,l]=r.range;if(a>=n.length)continue;let s=Math.min(l,n.length),u={role:"system",content:r.summary};n.splice(a,s-a,u)}return n}function Xn(e,t,o){let n=Math.max(0,e.length-Math.floor(o/2)),r=[],a=new Set(t.stages.map(u=>`${u.range[0]}-${u.range[1]}`)),l=-1,s=0;for(let u=0;u<n;u++){let T=e[u];if(T.role==="tool"||T.role==="assistant"&&typeof T.content=="string"&&T.content==="")l<0&&(l=u),s++;else{if(s>=3){let f=`${l}-${l+s}`;a.has(f)||r.push({id:`collapse_${l}_${l+s}`,range:[l,l+s],summary:`[${s} tool results collapsed]`,committed:!1})}l=-1,s=0}}if(s>=3){let u=`${l}-${l+s}`;a.has(u)||r.push({id:`collapse_${l}_${l+s}`,range:[l,l+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}import{existsSync as Le,readdirSync as Ut,readFileSync as Yn}from"node:fs";import{join as $t}from"node:path";var bt=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),kt=3,_t=2,Rt=128e3,xt=13e3,St=16384,Mt=65536,At=3,vt=65536,we=500,Et=3,wt=5e4,It=2e5,Ie=2e3,Lt=3e4,Ot=3,oe=10;var Pt=20;var Nt=3,Dt=2,Ft=300*1e3;var hr=300*1e3;var Cr=50*1024,br=500*1024,kr=500*1024*1024,_r=50*1024*1024;var Rr=60*1024;var jt=0;function Bt(e){return[...e].sort().join("+")}function Vn(e,t){if(!Le(t))return null;let o=Bt(e);try{let n=Ut(t,{withFileTypes:!0});for(let r of n){if(!r.isDirectory())continue;let a=$t(t,r.name,"SKILL.md");try{let s=Yn(a,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(s){let u=s[1].split(`
|
|
8
|
+
`).map(T=>T.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(Bt(u)===o)return r.name}}catch{}}}catch{}return null}function Jn(e){if(!Le(e))return 0;try{return Ut(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&Le($t(e,t.name,"SKILL.md"))).length}catch{return 0}}function Qn(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<Nt||e.distinctToolCount<Dt||Date.now()-jt<Ft||t?.projectSkillsDir&&(Jn(t.projectSkillsDir)>=Pt||t.tools.length>0&&Vn(t.tools,t.projectSkillsDir)))}function Zn(e){return e.existingSkillName?e.feedback==="negative":!1}function de(e,t){return Zn(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Qn(e,t)?(jt=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 zt(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 eo(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function to(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function no(e){if(!e.eligibility?.length)return[...e.tools];let t=to(e.eligibility);return e.tools.filter(o=>{let n=zt(o);if(!n)return!1;let r=t.get(n);return!r||eo(r.status)})}function oo(e){let t=[],o=e.compatibility??{},n=e.toolChoice;if(e.thinkingEnabled&&o.requireAutoWhenThinking){let r=typeof n=="object"&&n&&!Array.isArray(n)?String(n.type??""):n;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),n="auto")}if(n==="required"&&o.allowRequiredToolChoice===!1){let r=o.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),n=r}if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&o.allowNamedToolChoice===!1){let r=o.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),n=r}return{normalizedToolChoice:n,warnings:t}}function Oe(e){let t=oo({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),o=t.normalizedToolChoice,n=[...t.warnings],r=no({tools:e.tools,eligibility:e.eligibility});if(!o||o==="auto")return{tools:r,normalizedToolChoice:o,warnings:n};if(o==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(o==="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:n}}if(typeof o=="object"&&!Array.isArray(o)&&o.type==="function"){let a=o.function??void 0,l=typeof a?.name=="string"?a.name.trim():"";if(!l)throw new Error("tool_choice.function.name is required");let s=r.filter(u=>zt(u)===l);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${l}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:l}},extraSystemPrompt:`You must call the ${l} tool before responding.`,warnings:n}}return{tools:r,normalizedToolChoice:o,warnings:n}}var ro=["stop","aborted","timeout","cancelled","interrupted","error"],so=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Gt(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function io(e,t){return{...e,content:[...Gt(e.content),...Gt(t.content)]}}function ao(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 lo(e){return new Set((e??ro).map(t=>t.trim().toLowerCase()))}function co(e,t){return e?lo(t).has(e.trim().toLowerCase()):!1}function Pe(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 u=s.tool_calls.filter(T=>ao(T));return{...s,...u.length>0?{tool_calls:u}:{tool_calls:void 0}}}return{...s}}),o=new Set;for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let u of s.tool_calls)typeof u.id=="string"&&u.id&&o.add(u.id);let n=t.filter(s=>s.role!=="tool"?!0:!!(s.tool_call_id&&o.has(s.tool_call_id))),r=new Set;for(let s of n)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 n){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let u=s.tool_calls.filter(T=>typeof T.id=="string"&&r.has(T.id));if(u.length===0){let{tool_calls:T,...d}=s;d.content!=null&&d.content!==""&&a.push(d);continue}if(u.length<s.tool_calls.length){a.push({...s,tool_calls:u});continue}}a.push(s)}let l=[];for(let s of a){let u=l.length>0?l[l.length-1]:void 0;if(s.role==="user"&&u?.role==="user"){l[l.length-1]=io(u,s);continue}l.push(s)}return l}function Ne(e,t){return co(t?.stopReason,t?.forcedStopReasons)?e.map(o=>{if(o.role!=="assistant")return{...o};let n={...o};for(let r of so)delete n[r];return n}):[...e]}function De(e,t){let o=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",n=new Set;for(let a of e)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&n.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 l of a.tool_calls)typeof l.id!="string"||!l.id||n.has(l.id)||(n.add(l.id),r.push({role:"tool",tool_call_id:l.id,content:o}));return r}function Fe(e,t){let o=Pe(e),n=Ne(o,t);return De(n,t)}function uo(e){let t=new Set,o=new Set;for(let n of e){if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let r of n.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&o.add(n.tool_call_id)}return[...t].filter(n=>!o.has(n))}function po(e){let t=new Set;for(let o of e)o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&t.add(o.tool_call_id);return[...t]}function mo(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Be(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 pe(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 me(e){let t=[],o=Pe(e.replayMessages);o.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let n=Ne(o,e.options);n.some((a,l)=>a!==o[l])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=De(n,e.options);return r.length>n.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:mo({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:uo(r),completedToolCallIds:po(r)}),recoveryActions:t}}var go=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Ue(e){return e?go.has(e):!0}function $e(e){return e===429||e===529}function ge(e,t=500,o=32e3){let n=Math.min(t*Math.pow(2,e-1),o);return n+Math.floor(Math.random()*n*.25)}var Nr={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function je(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var re=class extends Error{constructor(o,n){super(`Model fallback triggered: ${o} -> ${n}`);this.originalModel=o;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function ze(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Ge(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let o=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,n=o>0?e.promptTokens/o*100:100;return e.promptTokens>=o?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:n>=85?{level:"warning",usagePercent:n,remainingTokens:o-e.promptTokens}:{level:"ok"}}function He(e,t,o){let n=e.message?.toLowerCase()??"",r=e.status??0;return r===413||n.includes("prompt_too_long")||n.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&o.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:n||"unknown_error"}}function qe(e,t,o){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let n=Math.min(e.currentMaxOutputTokens*2,o);return n<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:n}}function We(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var yo={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Ke(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function W(e,t=yo){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function Ht(e,t){let o=e.get(t.index);o||(o={id:"",name:"",arguments:""},e.set(t.index,o)),t.id&&(o.id=t.id),t.name&&(o.name+=t.name),o.arguments+=t.arguments}import{mkdir as Ro,writeFile as xo}from"fs/promises";import{join as qt}from"path";import{tmpdir as So}from"os";var Mo="tool-results",Wt="<persisted-output>",Ao="</persisted-output>";function Kt(){return{seenIds:new Set,replacements:new Map}}function Xt(e){return qt(So(),"qlogicagent-sessions",e,Mo)}async function vo(e){try{await Ro(Xt(e),{recursive:!0})}catch{}}function Eo(e,t){let o=t.replace(/[^a-zA-Z0-9_-]/g,"_");return qt(Xt(e),`${o}.txt`)}function wo(e,t){if(e.length<=t)return{preview:e,hasMore:!1};let n=e.slice(0,t).lastIndexOf(`
|
|
9
|
+
`),r=n>t*.5?n:t;return{preview:e.slice(0,r),hasMore:!0}}function Yt(e){return e.includes(Wt)}async function Vt(e,t,o){await vo(o);let n=Eo(o,t);try{await xo(n,e,{encoding:"utf-8",flag:"wx"})}catch(l){if(l.code!=="EEXIST")return null}let{preview:r,hasMore:a}=wo(e,Ie);return{filepath:n,originalSize:e.length,preview:r,hasMore:a}}function Jt(e){let t=`${Wt}
|
|
10
10
|
`;return t+=`Output too large (${e.originalSize} chars). Full output saved to: ${e.filepath}
|
|
11
11
|
|
|
12
|
-
`,t+=`Preview (first ${
|
|
12
|
+
`,t+=`Preview (first ${Ie} bytes):
|
|
13
13
|
`,t+=e.preview,t+=e.hasMore?`
|
|
14
14
|
...
|
|
15
15
|
`:`
|
|
16
|
-
`,t+=
|
|
17
|
-
...[truncated ${e.length-n} chars]`}function Po(e){let t=[],o=[];for(let n of e)n.role==="tool"&&typeof n.content=="string"&&n.tool_call_id?Zt(n.content)||o.push({toolCallId:n.tool_call_id,content:n.content,size:n.content.length}):n.role==="assistant"&&o.length>0&&(t.push(o),o=[]);return o.length>0&&t.push(o),t}function No(e,t){let o=[],n=[],r=[];for(let a of e){let l=t.replacements.get(a.toolCallId);l!==void 0?o.push({...a,replacement:l}):t.seenIds.has(a.toolCallId)?n.push(a):r.push(a)}return{mustReapply:o,frozen:n,fresh:r}}function Do(e,t,o){let n=[...e].sort((l,s)=>s.size-l.size),r=[],a=t+e.reduce((l,s)=>l+s.size,0);for(let l of n){if(a<=o)break;r.push(l),a-=l.size}return r}async function on(e,t,o,n=Ge){let r=Po(e);if(r.length===0)return{messages:e,newlyReplacedCount:0};let a=new Map,l=[];for(let d of r){let{mustReapply:f,frozen:A,fresh:C}=No(d,t);for(let _ of f)a.set(_.toolCallId,_.replacement);if(C.length===0){for(let _ of d)t.seenIds.add(_.toolCallId);continue}let x=A.reduce((_,E)=>_+E.size,0),k=C.reduce((_,E)=>_+E.size,0),R=x+k>n?Do(C,x,n):[],L=new Set(R.map(_=>_.toolCallId));for(let _ of d)L.has(_.toolCallId)||t.seenIds.add(_.toolCallId);R.length>0&&l.push(...R)}if(a.size===0&&l.length===0)return{messages:e,newlyReplacedCount:0};let s=await Promise.all(l.map(async d=>{let f=await en(d.content,d.toolCallId,o);return{candidate:d,result:f}})),u=0;for(let{candidate:d,result:f}of s){if(t.seenIds.add(d.toolCallId),!f)continue;let A=tn(f);a.set(d.toolCallId,A),t.replacements.set(d.toolCallId,A),u++}return a.size===0?{messages:e,newlyReplacedCount:0}:{messages:e.map(d=>{if(d.role!=="tool"||!d.tool_call_id)return d;let f=a.get(d.tool_call_id);return f===void 0?d:{...d,content:f}}),newlyReplacedCount:u}}var Fo=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),Uo=new Set(["bash","execute_command","Bash","shell"]),Te=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(t){this.config=t,this.concurrencySafe=t.concurrencySafeTools??Fo,this.siblingAbortController=new AbortController,t.signal&&t.signal.addEventListener("abort",()=>{this.siblingAbortController.abort("parent_abort")},{once:!0})}discard(){this.discarded=!0}addTool(t){let o=this.concurrencySafe.has(t.function.name);this.tools.push({id:t.id,toolCall:t,status:"queued",isConcurrencySafe:o,results:[],pendingProgress:[]}),this.processQueue()}canExecuteTool(t){let o=this.tools.filter(r=>r.status==="executing"),n=this.config.maxConcurrentTools;return n&&n>0&&o.length>=n?!1:o.length===0||t&&o.every(r=>r.isConcurrencySafe)}async processQueue(){for(let t of this.tools)if(t.status==="queued"){if(this.canExecuteTool(t.isConcurrencySafe))await this.executeTool(t);else if(!t.isConcurrencySafe)break}}getAbortReason(){return this.discarded?"discarded":this.hasErrored?"sibling_error":this.config.signal?.aborted?"user_interrupted":null}getToolDescription(t){let o;try{o=JSON.parse(t.toolCall.function.arguments)}catch{}let n=o?.command??o?.file_path??o?.pattern??"";if(typeof n=="string"&&n.length>0){let r=n.length>40?n.slice(0,40)+"\u2026":n;return`${t.toolCall.function.name}(${r})`}return t.toolCall.function.name}createSyntheticError(t,o){let n=this.erroredToolDescription,r=o==="user_interrupted"?"User rejected tool use":o==="discarded"?"Streaming fallback - tool execution discarded":n?`Cancelled: parallel tool call ${n} errored`:"Cancelled: parallel tool call errored";return{callId:t.id,toolName:t.toolCall.function.name,ok:!1,error:r,message:Z(t.id,{ok:!1,error:r})}}async executeTool(t){t.status="executing";let n=(async()=>{let r=this.getAbortReason();if(r){t.results.push(this.createSyntheticError(t,r)),t.status="completed";return}let{toolInvoker:a,hooks:l,sessionId:s,turnId:u,log:T}=this.config,d=t.toolCall.function.name,f=!1,A=t.toolCall.function.arguments;if(l)try{let _=await l.invoke("tool.before_invoke",{sessionId:s,turnId:u,callId:t.id,toolName:d,arguments:Bo(A)});if(_.action==="abort"){let E=_.reason??"blocked by policy";T.info(`tool ${d} blocked: ${E}`),t.results.push({callId:t.id,toolName:d,ok:!1,error:E,blocked:!0,blockReason:E,message:Z(t.id,{ok:!1,error:E})}),t.status="completed";return}_.action==="continue"&&_.context?.arguments&&(A=JSON.stringify(_.context.arguments))}catch{}let C=await a.invoke(u,d,A,this.siblingAbortController.signal),x=this.getAbortReason();if(x&&!f){t.results.push(this.createSyntheticError(t,x)),t.status="completed";return}let k=!C.error,R=C.result;k&&R&&R.length>5e4&&(R=await nn(R,t.id,s));let L=Z(t.id,{ok:k,payload:R,error:C.error,toolReferences:C.toolReferences,imageUrls:C.imageUrls});k||(f=!0,Uo.has(d)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(t),this.siblingAbortController.abort("sibling_error"))),l?.invoke(k?"tool.after_invoke":"tool.invoke_failed",{sessionId:s,turnId:u,callId:t.id,toolName:d,ok:k,...C.error?{error:C.error}:{}}).catch(()=>{}),t.results.push({callId:t.id,toolName:d,ok:k,error:C.error,message:L}),t.status="completed"})();t.promise=n,n.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded){for(let t of this.tools)if(t.status!=="yielded"){if(t.status==="completed"&&t.results.length>0){t.status="yielded";for(let o of t.results)yield o}else if(t.status==="executing"&&!t.isConcurrencySafe)break}}}async*getRemainingResults(){if(!this.discarded){for(;this.hasUnfinishedTools();){await this.processQueue();for(let t of this.getCompletedResults())yield t;if(this.hasExecutingTools()&&!this.hasCompletedResults()){let t=this.tools.filter(n=>n.status==="executing"&&n.promise).map(n=>n.promise),o=new Promise(n=>{this.progressResolve=n});t.length>0&&await Promise.race([...t,o])}}for(let t of this.getCompletedResults())yield t}}hasCompletedResults(){return this.tools.some(t=>t.status==="completed")}hasExecutingTools(){return this.tools.some(t=>t.status==="executing")}hasUnfinishedTools(){return this.tools.some(t=>t.status!=="yielded")}};function Bo(e){try{return JSON.parse(e)}catch{return}}import{readFile as Ds}from"node:fs/promises";function dt(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function ct(e){let t=0;for(let o of e)t+=dt(o);return t}var ut={"deepseek-v4-flash":1e6,"deepseek-v4-pro":1e6,"deepseek-chat":1e6,"deepseek-reasoner":1e6,"gpt-4o":128e3,"gpt-4o-mini":128e3,"claude-sonnet-4-20250514":2e5,"claude-3-5-haiku-20241022":2e5,"gemini-3.1-pro-preview":1e6,"gemini-3-flash-preview":1e6,"gemini-3.1-flash-lite":1e6};function $o(e){if(!e)return 128e3;if(e in ut)return ut[e];let t=e.toLowerCase();for(let[o,n]of Object.entries(ut))if(t.startsWith(o.toLowerCase()))return n;return 128e3}var jo=8e3;var zo=new ne(200);var Fs=new oe;function Go(){return Se(new te(jo),new G(20,dt),new ee(dt))}var Ho=null;function rn(e,t){let o=t?.budget??Ae({modelContextWindow:$o(t?.model)}),r=(t?.pipeline??Go()).compress(e,o);if(r.droppedCount>0){let a=ct(e),l=ct(r.messages);zo.record({timestamp:Date.now(),strategy:r.strategy,tokensBefore:a,tokensAfter:l,droppedCount:r.droppedCount,latencyMs:r.metrics?.latencyMs??0,usedLlm:!1,cacheInvalidated:r.metrics?.cacheInvalidated??!1,tier:Me(a,o)})}return r.droppedCount>0&&Ho?.(r.droppedCount,ct(r.messages)),r}function sn(e,t,o){let n=o-t;return`[Budget] ${Math.round(e)}% used (${t.toLocaleString()} / ${o.toLocaleString()} tokens). ${n.toLocaleString()} tokens remaining. `+(e>=90?"Wrap up your current task \u9225?you are near the token limit.":"Continue working \u9225?do not summarize prematurely.")}var Vo=new Set(["write","edit","patch","apply_patch"]);function Jo(e){let t=e.split(".").pop()?.toLowerCase()??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(t)?"image":["md","txt","pdf","doc","docx","rtf","html"].includes(t)?"document":["mermaid","mmd","dot","puml","plantuml"].includes(t)?"diagram":["csv","tsv","xlsx","xls"].includes(t)?"table":["ts","tsx","js","jsx","py","rs","go","java","c","cpp","h","cs","rb","sh","sql","json","yaml","yml","toml","xml","css","scss","vue","svelte"].includes(t)?"code":"file"}function Qo(e){let t=e.split(".").pop()?.toLowerCase()??"";return{ts:"typescript",tsx:"typescriptreact",js:"javascript",jsx:"javascriptreact",py:"python",rs:"rust",go:"go",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",rb:"ruby",sh:"shellscript",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",vue:"vue",svelte:"svelte",md:"markdown"}[t]}function Zo(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.round(e),100):Le}function cn(e){let t=e.message.toLowerCase();return e.status===413||t.includes("prompt_too_long")||t.includes("context_length_exceeded")||t.includes("maximum context length")}function er(e){return e==="length"||e==="max_tokens"}function un(e){let t=e.message.toLowerCase();return(t.includes("image")||t.includes("media")||t.includes("file too large")||t.includes("payload too large"))&&(e.status===413||t.includes("too large")||t.includes("size"))}function tr(e){let t=e.headers;if(!t)return null;let o=t["retry-after"]??t["Retry-After"];if(!o)return null;let n=parseInt(o,10);return!isNaN(n)&&n>0?n*1e3:null}function nr(e){if(e.status!==400)return null;let t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!t?.[1]||!t?.[3])return null;let o=parseInt(t[1],10),n=parseInt(t[3],10);if(isNaN(o)||isNaN(n))return null;let r=n-o-1e3;return r>=3e3?r:null}function or(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}async function*dn(e,t,o,n){let{turnId:r,sessionId:a,messages:l,tools:s,model:u,apiKey:T,temperature:d=0,hooks:f,signal:A}=e,C={sessionId:a,turnId:r},x=e.maxTurns??0,k=e.querySource,{resolveToolEligibility:R}=await Promise.resolve().then(()=>(ln(),an)),L=R(s,e.toolEligibilityContext),_=L.eligibleTools;for(let S of L.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:S.toolName,reason:"blocked-by-policy"};if(!_.length){yield*rr(r,u,l,T,d,A,t,n);return}let E=Zo(e.maxRounds),O={contextWindowTokens:e.contextWindowTokens??Ne,responseBufferTokens:De,maxOutputTokens:e.maxOutputTokens??Fe,abortSignal:A,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},H=new Set,F=0,ie=_,ae,i={messages:[...l],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:nt(O),reactiveCompactState:at(),toolLoopState:fe({maxRounds:E,replayMessages:[...l]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:ve(),currentModel:u,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:Jt(),budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map},pt=Math.max(x*5,200),mt=0;for(;;){if(mt++,mt>pt){n.info(`hard iteration cap reached (${pt}), forcing completion`);let c=i.finalText||se(i.messages,n);yield{type:"end",turnId:r,content:c,usage:i.totalUsage,model:i.currentModel};return}let{messages:S,maxOutputTokensRecoveryCount:W,hasAttemptedReactiveCompact:ar,maxOutputTokensOverride:gt,turnCount:Y,guardState:v,reactiveCompactState:U,collapseStore:he}=i,{toolLoopState:P}=i;if(ae){try{let c=await ae;c&&(yield{type:"tool_use_summary",turnId:r,summary:c})}catch{}ae=void 0}if(e.refreshTools&&Y>1){let c=e.refreshTools();c!==ie&&(ie=c,n.debug(`tools refreshed: ${c.length} tools`))}if(it(v,O)){n.info(`turn aborted by guard at turn ${Y}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:i.totalUsage};return}let B=ot(v,O);if(B.level==="blocking"){B.reason==="prompt_too_long"&&K(U)&&(U.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${B.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),n.info(`token budget blocking (${B.reason}), ending tool loop`);break}B.level==="warning"&&n.info(`token budget warning: ${B.usagePercent}% used, ${B.remainingTokens} remaining`);let I;{let c=await on(S,i.contentReplacementState,a);I=c.messages,c.newlyReplacedCount>0&&(n.info(`tool-result-budget: persisted ${c.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:r,action:"tool_result_budget",detail:`${c.newlyReplacedCount} persisted`})}{let c=Ee(I,i.snipRemovedIds);I=c.messages,c.removedCount>0&&(n.info(`snip: removed ${c.removedCount} messages, freed ~${c.tokensFreed} tokens`),yield{type:"recovery",turnId:r,action:"snip",detail:`${c.removedCount} messages`})}{let p=new G().compress(I,0);p.droppedCount>0&&(I=p.messages,n.info(`microcompact: cleared ${p.droppedCount} old tool results`))}if(I=Ie(I,he).messages,v.promptTokens>0){let c=rn(I,{budget:O.contextWindowTokens*.75,model:i.currentModel});c.droppedCount>0&&(I=c.messages,n.info(`autocompact: ${c.strategy}, dropped ${c.droppedCount}`),yield{type:"recovery",turnId:r,action:"autocompact",detail:`${c.strategy}: ${c.droppedCount} dropped`},i.hasAttemptedReactiveCompact=!1,f?.invoke("context.after_compact",{...C,removedCount:c.droppedCount}).catch(()=>{}))}I=or(I);let le=Ke({tools:ie,toolChoice:e.toolChoice??"auto"}),V=fe({maxRounds:E,replayMessages:I,lastStopReason:P.lastStopReason,options:{stopReason:P.lastStopReason}}),ft=le.extraSystemPrompt?[{role:"system",content:le.extraSystemPrompt},...V.state.replayMessages]:V.state.replayMessages;P=V.state,V.recoveryActions.length>0&&n.debug(`tool loop recovery: ${V.recoveryActions.map(c=>c.detail??c.kind).join("; ")}`),n.debug(`turn ${Y}, messages: ${ft.length}`),f?.invoke("turn.before_inference",{...C,model:i.currentModel}).catch(()=>{});let ce=!1,yt=[],Tt=new Map,ht="stop",N,b=null,ue=!1,J=[],w=[];try{for await(let c of t.stream({model:i.currentModel,messages:ft,tools:le.tools,toolChoice:le.normalizedToolChoice??"auto",temperature:d,maxTokens:(gt??v.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:i.lastResponseId,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},T,A))switch(c.type){case"delta":yt.push(c.text),ce||(yield{type:"delta",turnId:r,text:c.text});break;case"tool_call_delta":ce=!0,qt(Tt,c);break;case"reasoning_delta":J.push(c.text);break;case"reasoning_block_complete":c.signature&&w.push({thinking:J.join(""),signature:c.signature}),J.length=0;break;case"usage":N={inputTokens:c.promptTokens,outputTokens:c.completionTokens,reasoningTokens:c.reasoningTokens,cacheRead:c.cacheReadTokens,cacheWrite:c.cacheCreationTokens};break;case"response_id":i.lastResponseId=c.id;break;case"annotations":yield{type:"annotations",turnId:r,annotations:c.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${c.toolType}: ${c.event}`};break;case"done":ht=c.finishReason;break}if(ce||f?.invoke("turn.after_inference",{...C,model:i.currentModel}).catch(()=>{}),e.postSamplingHooks&&e.postSamplingHooks.length>0){let c=i.currentModel;for(let p of e.postSamplingHooks)try{p({messages:[...I],model:c,sessionId:a})}catch{}}}catch(c){if(c instanceof re&&e.fallbackModel){n.info(`model fallback triggered: ${c.originalModel} \u2192 ${c.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`${c.originalModel} \u2192 ${c.fallbackModel}`},i={...i,currentModel:c.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let p=c instanceof Error?c.message:String(c),m=typeof c?.status=="number"?c.status:void 0;if(!m&&p&&(p.includes("ECONNRESET")||p.includes("EPIPE"))){let h=(i.consecutiveApiRetries??0)+1;if(h>X){n.info(`stale connection retry limit reached (${X}), aborting`),yield{type:"error",turnId:r,error:p,code:"RETRIES_EXHAUSTED",usage:i.totalUsage};return}n.info(`stale connection (${p.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:r,action:"stale_connection_retry",detail:p.slice(0,80)},i={...i,consecutiveApiRetries:h,transition:void 0};continue}let g=nr({status:m,message:p});if(g!==null){n.info(`max_tokens overflow: adjusting to ${g}`),v.currentMaxOutputTokens=g,i={...i,maxOutputTokensOverride:g,transition:void 0};continue}if(et(m)){if(i.consecutive529Errors++,i.consecutive529Errors>=qe&&e.fallbackModel&&i.currentModel!==e.fallbackModel){n.info(`529 \xD7 ${i.consecutive529Errors}: triggering fallback to ${e.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`529 \xD7 ${i.consecutive529Errors}`},i={...i,currentModel:e.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(tt()){let h=ye(i.consecutive529Errors);n.info(`persistent retry: waiting ${h}ms (attempt ${i.consecutive529Errors})`);let y=h;for(;y>0;){if(A?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED",usage:i.totalUsage};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(y/1e3)}s (${m})`};let M=Math.min(y,He);await new Promise(ke=>setTimeout(ke,M)),y-=M}i={...i,transition:void 0};continue}if(Ze(k)){let y=tr({status:m,message:p})??ye(i.consecutive529Errors);n.info(`transient ${m}: retry in ${y}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${m} retry in ${y}ms`},await new Promise(M=>setTimeout(M,y)),i={...i,transition:void 0};continue}n.info(`background source ${k}: not retrying ${m}`)}b={status:m,message:p}}if(b&&f?.invoke("turn.after_inference",{...C,model:i.currentModel,response:{error:b.message}}).catch(()=>{}),b)if(cn(b))ue=!0,n.info(`withheld prompt_too_long error (status=${b.status})`);else if(un(b))ue=!0,n.info(`withheld media_size error (status=${b.status})`);else{let c=rt({status:b.status??500,message:b.message},v,O);if(c.action==="reactive_compact"&&K(U)&&(U.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${b.status??500}: ${b.message}`}),c.action==="retry"){let m=(i.consecutiveApiRetries??0)+1;if(m>X){n.info(`API retry limit reached (${X}), aborting`);let g=q(b.status,b.message);yield{type:"error",turnId:r,error:b.message,code:g,usage:i.totalUsage};return}yield{type:"recovery",turnId:r,action:"retry",detail:c.reason},i={...i,consecutiveApiRetries:m,transition:void 0};continue}let p=q(b.status,b.message);f?.invoke("stop.failure",{sessionId:a,reason:p,error:b.message}).catch(()=>{}),yield{type:"error",turnId:r,error:b.message,code:p,usage:i.totalUsage};return}N&&(i.totalUsage.inputTokens+=N.inputTokens,i.totalUsage.outputTokens+=N.outputTokens,N.reasoningTokens&&(i.totalUsage.reasoningTokens=(i.totalUsage.reasoningTokens??0)+N.reasoningTokens),N.cacheRead&&(i.totalUsage.cacheRead=(i.totalUsage.cacheRead??0)+N.cacheRead),N.cacheWrite&&(i.totalUsage.cacheWrite=(i.totalUsage.cacheWrite??0)+N.cacheWrite)),N?.inputTokens&&(v.promptTokens=N.inputTokens);let Ct=yt.join("");Ct&&(i.finalText=Ct);let D=[...Tt.values()].map(c=>({id:c.id||`tc_${r}_${Y}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:c.name,arguments:c.arguments}}));if(D.length===0&&!ce){if(ue&&b&&cn(b)){if(i.transition?.reason!=="collapse_drain_retry"){let m=we(I,he);if(m.committed>0){n.info(`collapse drain: committed ${m.committed} stages`),yield{type:"recovery",turnId:r,action:"collapse_drain",detail:`${m.committed} stages committed`},i={...i,messages:m.messages,transition:{reason:"collapse_drain_retry",committed:m.committed}};continue}}if(K(U)){U.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"withheld prompt_too_long"},i={...i,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld 413: recovery exhausted, surfacing error"),f?.invoke("stop.failure",{sessionId:a,reason:"prompt_too_long",error:b.message}).catch(()=>{}),yield{type:"error",turnId:r,error:b.message,code:"PROMPT_TOO_LONG",usage:i.totalUsage};return}if(ue&&b&&un(b)){if(K(U)){U.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"media error strip-retry"},i={...i,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld media error: recovery exhausted"),f?.invoke("stop.failure",{sessionId:a,reason:"media_error",error:b.message}).catch(()=>{}),yield{type:"error",turnId:r,error:b.message,code:"IMAGE_ERROR",usage:i.totalUsage};return}if(er(ht)){v.consecutiveTruncations+=1;let m=e.modelMaxOutputTokens??Ue,g=st(v,O,m);if(g.shouldEscalate&>===void 0){v.currentMaxOutputTokens=g.newMax,n.info(`max_output_tokens escalate: ${g.newMax} tokens`),yield{type:"recovery",turnId:r,action:"output_escalation",detail:`${g.newMax} tokens`},i={...i,maxOutputTokensOverride:$e,transition:{reason:"max_output_tokens_escalate"}};continue}if(W<Be){let h={role:"user",content:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};n.info(`max_output_tokens recovery #${W+1}`),yield{type:"recovery",turnId:r,action:"max_output_tokens_recovery",detail:`attempt ${W+1}`},i={...i,messages:[...I,h],maxOutputTokensRecoveryCount:W+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:W+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else v.consecutiveTruncations=0;if(P=ge(P,{replayMessages:S,lastStopReason:"completed"}),f){let m=await f.invoke("stop",{sessionId:a,reason:"completed"});if(m.action==="prevent"){n.info(`stop hook prevented continuation: ${m.reason??"no reason"}`),yield{type:"end",turnId:r,content:i.finalText,usage:i.totalUsage,model:i.currentModel};return}if(m.action==="abort"){let g=m.reason??"Stop hook requested continuation";n.info(`stop hook blocking: ${g}`);let h={role:"user",content:g},y={role:"assistant",content:i.finalText,...w.length>0&&{thinkingBlocks:[...w]}};i={...i,messages:[...S,y,h],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(e.tokenBudget&&e.tokenBudget>0&&i.budgetContinuationCount<5){let m=i.totalUsage.inputTokens+i.totalUsage.outputTokens+(i.totalUsage.reasoningTokens??0),g=m/e.tokenBudget*100,h=m-i.lastBudgetGlobalTokens,y=i.budgetContinuationCount>=je&&h<de&&i.lastBudgetDeltaTokens<de;if(y&&n.info(`token budget early stop: diminishing returns at ${Math.round(g)}% (delta=${h})`),!y&&g<90){let M=i.budgetContinuationCount+1,ke={role:"user",content:sn(g,m,e.tokenBudget)};n.info(`token budget continuation #${M}: ${Math.round(g)}% used`),yield{type:"recovery",turnId:r,action:"budget_continuation",detail:`${Math.round(g)}% used (#${M})`};let yn={role:"assistant",content:i.finalText,...w.length>0&&{thinkingBlocks:[...w]}};i={...i,messages:[...S,yn,ke],budgetContinuationCount:M,lastBudgetDeltaTokens:h,lastBudgetGlobalTokens:m,transition:{reason:"token_budget_continuation"}};continue}}if(!i.stopHookActive&&F===0){let m=l.find(y=>y.role==="user"),g=typeof m?.content=="string"?m.content:"";if(/创建文件|生成文件|写入|写一个|建一个|新建|create\s+(a\s+)?file|write\s+(a\s+)?file|make\s+(a\s+)?file|修改|改成|把.*改/i.test(g)){n.info("AP1 action-verification: user requested file action but no tools were called, injecting nudge");let y={role:"user",content:"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes \u2014 actually make them."},M={role:"assistant",content:i.finalText,...w.length>0&&{thinkingBlocks:[...w]}};i={...i,messages:[...S,M,y],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(!i.stopHookActive&&F>=3&&H.has("write")){let m=0;for(let g of S){let h=g,y=h.is_error===!0||typeof h.content=="string"&&h.content.startsWith("Error:");h.role==="tool"&&typeof h.content=="string"&&!y&&m++}if(m>=3){n.info("AP3 verification nudge: 3+ files created, injecting completeness check");let g={role:"user",content:"You created multiple files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. If everything is correct, confirm completion. If not, fix the issues now."},h={role:"assistant",content:i.finalText,...w.length>0&&{thinkingBlocks:[...w]}};i={...i,messages:[...S,h,g],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(F>0){let m={ok:!0,toolCallCount:F,distinctToolCount:H.size,multiStep:F>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},g=me(m,{tools:[...H]});g&&(yield{type:"skill_instruction",turnId:r,instruction:g})}let p=i.finalText||se(S,n);yield{type:"end",turnId:r,content:p,usage:i.totalUsage,model:i.currentModel};return}for(let c of D){let p=c.function.arguments,m=ie.find(g=>g.function.name===c.function.name);if(m?.backfillObservableInput)try{let g=JSON.parse(c.function.arguments),h={...g};m.backfillObservableInput(h),Object.keys(h).some(M=>!(M in g))&&(p=JSON.stringify(h))}catch{}yield{type:"tool_call",turnId:r,callId:c.id,name:c.function.name,arguments:p}}let gn=w.length===0&&J.length>0?J.join(""):void 0;S.push(_e(D,i.finalText||void 0,w.length>0?w:void 0,gn)),P=Qe(P,{replayMessages:S,pendingToolCallIds:D.map(c=>c.id),completedToolCallIds:P.completedToolCallIds,lastStopReason:"tool_calls"});let bt=[];try{let c=new Te({toolInvoker:o,hooks:f,sessionId:a,turnId:r,log:n,signal:A,maxConcurrentTools:e?.maxConcurrentTools});for(let p of D)c.addTool(p);for await(let p of c.getRemainingResults()){p.blocked&&(yield{type:"tool_blocked",turnId:r,callId:p.callId,name:p.toolName,reason:p.blockReason??"blocked"}),S.push(p.message),bt.push(p.callId),H.add(p.toolName),F++;let m=typeof p.message?.content=="string"?p.message.content:"",g=p.ok&&m?m.slice(0,2e3):void 0;if(yield{type:"tool_result",turnId:r,callId:p.callId,name:p.toolName,ok:p.ok,error:p.error,outputPreview:g},p.ok){let h=D.find(y=>y.id===p.callId);if(h){if(p.toolName==="plan_mode")try{let y=JSON.parse(h.function.arguments);y.action==="exit"&&typeof y.plan=="string"&&y.plan.length>0&&(yield{type:"plan_update",turnId:r,slug:"approved-plan",content:y.plan})}catch{}if(Vo.has(p.toolName))try{let y=JSON.parse(h.function.arguments),M=typeof y.file_path=="string"?y.file_path:typeof y.filePath=="string"?y.filePath:typeof y.path=="string"?y.path:void 0;M&&(yield{type:"artifact",turnId:r,artifactId:`artifact-${p.callId}`,artifactType:Jo(M),title:M.split(/[\\/]/).pop()||M,filePath:M,language:Qo(M)})}catch{}}}}}catch(c){let p=c instanceof Error?c.message:String(c);yield{type:"error",turnId:r,error:p,code:"TOOL_EXECUTION_ERROR",usage:i.totalUsage};return}if(P=ge(P,{replayMessages:S,completedToolCallIds:[...P.completedToolCallIds,...bt],lastStopReason:"tool_calls"}),e.generateToolUseSummary&&D.length>0){let c=D.map(p=>({name:p.function.name,arguments:p.function.arguments}));ae=e.generateToolUseSummary(c).catch(()=>null)}let kt=S.slice(-D.length),fn=kt.length>0&&kt.every(c=>{let p=c?.content;return typeof p!="string"?!1:p.startsWith("Error: ")}),Q=i.consecutiveFailedRounds;if(fn){if(Q+=1,Q>=Oe){let c=i.finalText||se(S,n);n.info(`early exit: ${Q} consecutive failed rounds, returning ${i.finalText?"partial":"fallback"} response`),yield{type:"end",turnId:r,content:c,usage:i.totalUsage,model:i.currentModel};return}}else Q=0;let Ce=i.identicalCallCounts,_t=!1;for(let c of D){let p=`${c.function.name}::${c.function.arguments}`,m=Ce.get(p)??0;if(Ce.set(p,m+1),m+1>Pe&&!_t){let g={role:"user",content:`You have called tool "${c.function.name}" with the exact same arguments ${m+1} times. This is not working. Stop repeating this call. Either try a different approach, different arguments, or report the issue to the user.`};S.push(g),_t=!0,n.info(`AP4 identical-call nudge: ${c.function.name} repeated ${m+1}x`)}}let be=Y+1;if(x>0&&be>x){if(n.info(`max turns reached (${x}), completing`),f){let p=await f.invoke("stop",{sessionId:a,reason:"max_turns"});if(p.action==="abort"){let m=p.reason??"Stop hook requested continuation after max_turns",g={role:"assistant",content:i.finalText,...w.length>0&&{thinkingBlocks:[...w]}};i={...i,messages:[...S,g,{role:"user",content:m}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let c=i.finalText||se(S,n);yield{type:"end",turnId:r,content:c,usage:i.totalUsage,model:i.currentModel};return}if(be>E){if(n.info(`tool loop budget exhausted (${E} rounds), returning`),F>0){let p={ok:!0,toolCallCount:F,distinctToolCount:H.size,multiStep:F>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},m=me(p,{tools:[...H]});m&&(yield{type:"skill_instruction",turnId:r,instruction:m})}let c=i.finalText||se(S,n);yield{type:"end",turnId:r,content:c,usage:i.totalUsage,model:i.currentModel};return}i={messages:S,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:be,transition:{reason:"next_turn"},guardState:v,reactiveCompactState:U,toolLoopState:P,consecutiveFailedRounds:Q,finalText:i.finalText,totalUsage:i.totalUsage,collapseStore:he,currentModel:i.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:i.stopHookActive,lastResponseId:i.lastResponseId,snipRemovedIds:i.snipRemovedIds,contentReplacementState:i.contentReplacementState,budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:Ce}}}function se(e,t){let o=[];for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="tool"&&typeof r.content=="string")o.unshift(r.content.slice(0,500));else if(r.role==="assistant"){if(typeof r.content=="string"&&r.content.trim())return t.info("synthesizeFallbackContent: found assistant text, using it"),r.content;break}else break}return o.length>0?(t.info(`synthesizeFallbackContent: synthesized from ${o.length} tool result(s)`),o.join(`
|
|
16
|
+
`,t+=Ao,t}async function Qt(e,t,o,n=wt){if(e.length<=n||Yt(e))return e;let r=await Vt(e,t,o);return r?Jt(r):e.slice(0,n)+`
|
|
17
|
+
...[truncated ${e.length-n} chars]`}function Io(e){let t=[],o=[];for(let n of e)n.role==="tool"&&typeof n.content=="string"&&n.tool_call_id?Yt(n.content)||o.push({toolCallId:n.tool_call_id,content:n.content,size:n.content.length}):n.role==="assistant"&&o.length>0&&(t.push(o),o=[]);return o.length>0&&t.push(o),t}function Lo(e,t){let o=[],n=[],r=[];for(let a of e){let l=t.replacements.get(a.toolCallId);l!==void 0?o.push({...a,replacement:l}):t.seenIds.has(a.toolCallId)?n.push(a):r.push(a)}return{mustReapply:o,frozen:n,fresh:r}}function Oo(e,t,o){let n=[...e].sort((l,s)=>s.size-l.size),r=[],a=t+e.reduce((l,s)=>l+s.size,0);for(let l of n){if(a<=o)break;r.push(l),a-=l.size}return r}async function Zt(e,t,o,n=It){let r=Io(e);if(r.length===0)return{messages:e,newlyReplacedCount:0};let a=new Map,l=[];for(let d of r){let{mustReapply:f,frozen:M,fresh:C}=Lo(d,t);for(let _ of f)a.set(_.toolCallId,_.replacement);if(C.length===0){for(let _ of d)t.seenIds.add(_.toolCallId);continue}let x=M.reduce((_,v)=>_+v.size,0),k=C.reduce((_,v)=>_+v.size,0),R=x+k>n?Oo(C,x,n):[],L=new Set(R.map(_=>_.toolCallId));for(let _ of d)L.has(_.toolCallId)||t.seenIds.add(_.toolCallId);R.length>0&&l.push(...R)}if(a.size===0&&l.length===0)return{messages:e,newlyReplacedCount:0};let s=await Promise.all(l.map(async d=>{let f=await Vt(d.content,d.toolCallId,o);return{candidate:d,result:f}})),u=0;for(let{candidate:d,result:f}of s){if(t.seenIds.add(d.toolCallId),!f)continue;let M=Jt(f);a.set(d.toolCallId,M),t.replacements.set(d.toolCallId,M),u++}return a.size===0?{messages:e,newlyReplacedCount:0}:{messages:e.map(d=>{if(d.role!=="tool"||!d.tool_call_id)return d;let f=a.get(d.tool_call_id);return f===void 0?d:{...d,content:f}}),newlyReplacedCount:u}}var Po=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),No=new Set(["bash","execute_command","Bash","shell"]),fe=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(t){this.config=t,this.concurrencySafe=t.concurrencySafeTools??Po,this.siblingAbortController=new AbortController,t.signal&&t.signal.addEventListener("abort",()=>{this.siblingAbortController.abort("parent_abort")},{once:!0})}discard(){this.discarded=!0}addTool(t){let o=this.concurrencySafe.has(t.function.name);this.tools.push({id:t.id,toolCall:t,status:"queued",isConcurrencySafe:o,results:[],pendingProgress:[]}),this.processQueue()}canExecuteTool(t){let o=this.tools.filter(r=>r.status==="executing"),n=this.config.maxConcurrentTools;return n&&n>0&&o.length>=n?!1:o.length===0||t&&o.every(r=>r.isConcurrencySafe)}async processQueue(){for(let t of this.tools)if(t.status==="queued"){if(this.canExecuteTool(t.isConcurrencySafe))await this.executeTool(t);else if(!t.isConcurrencySafe)break}}getAbortReason(){return this.discarded?"discarded":this.hasErrored?"sibling_error":this.config.signal?.aborted?"user_interrupted":null}getToolDescription(t){let o;try{o=JSON.parse(t.toolCall.function.arguments)}catch{}let n=o?.command??o?.file_path??o?.pattern??"";if(typeof n=="string"&&n.length>0){let r=n.length>40?n.slice(0,40)+"\u2026":n;return`${t.toolCall.function.name}(${r})`}return t.toolCall.function.name}createSyntheticError(t,o){let n=this.erroredToolDescription,r=o==="user_interrupted"?"User rejected tool use":o==="discarded"?"Streaming fallback - tool execution discarded":n?`Cancelled: parallel tool call ${n} errored`:"Cancelled: parallel tool call errored";return{callId:t.id,toolName:t.toolCall.function.name,ok:!1,error:r,message:Q(t.id,{ok:!1,error:r})}}async executeTool(t){t.status="executing";let n=(async()=>{let r=this.getAbortReason();if(r){t.results.push(this.createSyntheticError(t,r)),t.status="completed";return}let{toolInvoker:a,hooks:l,sessionId:s,turnId:u,log:T}=this.config,d=t.toolCall.function.name,f=!1,M=t.toolCall.function.arguments;if(l)try{let _=await l.invoke("tool.before_invoke",{sessionId:s,turnId:u,callId:t.id,toolName:d,arguments:Do(M)});if(_.action==="abort"){let v=_.reason??"blocked by policy";T.info(`tool ${d} blocked: ${v}`),t.results.push({callId:t.id,toolName:d,ok:!1,error:v,blocked:!0,blockReason:v,message:Q(t.id,{ok:!1,error:v})}),t.status="completed";return}_.action==="continue"&&_.context?.arguments&&(M=JSON.stringify(_.context.arguments))}catch{}let C=await a.invoke(u,d,M,this.siblingAbortController.signal),x=this.getAbortReason();if(x&&!f){t.results.push(this.createSyntheticError(t,x)),t.status="completed";return}let k=!C.error,R=C.result;k&&R&&R.length>5e4&&(R=await Qt(R,t.id,s));let L=Q(t.id,{ok:k,payload:R,error:C.error,toolReferences:C.toolReferences,imageUrls:C.imageUrls});k||(f=!0,No.has(d)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(t),this.siblingAbortController.abort("sibling_error"))),l?.invoke(k?"tool.after_invoke":"tool.invoke_failed",{sessionId:s,turnId:u,callId:t.id,toolName:d,ok:k,...C.error?{error:C.error}:{}}).catch(()=>{}),t.results.push({callId:t.id,toolName:d,ok:k,error:C.error,message:L}),t.status="completed"})();t.promise=n,n.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded){for(let t of this.tools)if(t.status!=="yielded"){if(t.status==="completed"&&t.results.length>0){t.status="yielded";for(let o of t.results)yield o}else if(t.status==="executing"&&!t.isConcurrencySafe)break}}}async*getRemainingResults(){if(!this.discarded){for(;this.hasUnfinishedTools();){await this.processQueue();for(let t of this.getCompletedResults())yield t;if(this.hasExecutingTools()&&!this.hasCompletedResults()){let t=this.tools.filter(n=>n.status==="executing"&&n.promise).map(n=>n.promise),o=new Promise(n=>{this.progressResolve=n});t.length>0&&await Promise.race([...t,o])}}for(let t of this.getCompletedResults())yield t}}hasCompletedResults(){return this.tools.some(t=>t.status==="completed")}hasExecutingTools(){return this.tools.some(t=>t.status==="executing")}hasUnfinishedTools(){return this.tools.some(t=>t.status!=="yielded")}};function Do(e){try{return JSON.parse(e)}catch{return}}import{readFile as Ps}from"node:fs/promises";function Ve(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function Xe(e){let t=0;for(let o of e)t+=Ve(o);return t}var Ye={"deepseek-v4-flash":1e6,"deepseek-v4-pro":1e6,"deepseek-chat":1e6,"deepseek-reasoner":1e6,"gpt-4o":128e3,"gpt-4o-mini":128e3,"claude-sonnet-4-20250514":2e5,"claude-3-5-haiku-20241022":2e5,"gemini-3.1-pro-preview":1e6,"gemini-3-flash-preview":1e6,"gemini-3.1-flash-lite":1e6};function Fo(e){if(!e)return 128e3;if(e in Ye)return Ye[e];let t=e.toLowerCase();for(let[o,n]of Object.entries(Ye))if(t.startsWith(o.toLowerCase()))return n;return 128e3}var Bo=8e3;var Uo=new te(200);var Ns=new ne;function $o(){return Re(new ee(Bo),new G(20,Ve),new Z(Ve))}var jo=null;function en(e,t){let o=t?.budget??xe({modelContextWindow:Fo(t?.model)}),r=(t?.pipeline??$o()).compress(e,o);if(r.droppedCount>0){let a=Xe(e),l=Xe(r.messages);Uo.record({timestamp:Date.now(),strategy:r.strategy,tokensBefore:a,tokensAfter:l,droppedCount:r.droppedCount,latencyMs:r.metrics?.latencyMs??0,usedLlm:!1,cacheInvalidated:r.metrics?.cacheInvalidated??!1,tier:Se(a,o)})}return r.droppedCount>0&&jo?.(r.droppedCount,Xe(r.messages)),r}function tn(e,t,o){let n=o-t;return`[Budget] ${Math.round(e)}% used (${t.toLocaleString()} / ${o.toLocaleString()} tokens). ${n.toLocaleString()} tokens remaining. `+(e>=90?"Wrap up your current task \u9225?you are near the token limit.":"Continue working \u9225?do not summarize prematurely.")}var Yo=new Set(["write","edit","patch","apply_patch"]);function Vo(e){let t=e.split(".").pop()?.toLowerCase()??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(t)?"image":["md","txt","pdf","doc","docx","rtf","html"].includes(t)?"document":["mermaid","mmd","dot","puml","plantuml"].includes(t)?"diagram":["csv","tsv","xlsx","xls"].includes(t)?"table":["ts","tsx","js","jsx","py","rs","go","java","c","cpp","h","cs","rb","sh","sql","json","yaml","yml","toml","xml","css","scss","vue","svelte"].includes(t)?"code":"file"}function Jo(e){let t=e.split(".").pop()?.toLowerCase()??"";return{ts:"typescript",tsx:"typescriptreact",js:"javascript",jsx:"javascriptreact",py:"python",rs:"rust",go:"go",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",rb:"ruby",sh:"shellscript",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",vue:"vue",svelte:"svelte",md:"markdown"}[t]}function Qo(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.round(e),100):bt}function rn(e){let t=e.message.toLowerCase();return e.status===413||t.includes("prompt_too_long")||t.includes("context_length_exceeded")||t.includes("maximum context length")}function Zo(e){return e==="length"||e==="max_tokens"}function sn(e){let t=e.message.toLowerCase();return(t.includes("image")||t.includes("media")||t.includes("file too large")||t.includes("payload too large"))&&(e.status===413||t.includes("too large")||t.includes("size"))}function er(e){let t=e.headers;if(!t)return null;let o=t["retry-after"]??t["Retry-After"];if(!o)return null;let n=parseInt(o,10);return!isNaN(n)&&n>0?n*1e3:null}function tr(e){if(e.status!==400)return null;let t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!t?.[1]||!t?.[3])return null;let o=parseInt(t[1],10),n=parseInt(t[3],10);if(isNaN(o)||isNaN(n))return null;let r=n-o-1e3;return r>=3e3?r:null}function nr(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}async function*an(e,t,o,n){let{turnId:r,sessionId:a,messages:l,tools:s,model:u,apiKey:T,temperature:d=0,hooks:f,signal:M}=e,C={sessionId:a,turnId:r},x=e.maxTurns??0,k=e.querySource,{resolveToolEligibility:R}=await Promise.resolve().then(()=>(on(),nn)),L=R(s,e.toolEligibilityContext),_=L.eligibleTools;for(let S of L.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:S.toolName,reason:"blocked-by-policy"};if(!_.length){yield*or(r,u,l,T,d,M,t,n);return}let v=Qo(e.maxRounds),O={contextWindowTokens:e.contextWindowTokens??Rt,responseBufferTokens:xt,maxOutputTokens:e.maxOutputTokens??St,abortSignal:M,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},H=new Set,F=0,ie=_,ae,i={messages:[...l],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:ze(O),reactiveCompactState:Ke(),toolLoopState:me({maxRounds:v,replayMessages:[...l]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:Ae(),currentModel:u,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:Kt(),budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map},Je=Math.max(x*5,200),Qe=0;for(;;){if(Qe++,Qe>Je){n.info(`hard iteration cap reached (${Je}), forcing completion`);let c=i.finalText||se(i.messages,n);yield{type:"end",turnId:r,content:c,usage:i.totalUsage,model:i.currentModel};return}let{messages:S,maxOutputTokensRecoveryCount:K,hasAttemptedReactiveCompact:ar,maxOutputTokensOverride:Ze,turnCount:X,guardState:E,reactiveCompactState:B,collapseStore:ye}=i,{toolLoopState:P}=i;if(ae){try{let c=await ae;c&&(yield{type:"tool_use_summary",turnId:r,summary:c})}catch{}ae=void 0}if(e.refreshTools&&X>1){let c=e.refreshTools();c!==ie&&(ie=c,n.debug(`tools refreshed: ${c.length} tools`))}if(We(E,O)){n.info(`turn aborted by guard at turn ${X}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:i.totalUsage};return}let U=Ge(E,O);if(U.level==="blocking"){U.reason==="prompt_too_long"&&W(B)&&(B.attemptedThisTurn=!0,E.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${U.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),n.info(`token budget blocking (${U.reason}), ending tool loop`);break}U.level==="warning"&&n.info(`token budget warning: ${U.usagePercent}% used, ${U.remainingTokens} remaining`);let w;{let c=await Zt(S,i.contentReplacementState,a);w=c.messages,c.newlyReplacedCount>0&&(n.info(`tool-result-budget: persisted ${c.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:r,action:"tool_result_budget",detail:`${c.newlyReplacedCount} persisted`})}{let c=Me(w,i.snipRemovedIds);w=c.messages,c.removedCount>0&&(n.info(`snip: removed ${c.removedCount} messages, freed ~${c.tokensFreed} tokens`),yield{type:"recovery",turnId:r,action:"snip",detail:`${c.removedCount} messages`})}{let p=new G().compress(w,0);p.droppedCount>0&&(w=p.messages,n.info(`microcompact: cleared ${p.droppedCount} old tool results`))}if(w=ve(w,ye).messages,E.promptTokens>0){let c=en(w,{budget:O.contextWindowTokens*.75,model:i.currentModel});c.droppedCount>0&&(w=c.messages,n.info(`autocompact: ${c.strategy}, dropped ${c.droppedCount}`),yield{type:"recovery",turnId:r,action:"autocompact",detail:`${c.strategy}: ${c.droppedCount} dropped`},i.hasAttemptedReactiveCompact=!1,f?.invoke("context.after_compact",{...C,removedCount:c.droppedCount}).catch(()=>{}))}w=nr(w);let le=Oe({tools:ie,toolChoice:e.toolChoice??"auto"}),Y=me({maxRounds:v,replayMessages:w,lastStopReason:P.lastStopReason,options:{stopReason:P.lastStopReason}}),et=le.extraSystemPrompt?[{role:"system",content:le.extraSystemPrompt},...Y.state.replayMessages]:Y.state.replayMessages;P=Y.state,Y.recoveryActions.length>0&&n.debug(`tool loop recovery: ${Y.recoveryActions.map(c=>c.detail??c.kind).join("; ")}`),n.debug(`turn ${X}, messages: ${et.length}`),f?.invoke("turn.before_inference",{...C,model:i.currentModel}).catch(()=>{});let ce=!1,tt=[],nt=new Map,ot="stop",N,b=null,ue=!1,V=[],I=[];try{for await(let c of t.stream({model:i.currentModel,messages:et,tools:le.tools,toolChoice:le.normalizedToolChoice??"auto",temperature:d,maxTokens:(Ze??E.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:i.lastResponseId,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},T,M))switch(c.type){case"delta":tt.push(c.text),ce||(yield{type:"delta",turnId:r,text:c.text});break;case"tool_call_delta":ce=!0,Ht(nt,c);break;case"reasoning_delta":V.push(c.text);break;case"reasoning_block_complete":c.signature&&I.push({thinking:V.join(""),signature:c.signature}),V.length=0;break;case"usage":N={inputTokens:c.promptTokens,outputTokens:c.completionTokens,reasoningTokens:c.reasoningTokens,cacheRead:c.cacheReadTokens,cacheWrite:c.cacheCreationTokens};break;case"response_id":i.lastResponseId=c.id;break;case"annotations":yield{type:"annotations",turnId:r,annotations:c.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${c.toolType}: ${c.event}`};break;case"done":ot=c.finishReason;break}if(ce||f?.invoke("turn.after_inference",{...C,model:i.currentModel}).catch(()=>{}),e.postSamplingHooks&&e.postSamplingHooks.length>0){let c=i.currentModel;for(let p of e.postSamplingHooks)try{p({messages:[...w],model:c,sessionId:a})}catch{}}}catch(c){if(c instanceof re&&e.fallbackModel){n.info(`model fallback triggered: ${c.originalModel} \u2192 ${c.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`${c.originalModel} \u2192 ${c.fallbackModel}`},i={...i,currentModel:c.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let p=c instanceof Error?c.message:String(c),m=typeof c?.status=="number"?c.status:void 0;if(!m&&p&&(p.includes("ECONNRESET")||p.includes("EPIPE"))){let h=(i.consecutiveApiRetries??0)+1;if(h>oe){n.info(`stale connection retry limit reached (${oe}), aborting`),yield{type:"error",turnId:r,error:p,code:"RETRIES_EXHAUSTED",usage:i.totalUsage};return}n.info(`stale connection (${p.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:r,action:"stale_connection_retry",detail:p.slice(0,80)},i={...i,consecutiveApiRetries:h,transition:void 0};continue}let g=tr({status:m,message:p});if(g!==null){n.info(`max_tokens overflow: adjusting to ${g}`),E.currentMaxOutputTokens=g,i={...i,maxOutputTokensOverride:g,transition:void 0};continue}if($e(m)){if(i.consecutive529Errors++,i.consecutive529Errors>=Ot&&e.fallbackModel&&i.currentModel!==e.fallbackModel){n.info(`529 \xD7 ${i.consecutive529Errors}: triggering fallback to ${e.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`529 \xD7 ${i.consecutive529Errors}`},i={...i,currentModel:e.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(je()){let h=ge(i.consecutive529Errors);n.info(`persistent retry: waiting ${h}ms (attempt ${i.consecutive529Errors})`);let y=h;for(;y>0;){if(M?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED",usage:i.totalUsage};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(y/1e3)}s (${m})`};let A=Math.min(y,Lt);await new Promise(Ce=>setTimeout(Ce,A)),y-=A}i={...i,transition:void 0};continue}if(Ue(k)){let y=er({status:m,message:p})??ge(i.consecutive529Errors);n.info(`transient ${m}: retry in ${y}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${m} retry in ${y}ms`},await new Promise(A=>setTimeout(A,y)),i={...i,transition:void 0};continue}n.info(`background source ${k}: not retrying ${m}`)}b={status:m,message:p}}if(b&&f?.invoke("turn.after_inference",{...C,model:i.currentModel,response:{error:b.message}}).catch(()=>{}),b)if(rn(b))ue=!0,n.info(`withheld prompt_too_long error (status=${b.status})`);else if(sn(b))ue=!0,n.info(`withheld media_size error (status=${b.status})`);else{let c=He({status:b.status??500,message:b.message},E,O);if(c.action==="reactive_compact"&&W(B)&&(B.attemptedThisTurn=!0,E.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${b.status??500}: ${b.message}`}),c.action==="retry"){let m=(i.consecutiveApiRetries??0)+1;if(m>oe){n.info(`API retry limit reached (${oe}), aborting`);let g=q(b.status,b.message);yield{type:"error",turnId:r,error:b.message,code:g,usage:i.totalUsage};return}yield{type:"recovery",turnId:r,action:"retry",detail:c.reason},i={...i,consecutiveApiRetries:m,transition:void 0};continue}let p=q(b.status,b.message);f?.invoke("stop.failure",{sessionId:a,reason:p,error:b.message}).catch(()=>{}),yield{type:"error",turnId:r,error:b.message,code:p,usage:i.totalUsage};return}N&&(i.totalUsage.inputTokens+=N.inputTokens,i.totalUsage.outputTokens+=N.outputTokens,N.reasoningTokens&&(i.totalUsage.reasoningTokens=(i.totalUsage.reasoningTokens??0)+N.reasoningTokens),N.cacheRead&&(i.totalUsage.cacheRead=(i.totalUsage.cacheRead??0)+N.cacheRead),N.cacheWrite&&(i.totalUsage.cacheWrite=(i.totalUsage.cacheWrite??0)+N.cacheWrite)),N?.inputTokens&&(E.promptTokens=N.inputTokens);let rt=tt.join("");rt&&(i.finalText=rt);let D=[...nt.values()].map(c=>({id:c.id||`tc_${r}_${X}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:c.name,arguments:c.arguments}}));if(D.length===0&&!ce){if(ue&&b&&rn(b)){if(i.transition?.reason!=="collapse_drain_retry"){let m=Ee(w,ye);if(m.committed>0){n.info(`collapse drain: committed ${m.committed} stages`),yield{type:"recovery",turnId:r,action:"collapse_drain",detail:`${m.committed} stages committed`},i={...i,messages:m.messages,transition:{reason:"collapse_drain_retry",committed:m.committed}};continue}}if(W(B)){B.attemptedThisTurn=!0,E.hasAttemptedReactiveCompact=!0,n.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"withheld prompt_too_long"},i={...i,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld 413: recovery exhausted, surfacing error"),f?.invoke("stop.failure",{sessionId:a,reason:"prompt_too_long",error:b.message}).catch(()=>{}),yield{type:"error",turnId:r,error:b.message,code:"PROMPT_TOO_LONG",usage:i.totalUsage};return}if(ue&&b&&sn(b)){if(W(B)){B.attemptedThisTurn=!0,E.hasAttemptedReactiveCompact=!0,n.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"media error strip-retry"},i={...i,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld media error: recovery exhausted"),f?.invoke("stop.failure",{sessionId:a,reason:"media_error",error:b.message}).catch(()=>{}),yield{type:"error",turnId:r,error:b.message,code:"IMAGE_ERROR",usage:i.totalUsage};return}if(Zo(ot)){E.consecutiveTruncations+=1;let m=e.modelMaxOutputTokens??Mt,g=qe(E,O,m);if(g.shouldEscalate&&Ze===void 0){E.currentMaxOutputTokens=g.newMax,n.info(`max_output_tokens escalate: ${g.newMax} tokens`),yield{type:"recovery",turnId:r,action:"output_escalation",detail:`${g.newMax} tokens`},i={...i,maxOutputTokensOverride:vt,transition:{reason:"max_output_tokens_escalate"}};continue}if(K<At){let h={role:"user",content:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};n.info(`max_output_tokens recovery #${K+1}`),yield{type:"recovery",turnId:r,action:"max_output_tokens_recovery",detail:`attempt ${K+1}`},i={...i,messages:[...w,h],maxOutputTokensRecoveryCount:K+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:K+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else E.consecutiveTruncations=0;if(P=pe(P,{replayMessages:S,lastStopReason:"completed"}),f){let m=await f.invoke("stop",{sessionId:a,reason:"completed"});if(m.action==="prevent"){n.info(`stop hook prevented continuation: ${m.reason??"no reason"}`),yield{type:"end",turnId:r,content:i.finalText,usage:i.totalUsage,model:i.currentModel};return}if(m.action==="abort"){let g=m.reason??"Stop hook requested continuation";n.info(`stop hook blocking: ${g}`);let h={role:"user",content:g},y={role:"assistant",content:i.finalText,...I.length>0&&{thinkingBlocks:[...I]}};i={...i,messages:[...S,y,h],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(e.tokenBudget&&e.tokenBudget>0&&i.budgetContinuationCount<5){let m=i.totalUsage.inputTokens+i.totalUsage.outputTokens+(i.totalUsage.reasoningTokens??0),g=m/e.tokenBudget*100,h=m-i.lastBudgetGlobalTokens,y=i.budgetContinuationCount>=Et&&h<we&&i.lastBudgetDeltaTokens<we;if(y&&n.info(`token budget early stop: diminishing returns at ${Math.round(g)}% (delta=${h})`),!y&&g<90){let A=i.budgetContinuationCount+1,Ce={role:"user",content:tn(g,m,e.tokenBudget)};n.info(`token budget continuation #${A}: ${Math.round(g)}% used`),yield{type:"recovery",turnId:r,action:"budget_continuation",detail:`${Math.round(g)}% used (#${A})`};let mn={role:"assistant",content:i.finalText,...I.length>0&&{thinkingBlocks:[...I]}};i={...i,messages:[...S,mn,Ce],budgetContinuationCount:A,lastBudgetDeltaTokens:h,lastBudgetGlobalTokens:m,transition:{reason:"token_budget_continuation"}};continue}}if(!i.stopHookActive&&F===0){let m=l.find(y=>y.role==="user"),g=typeof m?.content=="string"?m.content:"";if(/创建文件|生成文件|写入|写一个|建一个|新建|create\s+(a\s+)?file|write\s+(a\s+)?file|make\s+(a\s+)?file|修改|改成|把.*改/i.test(g)){n.info("AP1 action-verification: user requested file action but no tools were called, injecting nudge");let y={role:"user",content:"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes \u2014 actually make them."},A={role:"assistant",content:i.finalText,...I.length>0&&{thinkingBlocks:[...I]}};i={...i,messages:[...S,A,y],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(!i.stopHookActive&&F>=3&&H.has("write")){let m=0;for(let g of S){let h=g,y=h.is_error===!0||typeof h.content=="string"&&h.content.startsWith("Error:");h.role==="tool"&&typeof h.content=="string"&&!y&&m++}if(m>=3){n.info("AP3 verification nudge: 3+ files created, injecting completeness check");let g={role:"user",content:"You created multiple files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. If everything is correct, confirm completion. If not, fix the issues now."},h={role:"assistant",content:i.finalText,...I.length>0&&{thinkingBlocks:[...I]}};i={...i,messages:[...S,h,g],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(F>0){let m={ok:!0,toolCallCount:F,distinctToolCount:H.size,multiStep:F>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},g=de(m,{tools:[...H]});g&&(yield{type:"skill_instruction",turnId:r,instruction:g})}let p=i.finalText||se(S,n);yield{type:"end",turnId:r,content:p,usage:i.totalUsage,model:i.currentModel};return}for(let c of D){let p=c.function.arguments,m=ie.find(g=>g.function.name===c.function.name);if(m?.backfillObservableInput)try{let g=JSON.parse(c.function.arguments),h={...g};m.backfillObservableInput(h),Object.keys(h).some(A=>!(A in g))&&(p=JSON.stringify(h))}catch{}yield{type:"tool_call",turnId:r,callId:c.id,name:c.function.name,arguments:p}}let dn=I.length===0&&V.length>0?V.join(""):void 0;S.push(be(D,i.finalText||void 0,I.length>0?I:void 0,dn)),P=Be(P,{replayMessages:S,pendingToolCallIds:D.map(c=>c.id),completedToolCallIds:P.completedToolCallIds,lastStopReason:"tool_calls"});let st=[];try{let c=new fe({toolInvoker:o,hooks:f,sessionId:a,turnId:r,log:n,signal:M,maxConcurrentTools:e?.maxConcurrentTools});for(let p of D)c.addTool(p);for await(let p of c.getRemainingResults()){p.blocked&&(yield{type:"tool_blocked",turnId:r,callId:p.callId,name:p.toolName,reason:p.blockReason??"blocked"}),S.push(p.message),st.push(p.callId),H.add(p.toolName),F++;let m=typeof p.message?.content=="string"?p.message.content:"",g=p.ok&&m?m.slice(0,2e3):void 0;if(yield{type:"tool_result",turnId:r,callId:p.callId,name:p.toolName,ok:p.ok,error:p.error,outputPreview:g},p.ok){let h=D.find(y=>y.id===p.callId);if(h){if(p.toolName==="plan_mode")try{let y=JSON.parse(h.function.arguments);y.action==="exit"&&typeof y.plan=="string"&&y.plan.length>0&&(yield{type:"plan_update",turnId:r,slug:"approved-plan",content:y.plan})}catch{}if(Yo.has(p.toolName))try{let y=JSON.parse(h.function.arguments),A=typeof y.file_path=="string"?y.file_path:typeof y.filePath=="string"?y.filePath:typeof y.path=="string"?y.path:void 0;A&&(yield{type:"artifact",turnId:r,artifactId:`artifact-${p.callId}`,artifactType:Vo(A),title:A.split(/[\\/]/).pop()||A,filePath:A,language:Jo(A)})}catch{}}}}}catch(c){let p=c instanceof Error?c.message:String(c);yield{type:"error",turnId:r,error:p,code:"TOOL_EXECUTION_ERROR",usage:i.totalUsage};return}if(P=pe(P,{replayMessages:S,completedToolCallIds:[...P.completedToolCallIds,...st],lastStopReason:"tool_calls"}),e.generateToolUseSummary&&D.length>0){let c=D.map(p=>({name:p.function.name,arguments:p.function.arguments}));ae=e.generateToolUseSummary(c).catch(()=>null)}let it=S.slice(-D.length),pn=it.length>0&&it.every(c=>{let p=c?.content;return typeof p!="string"?!1:p.startsWith("Error: ")}),J=i.consecutiveFailedRounds;if(pn){if(J+=1,J>=kt){let c=i.finalText||se(S,n);n.info(`early exit: ${J} consecutive failed rounds, returning ${i.finalText?"partial":"fallback"} response`),yield{type:"end",turnId:r,content:c,usage:i.totalUsage,model:i.currentModel};return}}else J=0;let Te=i.identicalCallCounts,at=!1;for(let c of D){let p=`${c.function.name}::${c.function.arguments}`,m=Te.get(p)??0;if(Te.set(p,m+1),m+1>_t&&!at){let g={role:"user",content:`You have called tool "${c.function.name}" with the exact same arguments ${m+1} times. This is not working. Stop repeating this call. Either try a different approach, different arguments, or report the issue to the user.`};S.push(g),at=!0,n.info(`AP4 identical-call nudge: ${c.function.name} repeated ${m+1}x`)}}let he=X+1;if(x>0&&he>x){if(n.info(`max turns reached (${x}), completing`),f){let p=await f.invoke("stop",{sessionId:a,reason:"max_turns"});if(p.action==="abort"){let m=p.reason??"Stop hook requested continuation after max_turns",g={role:"assistant",content:i.finalText,...I.length>0&&{thinkingBlocks:[...I]}};i={...i,messages:[...S,g,{role:"user",content:m}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let c=i.finalText||se(S,n);yield{type:"end",turnId:r,content:c,usage:i.totalUsage,model:i.currentModel};return}if(he>v){if(n.info(`tool loop budget exhausted (${v} rounds), returning`),F>0){let p={ok:!0,toolCallCount:F,distinctToolCount:H.size,multiStep:F>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},m=de(p,{tools:[...H]});m&&(yield{type:"skill_instruction",turnId:r,instruction:m})}let c=i.finalText||se(S,n);yield{type:"end",turnId:r,content:c,usage:i.totalUsage,model:i.currentModel};return}i={messages:S,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:he,transition:{reason:"next_turn"},guardState:E,reactiveCompactState:B,toolLoopState:P,consecutiveFailedRounds:J,finalText:i.finalText,totalUsage:i.totalUsage,collapseStore:ye,currentModel:i.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:i.stopHookActive,lastResponseId:i.lastResponseId,snipRemovedIds:i.snipRemovedIds,contentReplacementState:i.contentReplacementState,budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:Te}}}function se(e,t){let o=[];for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="tool"&&typeof r.content=="string")o.unshift(r.content.slice(0,500));else if(r.role==="assistant"){if(typeof r.content=="string"&&r.content.trim())return t.info("synthesizeFallbackContent: found assistant text, using it"),r.content;break}else break}return o.length>0?(t.info(`synthesizeFallbackContent: synthesized from ${o.length} tool result(s)`),o.join(`
|
|
18
18
|
|
|
19
|
-
`)):""}async function*
|
|
19
|
+
`)):""}async function*or(e,t,o,n,r,a,l,s){let u=[],T;s.debug(`single LLM round, messages: ${o.length}`);for await(let d of l.stream({model:t,messages:o,temperature:r},n,a))switch(d.type){case"delta":u.push(d.text),yield{type:"delta",turnId:e,text:d.text};break;case"usage":T={inputTokens:d.promptTokens,outputTokens:d.completionTokens,reasoningTokens:d.reasoningTokens,cacheRead:d.cacheReadTokens,cacheWrite:d.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:e,content:u.join(""),usage:T??{inputTokens:0,outputTokens:0},model:t}}var rr={coding:[/(?:bug|error|fix|debug|报错|修复|编译|compile|build|lint)/i,/(?:implement|refactor|重构|实现|代码|code|function|method|class)/i,/(?:test|测试|vitest|jest|断言|assert)/i,/(?:type(?:script)?|接口|interface|generic|泛型)/i,/(?:import|export|module|依赖|package|npm|pnpm)/i,/(?:git|commit|branch|merge|rebase|PR|MR)/i],config:[/(?:deploy|部署|运维|docker|container|kubernetes|k8s)/i,/(?:port|端口|config|配置|env|环境变量|.env)/i,/(?:server|service|daemon|进程|systemd|nginx|redis)/i,/(?:版本|version|upgrade|migrate|迁移)/i,/(?:domain|域名|ssl|cert|证书|DNS)/i],conversation:[/(?:你好|hi|hello|hey|请问|问一下)/i,/(?:我(?:喜欢|偏好|习惯|想)|prefer|I (?:like|want|need))/i,/(?:帮我|help me|能不能|可以吗|would you)/i,/(?:style|风格|format|格式|命名|naming)/i],learning:[/(?:best practice|最佳实践|pattern|模式|惯例|convention)/i,/(?:怎么做|how to|how do|what's the|推荐|recommend)/i,/(?:为什么|why|原因|reason|explain|解释)/i,/(?:lesson|经验|教训|gotcha|pitfall|坑)/i],decision:[/(?:should|应该|选择|choose|decision|决定|trade-?off|权衡)/i,/(?:vs|versus|对比|compare|区别|difference)/i,/(?:architecture|架构|方案|approach|strategy)/i,/(?:pros|cons|优缺点|利弊|好处|坏处)/i],general:[]},sr={coding:{preferred:["lesson","pattern","fact"],deprioritized:["preference"]},config:{preferred:["fact","decision","lesson"],deprioritized:["preference","skill-learning"]},conversation:{preferred:["preference","fact"],deprioritized:["pattern","skill-learning"]},learning:{preferred:["lesson","pattern","skill-learning"],deprioritized:["preference"]},decision:{preferred:["decision","fact","lesson"],deprioritized:["skill-learning","preference"]},general:{preferred:[],deprioritized:[]}};function ln(e){if(!e||e.length<5)return{scenario:"general",preferred:[],deprioritized:[],confidence:0};let t=[];for(let[r,a]of Object.entries(rr)){if(r==="general")continue;let l=a.filter(s=>s.test(e)).length;if(l>0){let s=Math.min(1,l/2);t.push({scenario:r,score:s})}}if(t.length===0)return{scenario:"general",preferred:[],deprioritized:[],confidence:0};t.sort((r,a)=>a.score-r.score);let o=t[0];if(o.score<.5)return{scenario:"general",preferred:[],deprioritized:[],confidence:o.score};let n=sr[o.scenario];return{scenario:o.scenario,preferred:n.preferred,deprioritized:n.deprioritized,confidence:o.score}}var un=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;constructor(t){this.transport=t.llmTransport,this.apiKey=t.apiKey,this.toolInvoker=t.toolInvoker,this.log=t.log,this.hooks=t.hooks,this.maxRounds=Math.min(t.maxRounds??25,100)}async*run(t,o){let{turnId:n,messages:r,tools:a,systemPrompt:l,config:s}=t,u={sessionId:t.sessionId,turnId:n};yield{type:"start",turnId:n},this.hooks?.invoke("turn.submitted",{...u,prompt:r[r.length-1]?.content??void 0}).catch(()=>{});let T=Fe(r),d=[];if(l&&d.push({role:"system",content:l}),d.push(...T),this.hooks){let C=T.filter(k=>k.role==="user").pop(),x=typeof C?.content=="string"?C.content.slice(0,500):void 0;if(x)try{let k=ln(x),R=await this.hooks.invoke("memory.before_recall",{sessionId:t.sessionId,turnId:n,query:x,preferredCategories:k.preferred.length>0?k.preferred:void 0,deprioritizedCategories:k.deprioritized.length>0?k.deprioritized:void 0}),L=R?.context?.recalledMemories;if(L&&L.length>0){let _=L.map(v=>`- ${v.text}`).join(`
|
|
20
20
|
`);d.splice(l?1:0,0,{role:"system",content:`[Recalled from long-term memory]
|
|
21
|
-
${_}`})}this.hooks.invoke("memory.after_recall",{sessionId:t.sessionId,turnId:n,blockCount:R?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let f=s?.model??"",
|
|
21
|
+
${_}`})}this.hooks.invoke("memory.after_recall",{sessionId:t.sessionId,turnId:n,blockCount:R?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let f=s?.model??"",M=Math.min(s?.maxRounds??this.maxRounds,100);try{let C=s?.summaryModel?async R=>{try{let L=R.map(O=>`${O.name}(${O.arguments.slice(0,200)})`).join(", "),_=this.transport.stream({model:s.summaryModel,messages:[{role:"system",content:"Summarize the tool usage in ~30 chars, git-commit-subject style. Reply with ONLY the summary, nothing else."},{role:"user",content:L}],tools:[],maxTokens:60},s.apiKey??this.apiKey),v="";for await(let O of _)O.type==="delta"&&(v+=O.text);return v.trim()||null}catch{return null}}:void 0,x={turnId:n,sessionId:t.sessionId,messages:d,tools:a,model:f,apiKey:s?.apiKey??this.apiKey,temperature:s?.temperature,maxRounds:M,contextWindowTokens:s?.contextWindowTokens,maxOutputTokens:s?.maxOutputTokens,modelMaxOutputTokens:s?.modelMaxOutputTokens,toolChoice:s?.toolChoice,parentDepth:s?.parentDepth,hooks:this.hooks,fallbackModel:s?.fallbackModel,maxTurns:s?.maxTurns,tokenBudget:s?.tokenBudget,maxConcurrentTools:s?.maxConcurrentTools,streamRequired:s?.streamRequired,reasoning:s?.reasoning,promptCacheKey:s?.promptCacheKey,promptCacheRetention:s?.promptCacheRetention,serviceTier:s?.serviceTier,openaiBuiltinTools:s?.openaiBuiltinTools,maxToolCalls:s?.maxToolCalls,parallelToolCalls:s?.parallelToolCalls,textVerbosity:s?.textVerbosity,generateToolUseSummary:C,signal:o},k;for await(let R of an(x,this.transport,this.toolInvoker,this.log))k=R,yield R;k?.type==="end"?this.hooks?.invoke("turn.completed",{...u}).catch(()=>{}):k?.type==="error"&&this.hooks?.invoke("turn.failed",{...u,code:k.code,error:k.error}).catch(()=>{})}catch(C){if(o?.aborted)this.hooks?.invoke("turn.failed",{...u,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED"};else{let x=C instanceof Error?C.message:String(C),k=typeof C?.status=="number"?C.status:void 0,R=q(k,x);this.log.error(`turn ${n} error [${R}, retryable=${_e(R)}]: ${x}`),this.hooks?.invoke("turn.failed",{...u,code:R,error:x}).catch(()=>{}),yield{type:"error",turnId:n,error:x,code:R}}}}};export{un as Agent};
|