qlogicagent 2.11.8 → 2.11.9
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
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
function xe(e,t,r,o){return{role:"assistant",content:t||null,tool_calls:e,...r&&r.length>0?{thinkingBlocks:r}:{},...o?{reasoning_content:o}:{}}}function pe(e,t){let r=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:r,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var go=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,q={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]},fo=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,yo=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,To=512,ho=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Co=new Set([500,502,503,504,521,522,523,524,529]),ko=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ro=["upgrade your plan","upgrade plan","current plan","subscription"],bo=["daily","weekly","monthly"],_o=["try again","retry","temporary","cooldown"],xo=["usage limit","rate limit","organization usage"],So=["organization","workspace"],Mo=["billing period","exceeded","reached","exhausted"],Ao=/["']?(?: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,vo=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function z(e,t){if(!e)return!1;let r=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(r):r.includes(o))}function Eo(e){return z(e,q.format)}function ut(e){return z(e,q.rateLimit)}function Io(e){return z(e,q.timeout)}function wo(e){return go.test(e)}function Se(e){let t=e.toLowerCase();return t?e.length>To?yo.test(t):z(t,q.billing)?!0:fo.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function dt(e){return z(e,q.authPermanent)}function Lo(e){return z(e,q.auth)}function pt(e){return z(e,q.overloaded)}function H(e,t){return t.some(r=>e.includes(r))}function Po(e){return H(e,ko)||H(e,Ro)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Oo(e){let t=H(e,bo),r=e.includes("spend limit")||e.includes("spending limit"),o=H(e,So);return H(e,_o)&&H(e,xo)||t&&(e.includes("usage limit")||r)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(r||H(e,Mo))}function No(e){return e.trim().toLowerCase().replace(vo,"").trim()}function mt(e){let t=No(e);return!t||Po(t)?"billing":ut(t)||Oo(t)?"rate_limit":"billing"}function Do(e){return Ao.test(e)?mt(e):null}function gt(e){let t=e.match(ho);if(!t)return null;let r=Number(t[1]);return Number.isFinite(r)?{code:r,rest:(t[2]??"").trim()}:null}function Fo(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Bo(e){let t=e.trim();if(!t)return!1;let r=gt(t);return r?Co.has(r.code):!1}function ft(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?mt(t):"billing":e===429?"rate_limit":e===401||e===403?t&&dt(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&pt(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&Se(t)?"billing":"format":null}function Uo(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 $o(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 yt(e){if($o(e))return"session_expired";if(Uo(e))return"model_not_found";let t=Do(e);return t||(wo(e)?Se(e)?"billing":"rate_limit":ut(e)?"rate_limit":pt(e)?"overloaded":Bo(e)?gt(e.trim())?.code===529?"overloaded":"timeout":Fo(e)?"timeout":Eo(e)?"format":Se(e)?"billing":Io(e)?"timeout":dt(e)?"auth_permanent":Lo(e)?"auth":null)}var jo={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"},Go=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function K(e,t){let r=ft(e,t)??(t?yt(t):null);return r?jo[r]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Me(e){return Go.has(e)}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 Ho=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"]),ee=class{constructor(t=20,r=Tt){this.preserveRecentCount=t;this.estimateTokens=r}preserveRecentCount;estimateTokens;compress(t,r){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=t.length-this.preserveRecentCount,n=0,l=0;return{messages:t.map((a,m)=>{if(m>=o||a.role!=="tool"||typeof a.content!="string"||!a.name||!Ho.has(a.name)||a.content.length<=200)return a;let T=this.estimateTokens(a);return l+=T,n++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:n,strategy:"micro-compact",metrics:n>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function Ae(e,t,r=Tt){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,n=0,l=[];for(let a of e){let m=a.tool_call_id??"";if(m&&t.has(m)){o+=r(a),n++,t.delete(m);continue}l.push(a)}let d=n>0?{role:"system",content:`[${n} messages removed by snip]`}:void 0;return{messages:l,tokensFreed:o,removedCount:n,boundaryMessage:d}}function ve(){return{stages:[]}}function Ee(e,t,r){let o=r?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let l=ht(e,t),d=qo(l,t,o);if(d.length===0)return{messages:l,stagedCount:0};for(let a of d)t.stages.push(a);return l=ht(e,t),{messages:l,stagedCount:d.length}}function Ie(e,t){let r=0;for(let o of t.stages)o.committed||(o.committed=!0,r++);return r===0?{messages:e,committed:0}:{messages:Ct(e,t),committed:r}}function ht(e,t){return t.stages.filter(o=>o.committed).length===0?e:Ct(e,t)}function Ct(e,t){let r=t.stages.filter(n=>n.committed).sort((n,l)=>l.range[0]-n.range[0]),o=[...e];for(let n of r){let[l,d]=n.range;if(l>=o.length)continue;let a=Math.min(d,o.length),m={role:"system",content:n.summary};o.splice(l,a-l,m)}return o}function qo(e,t,r){let o=Math.max(0,e.length-Math.floor(r/2)),n=[],l=new Set(t.stages.map(m=>`${m.range[0]}-${m.range[1]}`)),d=-1,a=0;for(let m=0;m<o;m++){let T=e[m];if(T.role==="tool"||T.role==="assistant"&&typeof T.content=="string"&&T.content==="")d<0&&(d=m),a++;else{if(a>=3){let k=`${d}-${d+a}`;l.has(k)||n.push({id:`collapse_${d}_${d+a}`,range:[d,d+a],summary:`[${a} tool results collapsed]`,committed:!1})}d=-1,a=0}}if(a>=3){let m=`${d}-${d+a}`;l.has(m)||n.push({id:`collapse_${d}_${d+a}`,range:[d,d+a],summary:`[${a} tool results collapsed]`,committed:!1})}return n}import{existsSync as Le,readFileSync as Ut,writeFileSync as zo,readdirSync as $t,mkdirSync as Ko}from"node:fs";import{join as Pe,dirname as Wo}from"node:path";var kt=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Rt=3,bt=2,me=2,_t=128e3,xt=13e3,St=16384,Mt=65536,At=3,vt=65536,we=500,Et=3;var It=3e4,wt=3,te=2;var Lt=20;var Pt=3,Ot=2,Nt=300*1e3,Dt=3,Ft=720*60*60*1e3;var Gn=300*1e3;var Hn=3600*1e3;var qn=50*1024,zn=500*1024,Kn=500*1024*1024,Wn=50*1024*1024;var Xn=60*1024;var jt=0;var Xo="skill-patterns.json";function Gt(e){return Pe(e,".qlogicagent",Xo)}function Yo(e){let t=Gt(e);try{return JSON.parse(Ut(t,"utf8"))}catch{return{version:1,patterns:{}}}}function Bt(e,t){let r=Gt(e);Ko(Wo(r),{recursive:!0}),zo(r,JSON.stringify(t,null,2),"utf8")}function Vo(e){let t=Date.now()-Ft;for(let[r,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[r]}function Ht(e,t){if(t.length===0)return!1;let r=ge(t),o=Yo(e);Vo(o);let n=new Date().toISOString(),l=o.patterns[r];if(l||(l={signature:r,count:0,firstSeen:n,lastSeen:n,promoted:!1},o.patterns[r]=l),l.promoted)return Bt(e,o),!1;l.count++,l.lastSeen=n;let d=l.count>=Dt;return d&&(l.promoted=!0),Bt(e,o),d}function ge(e){return[...e].sort().join("+")}function Jo(e,t){if(!Le(t))return null;let r=ge(e);try{let o=$t(t,{withFileTypes:!0});for(let n of o){if(!n.isDirectory())continue;let l=Pe(t,n.name,"SKILL.md");try{let a=Ut(l,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let m=a[1].split(`
|
|
2
|
-
`).map(T=>T.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(ge(m)===r)return n.name}}catch{}}}catch{}return null}function Zo(e){if(!Le(e))return 0;try{return $t(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&Le(Pe(e,t.name,"SKILL.md"))).length}catch{return 0}}function Qo(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<Pt||e.distinctToolCount<Ot||Date.now()-jt<Nt||t?.projectSkillsDir&&(Zo(t.projectSkillsDir)>=Lt||t.tools.length>0&&Jo(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Ht(t.projectRoot,t.tools))}function en(e){return e.existingSkillName?e.feedback==="negative":!1}function fe(e,t){return en(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Qo(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 qt(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 tn(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function on(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function nn(e){if(!e.eligibility?.length)return[...e.tools];let t=on(e.eligibility);return e.tools.filter(r=>{let o=qt(r);if(!o)return!1;let n=t.get(o);return!n||tn(n.status)})}function rn(e){let t=[],r=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&r.requireAutoWhenThinking){let n=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;n&&n!=="auto"&&n!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&r.allowRequiredToolChoice===!1){let n=r.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${n}.`),o=n}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&r.allowNamedToolChoice===!1){let n=r.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${n}.`),o=n}return{normalizedToolChoice:o,warnings:t}}function Oe(e){let t=rn({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),r=t.normalizedToolChoice,o=[...t.warnings],n=nn({tools:e.tools,eligibility:e.eligibility});if(!r||r==="auto")return{tools:n,normalizedToolChoice:r,warnings:o};if(r==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(r==="required"){if(n.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:n,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof r=="object"&&!Array.isArray(r)&&r.type==="function"){let l=r.function??void 0,d=typeof l?.name=="string"?l.name.trim():"";if(!d)throw new Error("tool_choice.function.name is required");let a=n.filter(m=>qt(m)===d);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${d}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:d}},extraSystemPrompt:`You must call the ${d} tool before responding.`,warnings:o}}return{tools:n,normalizedToolChoice:r,warnings:o}}var sn=["stop","aborted","timeout","cancelled","interrupted","error"],an=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function zt(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function ln(e,t){return{...e,content:[...zt(e.content),...zt(t.content)]}}function cn(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 un(e){return new Set((e??sn).map(t=>t.trim().toLowerCase()))}function dn(e,t){return e?un(t).has(e.trim().toLowerCase()):!1}function Ne(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let m=a.tool_calls.filter(T=>cn(T));return{...a,...m.length>0?{tool_calls:m}:{tool_calls:void 0}}}return{...a}}),r=new Set;for(let a of t)if(!(a.role!=="assistant"||!Array.isArray(a.tool_calls)))for(let m of a.tool_calls)typeof m.id=="string"&&m.id&&r.add(m.id);let o=t.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&r.has(a.tool_call_id))),n=new Set;for(let a of o)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&n.add(a.tool_call_id);let l=[];for(let a of o){if(a.role==="assistant"&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0){let m=a.tool_calls.filter(T=>typeof T.id=="string"&&n.has(T.id));if(m.length===0){let{tool_calls:T,...h}=a;h.content!=null&&h.content!==""&&l.push(h);continue}if(m.length<a.tool_calls.length){l.push({...a,tool_calls:m});continue}}l.push(a)}let d=[];for(let a of l){let m=d.length>0?d[d.length-1]:void 0;if(a.role==="user"&&m?.role==="user"){d[d.length-1]=ln(m,a);continue}d.push(a)}return d}function De(e,t){return dn(t?.stopReason,t?.forcedStopReasons)?e.map(r=>{if(r.role!=="assistant")return{...r};let o={...r};for(let n of an)delete o[n];return o}):[...e]}function Fe(e,t){let r=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let l of e)l.role==="tool"&&typeof l.tool_call_id=="string"&&l.tool_call_id&&o.add(l.tool_call_id);let n=[];for(let l of e)if(n.push({...l}),!(l.role!=="assistant"||!Array.isArray(l.tool_calls)||l.tool_calls.length===0))for(let d of l.tool_calls)typeof d.id!="string"||!d.id||o.has(d.id)||(o.add(d.id),n.push({role:"tool",tool_call_id:d.id,content:r}));return n}function Be(e,t){let r=Ne(e),o=De(r,t);return Fe(o,t)}function pn(e){let t=new Set,r=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let n of o.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&r.add(o.tool_call_id)}return[...t].filter(o=>!r.has(o))}function mn(e){let t=new Set;for(let r of e)r.role==="tool"&&typeof r.tool_call_id=="string"&&r.tool_call_id&&t.add(r.tool_call_id);return[...t]}function gn(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Ue(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 ye(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 Te(e){let t=[],r=Ne(e.replayMessages);r.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=De(r,e.options);o.some((l,d)=>l!==r[d])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let n=Fe(o,e.options);return n.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:gn({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:n,pendingToolCallIds:pn(n),completedToolCallIds:mn(n)}),recoveryActions:t}}var fn=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function $e(e){return e?fn.has(e):!0}function je(e){return e===429||e===529}function he(e,t=500,r=32e3){let o=Math.min(t*Math.pow(2,e-1),r);return o+Math.floor(Math.random()*o*.25)}var ir={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Ce(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var oe=class extends Error{constructor(r,o){super(`Model fallback triggered: ${r} -> ${o}`);this.originalModel=r;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function Ge(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function He(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let r=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=r>0?e.promptTokens/r*100:100;return e.promptTokens>=r?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:r-e.promptTokens}:{level:"ok"}}function qe(e,t,r){let o=e.message?.toLowerCase()??"",n=e.status??0;return n===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&r.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:n>=500&&n<600?{action:"retry",reason:`server_error_${n}`}:n===429?{action:"retry",reason:"rate_limited"}:n===401||n===403?{action:"abort",reason:"auth_error"}:n===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function ze(e,t,r){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,r);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function Ke(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Tn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function We(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function W(e,t=Tn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function Xe(e,t){let r=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(r.id=t.id),t.name&&(r.name=t.name),r.arguments+=t.arguments??"",e.set(t.index,r)}function Kt(e,t){let r=typeof t.message?.content=="string"?t.message.content:"",o=r?r.slice(0,2e3):void 0,n=t.details,l=typeof n?.stdout=="string"?n.stdout.slice(0,8e3):void 0,d=typeof n?.stderr=="string"?n.stderr.slice(0,4e3):void 0,a=typeof n?.exitCode=="number"?n.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:o,durationMs:t.durationMs,exitCode:a,stdout:l,stderr:d,details:n}}var hn=new Set(["write","edit","patch","apply_patch"]);function Wt(e){let{turnId:t,result:r,toolCalls:o}=e;if(!r.ok)return[];let n=o.find(a=>a.id===r.callId);if(!n)return[];let l=[],d=Cn(n.function.arguments);if(!d)return l;if(r.toolName==="plan_mode"&&d.action==="exit"&&typeof d.plan=="string"&&d.plan.length>0&&l.push({type:"plan_update",turnId:t,slug:"approved-plan",content:d.plan}),hn.has(r.toolName)){let a=kn(d);a&&l.push({type:"artifact",turnId:t,artifactId:`artifact-${r.callId}`,artifactType:Rn(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:bn(a)})}return l}function Cn(e){try{return JSON.parse(e)}catch{return null}}function kn(e){return typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:void 0}function Rn(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 bn(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]}var xn=/^no (matches|files|results) found\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,Sn=new Set(["search","grep","glob","find","list","read","exec"]);function Xt(e){if(!Sn.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&xn.test(t)}function Ye(e,t){for(let r=e.length-1;r>=0;r--){let o=e[r];if(!o||o.role!=="tool")continue;let n=typeof o.content=="string"?o.content:"";if(n.startsWith("Error: "))return n.slice(7).trim()}}function Yt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.round(e),100):kt}function Vt(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function X(e,t){let r=[];for(let o=e.length-1;o>=0;o--){let n=e[o];if(n.role==="tool"&&typeof n.content=="string")r.unshift(n.content.slice(0,500));else if(n.role==="assistant"){if(typeof n.content=="string"&&n.content.trim())return t.info("synthesizeFallbackContent: found assistant text, using it"),n.content;break}else break}return r.length>0?(t.info(`synthesizeFallbackContent: synthesized from ${r.length} tool result(s)`),r.join(`
|
|
1
|
+
function Se(e,t,r,o){return{role:"assistant",content:t||null,tool_calls:e,...r&&r.length>0?{thinkingBlocks:r}:{},...o?{reasoning_content:o}:{}}}function ue(e,t){let r=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:r,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var go=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,q={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]},fo=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,yo=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,To=512,ho=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Co=new Set([500,502,503,504,521,522,523,524,529]),ko=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ro=["upgrade your plan","upgrade plan","current plan","subscription"],bo=["daily","weekly","monthly"],_o=["try again","retry","temporary","cooldown"],xo=["usage limit","rate limit","organization usage"],So=["organization","workspace"],Mo=["billing period","exceeded","reached","exhausted"],Ao=/["']?(?: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,vo=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function z(e,t){if(!e)return!1;let r=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(r):r.includes(o))}function Eo(e){return z(e,q.format)}function ut(e){return z(e,q.rateLimit)}function Io(e){return z(e,q.timeout)}function wo(e){return go.test(e)}function Me(e){let t=e.toLowerCase();return t?e.length>To?yo.test(t):z(t,q.billing)?!0:fo.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function dt(e){return z(e,q.authPermanent)}function Lo(e){return z(e,q.auth)}function pt(e){return z(e,q.overloaded)}function H(e,t){return t.some(r=>e.includes(r))}function Po(e){return H(e,ko)||H(e,Ro)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Oo(e){let t=H(e,bo),r=e.includes("spend limit")||e.includes("spending limit"),o=H(e,So);return H(e,_o)&&H(e,xo)||t&&(e.includes("usage limit")||r)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(r||H(e,Mo))}function No(e){return e.trim().toLowerCase().replace(vo,"").trim()}function mt(e){let t=No(e);return!t||Po(t)?"billing":ut(t)||Oo(t)?"rate_limit":"billing"}function Do(e){return Ao.test(e)?mt(e):null}function gt(e){let t=e.match(ho);if(!t)return null;let r=Number(t[1]);return Number.isFinite(r)?{code:r,rest:(t[2]??"").trim()}:null}function Fo(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Bo(e){let t=e.trim();if(!t)return!1;let r=gt(t);return r?Co.has(r.code):!1}function ft(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?mt(t):"billing":e===429?"rate_limit":e===401||e===403?t&&dt(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&pt(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&Me(t)?"billing":"format":null}function Uo(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 $o(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 yt(e){if($o(e))return"session_expired";if(Uo(e))return"model_not_found";let t=Do(e);return t||(wo(e)?Me(e)?"billing":"rate_limit":ut(e)?"rate_limit":pt(e)?"overloaded":Bo(e)?gt(e.trim())?.code===529?"overloaded":"timeout":Fo(e)?"timeout":Eo(e)?"format":Me(e)?"billing":Io(e)?"timeout":dt(e)?"auth_permanent":Lo(e)?"auth":null)}var jo={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"},Go=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function K(e,t){let r=ft(e,t)??(t?yt(t):null);return r?jo[r]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Ae(e){return Go.has(e)}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 Ho=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"]),ee=class{constructor(t=20,r=Tt){this.preserveRecentCount=t;this.estimateTokens=r}preserveRecentCount;estimateTokens;compress(t,r){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=t.length-this.preserveRecentCount,n=0,l=0;return{messages:t.map((a,m)=>{if(m>=o||a.role!=="tool"||typeof a.content!="string"||!a.name||!Ho.has(a.name)||a.content.length<=200)return a;let T=this.estimateTokens(a);return l+=T,n++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:n,strategy:"micro-compact",metrics:n>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function ve(e,t,r=Tt){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,n=0,l=[];for(let a of e){let m=a.tool_call_id??"";if(m&&t.has(m)){o+=r(a),n++,t.delete(m);continue}l.push(a)}let d=n>0?{role:"system",content:`[${n} messages removed by snip]`}:void 0;return{messages:l,tokensFreed:o,removedCount:n,boundaryMessage:d}}function Ee(){return{stages:[]}}function Ie(e,t,r){let o=r?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let l=ht(e,t),d=qo(l,t,o);if(d.length===0)return{messages:l,stagedCount:0};for(let a of d)t.stages.push(a);return l=ht(e,t),{messages:l,stagedCount:d.length}}function we(e,t){let r=0;for(let o of t.stages)o.committed||(o.committed=!0,r++);return r===0?{messages:e,committed:0}:{messages:Ct(e,t),committed:r}}function ht(e,t){return t.stages.filter(o=>o.committed).length===0?e:Ct(e,t)}function Ct(e,t){let r=t.stages.filter(n=>n.committed).sort((n,l)=>l.range[0]-n.range[0]),o=[...e];for(let n of r){let[l,d]=n.range;if(l>=o.length)continue;let a=Math.min(d,o.length),m={role:"system",content:n.summary};o.splice(l,a-l,m)}return o}function qo(e,t,r){let o=Math.max(0,e.length-Math.floor(r/2)),n=[],l=new Set(t.stages.map(m=>`${m.range[0]}-${m.range[1]}`)),d=-1,a=0;for(let m=0;m<o;m++){let T=e[m];if(T.role==="tool"||T.role==="assistant"&&typeof T.content=="string"&&T.content==="")d<0&&(d=m),a++;else{if(a>=3){let k=`${d}-${d+a}`;l.has(k)||n.push({id:`collapse_${d}_${d+a}`,range:[d,d+a],summary:`[${a} tool results collapsed]`,committed:!1})}d=-1,a=0}}if(a>=3){let m=`${d}-${d+a}`;l.has(m)||n.push({id:`collapse_${d}_${d+a}`,range:[d,d+a],summary:`[${a} tool results collapsed]`,committed:!1})}return n}import{existsSync as Pe,readFileSync as Ut,writeFileSync as zo,readdirSync as $t,mkdirSync as Ko}from"node:fs";import{join as Oe,dirname as Wo}from"node:path";var kt=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Rt=3,bt=2,de=2,_t=128e3,xt=13e3,St=16384,Mt=65536,At=3,vt=65536,Le=500,Et=3;var It=3e4,wt=3,te=2;var Lt=20;var Pt=3,Ot=2,Nt=300*1e3,Dt=3,Ft=720*60*60*1e3;var Gn=300*1e3;var Hn=3600*1e3;var qn=50*1024,zn=500*1024,Kn=500*1024*1024,Wn=50*1024*1024;var Xn=60*1024;var jt=0;var Xo="skill-patterns.json";function Gt(e){return Oe(e,".qlogicagent",Xo)}function Yo(e){let t=Gt(e);try{return JSON.parse(Ut(t,"utf8"))}catch{return{version:1,patterns:{}}}}function Bt(e,t){let r=Gt(e);Ko(Wo(r),{recursive:!0}),zo(r,JSON.stringify(t,null,2),"utf8")}function Vo(e){let t=Date.now()-Ft;for(let[r,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[r]}function Ht(e,t){if(t.length===0)return!1;let r=pe(t),o=Yo(e);Vo(o);let n=new Date().toISOString(),l=o.patterns[r];if(l||(l={signature:r,count:0,firstSeen:n,lastSeen:n,promoted:!1},o.patterns[r]=l),l.promoted)return Bt(e,o),!1;l.count++,l.lastSeen=n;let d=l.count>=Dt;return d&&(l.promoted=!0),Bt(e,o),d}function pe(e){return[...e].sort().join("+")}function Jo(e,t){if(!Pe(t))return null;let r=pe(e);try{let o=$t(t,{withFileTypes:!0});for(let n of o){if(!n.isDirectory())continue;let l=Oe(t,n.name,"SKILL.md");try{let a=Ut(l,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let m=a[1].split(`
|
|
2
|
+
`).map(T=>T.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(pe(m)===r)return n.name}}catch{}}}catch{}return null}function Zo(e){if(!Pe(e))return 0;try{return $t(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&Pe(Oe(e,t.name,"SKILL.md"))).length}catch{return 0}}function Qo(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<Pt||e.distinctToolCount<Ot||Date.now()-jt<Nt||t?.projectSkillsDir&&(Zo(t.projectSkillsDir)>=Lt||t.tools.length>0&&Jo(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Ht(t.projectRoot,t.tools))}function en(e){return e.existingSkillName?e.feedback==="negative":!1}function me(e,t){return en(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Qo(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 qt(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 tn(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function on(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function nn(e){if(!e.eligibility?.length)return[...e.tools];let t=on(e.eligibility);return e.tools.filter(r=>{let o=qt(r);if(!o)return!1;let n=t.get(o);return!n||tn(n.status)})}function rn(e){let t=[],r=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&r.requireAutoWhenThinking){let n=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;n&&n!=="auto"&&n!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&r.allowRequiredToolChoice===!1){let n=r.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${n}.`),o=n}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&r.allowNamedToolChoice===!1){let n=r.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${n}.`),o=n}return{normalizedToolChoice:o,warnings:t}}function Ne(e){let t=rn({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),r=t.normalizedToolChoice,o=[...t.warnings],n=nn({tools:e.tools,eligibility:e.eligibility});if(!r||r==="auto")return{tools:n,normalizedToolChoice:r,warnings:o};if(r==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(r==="required"){if(n.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:n,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof r=="object"&&!Array.isArray(r)&&r.type==="function"){let l=r.function??void 0,d=typeof l?.name=="string"?l.name.trim():"";if(!d)throw new Error("tool_choice.function.name is required");let a=n.filter(m=>qt(m)===d);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${d}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:d}},extraSystemPrompt:`You must call the ${d} tool before responding.`,warnings:o}}return{tools:n,normalizedToolChoice:r,warnings:o}}var sn=["stop","aborted","timeout","cancelled","interrupted","error"],an=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function zt(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function ln(e,t){return{...e,content:[...zt(e.content),...zt(t.content)]}}function cn(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 un(e){return new Set((e??sn).map(t=>t.trim().toLowerCase()))}function dn(e,t){return e?un(t).has(e.trim().toLowerCase()):!1}function De(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let m=a.tool_calls.filter(T=>cn(T));return{...a,...m.length>0?{tool_calls:m}:{tool_calls:void 0}}}return{...a}}),r=new Set;for(let a of t)if(!(a.role!=="assistant"||!Array.isArray(a.tool_calls)))for(let m of a.tool_calls)typeof m.id=="string"&&m.id&&r.add(m.id);let o=t.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&r.has(a.tool_call_id))),n=new Set;for(let a of o)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&n.add(a.tool_call_id);let l=[];for(let a of o){if(a.role==="assistant"&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0){let m=a.tool_calls.filter(T=>typeof T.id=="string"&&n.has(T.id));if(m.length===0){let{tool_calls:T,...h}=a;h.content!=null&&h.content!==""&&l.push(h);continue}if(m.length<a.tool_calls.length){l.push({...a,tool_calls:m});continue}}l.push(a)}let d=[];for(let a of l){let m=d.length>0?d[d.length-1]:void 0;if(a.role==="user"&&m?.role==="user"){d[d.length-1]=ln(m,a);continue}d.push(a)}return d}function Fe(e,t){return dn(t?.stopReason,t?.forcedStopReasons)?e.map(r=>{if(r.role!=="assistant")return{...r};let o={...r};for(let n of an)delete o[n];return o}):[...e]}function Be(e,t){let r=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let l of e)l.role==="tool"&&typeof l.tool_call_id=="string"&&l.tool_call_id&&o.add(l.tool_call_id);let n=[];for(let l of e)if(n.push({...l}),!(l.role!=="assistant"||!Array.isArray(l.tool_calls)||l.tool_calls.length===0))for(let d of l.tool_calls)typeof d.id!="string"||!d.id||o.has(d.id)||(o.add(d.id),n.push({role:"tool",tool_call_id:d.id,content:r}));return n}function Ue(e,t){let r=De(e),o=Fe(r,t);return Be(o,t)}function pn(e){let t=new Set,r=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let n of o.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&r.add(o.tool_call_id)}return[...t].filter(o=>!r.has(o))}function mn(e){let t=new Set;for(let r of e)r.role==="tool"&&typeof r.tool_call_id=="string"&&r.tool_call_id&&t.add(r.tool_call_id);return[...t]}function gn(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function $e(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=[],r=De(e.replayMessages);r.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=Fe(r,e.options);o.some((l,d)=>l!==r[d])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let n=Be(o,e.options);return n.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:gn({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:n,pendingToolCallIds:pn(n),completedToolCallIds:mn(n)}),recoveryActions:t}}var fn=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function je(e){return e?fn.has(e):!0}function Ge(e){return e===429||e===529}function ye(e,t=500,r=32e3){let o=Math.min(t*Math.pow(2,e-1),r);return o+Math.floor(Math.random()*o*.25)}var ir={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Te(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var oe=class extends Error{constructor(r,o){super(`Model fallback triggered: ${r} -> ${o}`);this.originalModel=r;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function He(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function qe(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let r=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=r>0?e.promptTokens/r*100:100;return e.promptTokens>=r?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:r-e.promptTokens}:{level:"ok"}}function ze(e,t,r){let o=e.message?.toLowerCase()??"",n=e.status??0;return n===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&r.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:n>=500&&n<600?{action:"retry",reason:`server_error_${n}`}:n===429?{action:"retry",reason:"rate_limited"}:n===401||n===403?{action:"abort",reason:"auth_error"}:n===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function Ke(e,t,r){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,r);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function We(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Tn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Xe(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function W(e,t=Tn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function Ye(e,t){let r=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(r.id=t.id),t.name&&(r.name=t.name),r.arguments+=t.arguments??"",e.set(t.index,r)}function Kt(e,t){let r=typeof t.message?.content=="string"?t.message.content:"",o=r?r.slice(0,2e3):void 0,n=t.details,l=typeof n?.stdout=="string"?n.stdout.slice(0,8e3):void 0,d=typeof n?.stderr=="string"?n.stderr.slice(0,4e3):void 0,a=typeof n?.exitCode=="number"?n.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:o,durationMs:t.durationMs,exitCode:a,stdout:l,stderr:d,details:n}}var hn=new Set(["write","edit","patch","apply_patch"]);function Wt(e){let{turnId:t,result:r,toolCalls:o}=e;if(!r.ok)return[];let n=o.find(a=>a.id===r.callId);if(!n)return[];let l=[],d=Cn(n.function.arguments);if(!d)return l;if(r.toolName==="plan_mode"&&d.action==="exit"&&typeof d.plan=="string"&&d.plan.length>0&&l.push({type:"plan_update",turnId:t,slug:"approved-plan",content:d.plan}),hn.has(r.toolName)){let a=kn(d);a&&l.push({type:"artifact",turnId:t,artifactId:`artifact-${r.callId}`,artifactType:Rn(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:bn(a)})}return l}function Cn(e){try{return JSON.parse(e)}catch{return null}}function kn(e){return typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:void 0}function Rn(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 bn(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]}var xn=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,Sn=new Set(["search","web_search","grep","glob","find","list","read","exec"]);function Xt(e){if(!Sn.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&xn.test(t)}function Ve(e,t){for(let r=e.length-1;r>=0;r--){let o=e[r];if(!o||o.role!=="tool")continue;let n=typeof o.content=="string"?o.content:"";if(n.startsWith("Error: "))return n.slice(7).trim()}}function Yt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.round(e),100):kt}function Vt(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function X(e,t){let r=[];for(let o=e.length-1;o>=0;o--){let n=e[o];if(n.role==="tool"&&typeof n.content=="string")r.unshift(n.content.slice(0,500));else if(n.role==="assistant"){if(typeof n.content=="string"&&n.content.trim())return t.info("synthesizeFallbackContent: found assistant text, using it"),n.content;break}else break}return r.length>0?(t.info(`synthesizeFallbackContent: synthesized from ${r.length} tool result(s)`),r.join(`
|
|
3
3
|
|
|
4
|
-
`)):""}function Jt(e){try{let t=JSON.parse(e),o=[t.description,t.command,t.query,t.url,t.path,t.file_path,t.filePath,t.pattern,t.model].find(l=>typeof l=="string"&&l.trim().length>0);if(typeof o=="string")return o.trim().slice(0,240);let n=Object.keys(t);return n.length>0?n.slice(0,5).join(" / "):void 0}catch{return}}function Ve(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 Zt(e){return e==="length"||e==="max_tokens"}function Je(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 Qt(e){let t=e.headers;if(!t)return null;let r=t["retry-after"]??t["Retry-After"];if(!r)return null;let o=parseInt(r,10);return!isNaN(o)&&o>0?o*1e3:null}function eo(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 r=parseInt(t[1],10),o=parseInt(t[3],10);if(isNaN(r)||isNaN(o))return null;let n=o-r-1e3;return n>=3e3?n:null}async function*to(e,t,r,o,n,l,d,a){let m=[],T;a.debug(`single LLM round, messages: ${r.length}`);for await(let h of d.stream({model:t,messages:r,temperature:n},o,l))switch(h.type){case"delta":m.push(h.text),yield{type:"delta",turnId:e,text:h.text};break;case"usage":T={inputTokens:h.promptTokens,outputTokens:h.completionTokens,reasoningTokens:h.reasoningTokens,cacheRead:h.cacheReadTokens,cacheWrite:h.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:e,content:m.join(""),usage:T??{inputTokens:0,outputTokens:0},model:t}}async function*oo(e,t,r,o){let{turnId:n,sessionId:l,messages:d,tools:a,model:m,apiKey:T,temperature:h=0,hooks:k,signal:j}=e,M={sessionId:l,turnId:n},R=e.maxTurns??0,w=e.querySource,b=e.runtimePorts.resolveToolEligibility(a,e.toolEligibilityContext),N=b.eligibleTools;for(let f of b.blockedTools)yield{type:"tool_blocked",turnId:n,callId:"",name:f.toolName,reason:"blocked-by-policy"};if(!N.length){yield*to(n,m,d,T,h,j,t,o);return}let $=Yt(e.maxRounds),D={contextWindowTokens:e.contextWindowTokens??_t,responseBufferTokens:xt,maxOutputTokens:e.maxOutputTokens??St,abortSignal:j,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},_=new Set,C=0,A=N,ne,re=!1,Ze=0,s={messages:[...d],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Ge(D),reactiveCompactState:We(),toolLoopState:Te({maxRounds:$,replayMessages:[...d]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:ve(),currentModel:m,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,toolFailureCounts:new Map,fileReadCounts:new Map},Qe=Math.max(R*5,200),et=0;for(;;){if(et++,et>Qe){o.info(`hard iteration cap reached (${Qe}), forcing completion`);let i=s.finalText||X(s.messages,o);yield{type:"end",turnId:n,content:i,usage:s.totalUsage,model:s.currentModel};return}let{messages:f,maxOutputTokensRecoveryCount:Y,hasAttemptedReactiveCompact:Nn,maxOutputTokensOverride:tt,turnCount:V,guardState:x,reactiveCompactState:U,collapseStore:ke}=s,{toolLoopState:L}=s;if(ne){try{let i=await ne;i&&(yield{type:"tool_use_summary",turnId:n,summary:i})}catch{}ne=void 0}if(e.refreshTools&&V>1){let i=e.refreshTools();i!==A&&(A=i,o.debug(`tools refreshed: ${i.length} tools`))}if(Ke(x,D)){o.info(`turn aborted by guard at turn ${V}`),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED",usage:s.totalUsage};return}let G=He(x,D);if(G.level==="blocking"){G.reason==="prompt_too_long"&&W(U)&&(U.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${G.reason}), reactive compact needed`),yield{type:"recovery",turnId:n,action:"reactive_compact",detail:"token budget pre-check"}),o.info(`token budget blocking (${G.reason}), ending tool loop`);break}G.level==="warning"&&o.info(`token budget warning: ${G.usagePercent}% used, ${G.remainingTokens} remaining`);let S;{let i=await e.runtimePorts.enforceToolResultBudget(f,s.contentReplacementState,l);S=i.messages,i.newlyReplacedCount>0&&(o.info(`tool-result-budget: persisted ${i.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:n,action:"tool_result_budget",detail:`${i.newlyReplacedCount} persisted`})}{let i=Ae(S,s.snipRemovedIds);S=i.messages,i.removedCount>0&&(o.info(`snip: removed ${i.removedCount} messages, freed ~${i.tokensFreed} tokens`),yield{type:"recovery",turnId:n,action:"snip",detail:`${i.removedCount} messages`})}{let c=new ee().compress(S,0);c.droppedCount>0&&(S=c.messages,o.info(`microcompact: cleared ${c.droppedCount} old tool results`))}if(S=Ee(S,ke).messages,x.promptTokens>0){let i=D.contextWindowTokens*.75,c=e.runtimePorts.getActiveContextCompressionEngine(),u;c?u=await c.compressAsync(S,i,{model:s.currentModel,sessionId:l}):u=e.runtimePorts.compressMessages(S,{budget:i,model:s.currentModel}),u.droppedCount>0&&(S=u.messages,o.info(`autocompact: ${u.strategy}, dropped ${u.droppedCount}`),yield{type:"recovery",turnId:n,action:"autocompact",detail:`${u.strategy}: ${u.droppedCount} dropped`},s.hasAttemptedReactiveCompact=!1,k?.invoke("context.after_compact",{...M,removedCount:u.droppedCount}).catch(()=>{}))}S=Vt(S);let lo=e.toolChoice==="required"&&re?"auto":e.toolChoice??"auto",se=Oe({tools:A,toolChoice:lo}),J=Te({maxRounds:$,replayMessages:S,lastStopReason:L.lastStopReason,options:{stopReason:L.lastStopReason}}),ot=se.extraSystemPrompt?[{role:"system",content:se.extraSystemPrompt},...J.state.replayMessages]:J.state.replayMessages;L=J.state,J.recoveryActions.length>0&&o.debug(`tool loop recovery: ${J.recoveryActions.map(i=>i.detail??i.kind).join("; ")}`),o.debug(`turn ${V}, messages: ${ot.length}`),k?.invoke("turn.before_inference",{...M,model:s.currentModel}).catch(()=>{});let ie=!1,nt=[],rt=new Map,st="stop",P,y=null,ae=!1,Z=[],I=[];try{for await(let i of t.stream({model:s.currentModel,messages:ot,tools:se.tools,toolChoice:se.normalizedToolChoice??"auto",temperature:h,maxTokens:(tt??x.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:s.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,j))switch(i.type){case"delta":nt.push(i.text),!ie&&!(e.toolChoice==="required"&&!re)&&(yield{type:"delta",turnId:n,text:i.text});break;case"tool_call_delta":ie=!0,Xe(rt,i);break;case"reasoning_delta":Z.push(i.text);break;case"reasoning_block_complete":i.signature&&I.push({thinking:Z.join(""),signature:i.signature}),Z.length=0;break;case"usage":P={inputTokens:i.promptTokens,outputTokens:i.completionTokens,reasoningTokens:i.reasoningTokens,cacheRead:i.cacheReadTokens,cacheWrite:i.cacheCreationTokens};break;case"response_id":s.lastResponseId=i.id;break;case"annotations":yield{type:"annotations",turnId:n,annotations:i.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:n,message:`${i.toolType}: ${i.event}`};break;case"done":st=i.finishReason;break}if(ie||k?.invoke("turn.after_inference",{...M,model:s.currentModel}).catch(()=>{}),e.postSamplingHooks&&e.postSamplingHooks.length>0){let i=s.currentModel;for(let c of e.postSamplingHooks)try{c({messages:[...S],model:i,sessionId:l})}catch{}}}catch(i){if(i instanceof oe&&e.fallbackModel){o.info(`model fallback triggered: ${i.originalModel} -> ${i.fallbackModel}`),yield{type:"recovery",turnId:n,action:"model_fallback",detail:`${i.originalModel} -> ${i.fallbackModel}`},s={...s,currentModel:i.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let c=i instanceof Error?i.message:String(i),u=typeof i?.status=="number"?i.status:void 0;if(!u&&c&&(c.includes("ECONNRESET")||c.includes("EPIPE"))){let g=(s.consecutiveApiRetries??0)+1;if(g>te){o.info(`stale connection retry limit reached (${te}), aborting`),yield{type:"error",turnId:n,error:c,code:"RETRIES_EXHAUSTED",usage:s.totalUsage};return}o.info(`stale connection (${c.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:n,action:"stale_connection_retry",detail:c.slice(0,80)},s={...s,consecutiveApiRetries:g,transition:void 0};continue}let p=eo({status:u,message:c});if(p!==null){o.info(`max_tokens overflow: adjusting to ${p}`),x.currentMaxOutputTokens=p,s={...s,maxOutputTokensOverride:p,transition:void 0};continue}if(je(u)){s.consecutive529Errors++;let g=2,v=e.fallbackModel&&s.currentModel!==e.fallbackModel;if(s.consecutive529Errors>g&&!v&&!Ce()){o.info(`transient ${u} \u8133 ${s.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:n,error:`API unavailable after ${s.consecutive529Errors} consecutive ${u} errors`,code:"API_ERROR",usage:s.totalUsage};return}if(s.consecutive529Errors>=wt&&e.fallbackModel&&s.currentModel!==e.fallbackModel){o.info(`529 \u8133 ${s.consecutive529Errors}: triggering fallback to ${e.fallbackModel}`),yield{type:"recovery",turnId:n,action:"model_fallback",detail:`529 \u8133 ${s.consecutive529Errors}`},s={...s,currentModel:e.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(Ce()){let E=he(s.consecutive529Errors);o.info(`persistent retry: waiting ${E}ms (attempt ${s.consecutive529Errors})`);let O=E;for(;O>0;){if(j?.aborted){yield{type:"error",turnId:n,error:"Aborted during retry wait",code:"ABORTED",usage:s.totalUsage};return}yield{type:"heartbeat",turnId:n,message:`Retrying in ${Math.ceil(O/1e3)}s (${u})`};let B=Math.min(O,It);await new Promise(_e=>setTimeout(_e,B)),O-=B}s={...s,transition:void 0};continue}if($e(w)){let O=Qt({status:u,message:c})??he(s.consecutive529Errors);o.info(`transient ${u}: retry in ${O}ms`),yield{type:"recovery",turnId:n,action:"retry",detail:`${u} retry in ${O}ms`},await new Promise(B=>setTimeout(B,O)),s={...s,transition:void 0};continue}o.info(`background source ${w}: not retrying ${u}`)}y={status:u,message:c}}if(y&&k?.invoke("turn.after_inference",{...M,model:s.currentModel,response:{error:y.message}}).catch(()=>{}),y)if(Ve(y))ae=!0,o.info(`withheld prompt_too_long error (status=${y.status})`);else if(Je(y))ae=!0,o.info(`withheld media_size error (status=${y.status})`);else{let i=qe({status:y.status??500,message:y.message},x,D);if(i.action==="reactive_compact"&&W(U)&&(U.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:n,action:"reactive_compact",detail:`API ${y.status??500}: ${y.message}`}),i.action==="retry"){let u=(s.consecutiveApiRetries??0)+1;if(u>te){o.info(`API retry limit reached (${te}), aborting`);let p=K(y.status,y.message);yield{type:"error",turnId:n,error:y.message,code:p,usage:s.totalUsage};return}yield{type:"recovery",turnId:n,action:"retry",detail:i.reason},s={...s,consecutiveApiRetries:u,transition:void 0};continue}let c=K(y.status,y.message);k?.invoke("stop.failure",{sessionId:l,reason:c,error:y.message}).catch(()=>{}),yield{type:"error",turnId:n,error:y.message,code:c,usage:s.totalUsage};return}P&&(s.totalUsage.inputTokens+=P.inputTokens,s.totalUsage.outputTokens+=P.outputTokens,P.reasoningTokens&&(s.totalUsage.reasoningTokens=(s.totalUsage.reasoningTokens??0)+P.reasoningTokens),P.cacheRead&&(s.totalUsage.cacheRead=(s.totalUsage.cacheRead??0)+P.cacheRead),P.cacheWrite&&(s.totalUsage.cacheWrite=(s.totalUsage.cacheWrite??0)+P.cacheWrite)),P?.inputTokens&&(x.promptTokens=P.inputTokens);let it=nt.join("");it&&(s.finalText=it);let F=[...rt.values()].map(i=>({id:i.id||`tc_${n}_${V}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:i.name,arguments:i.arguments}}));if(F.length===0&&!ie){if(e.toolChoice==="required"&&!re&&A.length>0&&Ze<2){Ze++;let u=A.map(p=>p.function.name).filter(Boolean).slice(0,8).join(", ");s={...s,messages:[...f,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${u}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(ae&&y&&Ve(y)){if(s.transition?.reason!=="collapse_drain_retry"){let u=Ie(S,ke);if(u.committed>0){o.info(`collapse drain: committed ${u.committed} stages`),yield{type:"recovery",turnId:n,action:"collapse_drain",detail:`${u.committed} stages committed`},s={...s,messages:u.messages,transition:{reason:"collapse_drain_retry",committed:u.committed}};continue}}if(W(U)){U.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:n,action:"reactive_compact",detail:"withheld prompt_too_long"},s={...s,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),k?.invoke("stop.failure",{sessionId:l,reason:"prompt_too_long",error:y.message}).catch(()=>{}),yield{type:"error",turnId:n,error:y.message,code:"PROMPT_TOO_LONG",usage:s.totalUsage};return}if(ae&&y&&Je(y)){if(W(U)){U.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:n,action:"reactive_compact",detail:"media error strip-retry"},s={...s,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),k?.invoke("stop.failure",{sessionId:l,reason:"media_error",error:y.message}).catch(()=>{}),yield{type:"error",turnId:n,error:y.message,code:"IMAGE_ERROR",usage:s.totalUsage};return}if(Zt(st)){x.consecutiveTruncations+=1;let u=e.modelMaxOutputTokens??Mt,p=ze(x,D,u);if(p.shouldEscalate&&tt===void 0){x.currentMaxOutputTokens=p.newMax,o.info(`max_output_tokens escalate: ${p.newMax} tokens`),yield{type:"recovery",turnId:n,action:"output_escalation",detail:`${p.newMax} tokens`},s={...s,maxOutputTokensOverride:vt,transition:{reason:"max_output_tokens_escalate"}};continue}if(Y<At){let g={role:"user",content:"Output token limit hit. Resume directly - 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."};o.info(`max_output_tokens recovery #${Y+1}`),yield{type:"recovery",turnId:n,action:"max_output_tokens_recovery",detail:`attempt ${Y+1}`},s={...s,messages:[...S,g],maxOutputTokensRecoveryCount:Y+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:Y+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else x.consecutiveTruncations=0;if(L=ye(L,{replayMessages:f,lastStopReason:"completed"}),k){let u=await k.invoke("stop",{sessionId:l,reason:"completed"});if(u.action==="prevent"){o.info(`stop hook prevented continuation: ${u.reason??"no reason"}`),yield{type:"end",turnId:n,content:s.finalText,usage:s.totalUsage,model:s.currentModel};return}if(u.action==="abort"){let p=u.reason??"Stop hook requested continuation";o.info(`stop hook blocking: ${p}`);let g={role:"user",content:p},v={role:"assistant",content:s.finalText,...I.length>0&&{thinkingBlocks:[...I]}};s={...s,messages:[...f,v,g],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(e.tokenBudget&&e.tokenBudget>0&&s.budgetContinuationCount<5){let u=s.totalUsage.inputTokens+s.totalUsage.outputTokens+(s.totalUsage.reasoningTokens??0),p=u/e.tokenBudget*100,g=u-s.lastBudgetGlobalTokens,v=s.budgetContinuationCount>=Et&&g<we&&s.lastBudgetDeltaTokens<we;if(v&&o.info(`token budget early stop: diminishing returns at ${Math.round(p)}% (delta=${g})`),!v&&p<90){let E=s.budgetContinuationCount+1,O={role:"user",content:e.runtimePorts.getBudgetContinuationMessage(p,u,e.tokenBudget)};o.info(`token budget continuation #${E}: ${Math.round(p)}% used`),yield{type:"recovery",turnId:n,action:"budget_continuation",detail:`${Math.round(p)}% used (#${E})`};let B={role:"assistant",content:s.finalText,...I.length>0&&{thinkingBlocks:[...I]}};s={...s,messages:[...f,B,O],budgetContinuationCount:E,lastBudgetDeltaTokens:g,lastBudgetGlobalTokens:u,transition:{reason:"token_budget_continuation"}};continue}}if(!s.stopHookActive){let u=d.find(E=>E.role==="user"),p=typeof u?.content=="string"?u.content:"",g=/create\s+(?:a\s+)?file|write\s+(?:a\s+)?file|make\s+(?:a\s+)?file|fix|implement|modify|update|repair|generate\s+(?:a\s+)?file|new\s+file/i.test(p),v=_.has("write")||_.has("edit");if(g&&!v){if(o.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),C>0){let B=[...f].reverse().find(_e=>_e.role==="tool");B&&typeof B.content=="string"&&(B.content+=`
|
|
4
|
+
`)):""}function Jt(e){try{let t=JSON.parse(e),o=[t.description,t.command,t.query,t.url,t.path,t.file_path,t.filePath,t.pattern,t.model].find(l=>typeof l=="string"&&l.trim().length>0);if(typeof o=="string")return o.trim().slice(0,240);let n=Object.keys(t);return n.length>0?n.slice(0,5).join(" / "):void 0}catch{return}}function Je(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 Zt(e){return e==="length"||e==="max_tokens"}function Ze(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 Qt(e){let t=e.headers;if(!t)return null;let r=t["retry-after"]??t["Retry-After"];if(!r)return null;let o=parseInt(r,10);return!isNaN(o)&&o>0?o*1e3:null}function eo(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 r=parseInt(t[1],10),o=parseInt(t[3],10);if(isNaN(r)||isNaN(o))return null;let n=o-r-1e3;return n>=3e3?n:null}async function*to(e,t,r,o,n,l,d,a){let m=[],T;a.debug(`single LLM round, messages: ${r.length}`);for await(let h of d.stream({model:t,messages:r,temperature:n},o,l))switch(h.type){case"delta":m.push(h.text),yield{type:"delta",turnId:e,text:h.text};break;case"usage":T={inputTokens:h.promptTokens,outputTokens:h.completionTokens,reasoningTokens:h.reasoningTokens,cacheRead:h.cacheReadTokens,cacheWrite:h.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:e,content:m.join(""),usage:T??{inputTokens:0,outputTokens:0},model:t}}async function*oo(e,t,r,o){let{turnId:n,sessionId:l,messages:d,tools:a,model:m,apiKey:T,temperature:h=0,hooks:k,signal:j}=e,M={sessionId:l,turnId:n},R=e.maxTurns??0,w=e.querySource,b=e.runtimePorts.resolveToolEligibility(a,e.toolEligibilityContext),N=b.eligibleTools;for(let f of b.blockedTools)yield{type:"tool_blocked",turnId:n,callId:"",name:f.toolName,reason:"blocked-by-policy"};if(!N.length){yield*to(n,m,d,T,h,j,t,o);return}let $=Yt(e.maxRounds),D={contextWindowTokens:e.contextWindowTokens??_t,responseBufferTokens:xt,maxOutputTokens:e.maxOutputTokens??St,abortSignal:j,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},_=new Set,C=0,A=N,ne,he=!1,Qe=0,s={messages:[...d],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:He(D),reactiveCompactState:Xe(),toolLoopState:fe({maxRounds:$,replayMessages:[...d]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:Ee(),currentModel:m,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,toolFailureCounts:new Map,fileReadCounts:new Map},et=Math.max(R*5,200),tt=0;for(;;){if(tt++,tt>et){o.info(`hard iteration cap reached (${et}), forcing completion`);let i=s.finalText||X(s.messages,o);yield{type:"end",turnId:n,content:i,usage:s.totalUsage,model:s.currentModel};return}let{messages:f,maxOutputTokensRecoveryCount:Y,hasAttemptedReactiveCompact:Nn,maxOutputTokensOverride:ot,turnCount:V,guardState:x,reactiveCompactState:U,collapseStore:Ce}=s,{toolLoopState:L}=s;if(ne){try{let i=await ne;i&&(yield{type:"tool_use_summary",turnId:n,summary:i})}catch{}ne=void 0}if(e.refreshTools&&V>1){let i=e.refreshTools();i!==A&&(A=i,o.debug(`tools refreshed: ${i.length} tools`))}if(We(x,D)){o.info(`turn aborted by guard at turn ${V}`),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED",usage:s.totalUsage};return}let G=qe(x,D);if(G.level==="blocking"){G.reason==="prompt_too_long"&&W(U)&&(U.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${G.reason}), reactive compact needed`),yield{type:"recovery",turnId:n,action:"reactive_compact",detail:"token budget pre-check"}),o.info(`token budget blocking (${G.reason}), ending tool loop`);break}G.level==="warning"&&o.info(`token budget warning: ${G.usagePercent}% used, ${G.remainingTokens} remaining`);let S;{let i=await e.runtimePorts.enforceToolResultBudget(f,s.contentReplacementState,l);S=i.messages,i.newlyReplacedCount>0&&(o.info(`tool-result-budget: persisted ${i.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:n,action:"tool_result_budget",detail:`${i.newlyReplacedCount} persisted`})}{let i=ve(S,s.snipRemovedIds);S=i.messages,i.removedCount>0&&(o.info(`snip: removed ${i.removedCount} messages, freed ~${i.tokensFreed} tokens`),yield{type:"recovery",turnId:n,action:"snip",detail:`${i.removedCount} messages`})}{let c=new ee().compress(S,0);c.droppedCount>0&&(S=c.messages,o.info(`microcompact: cleared ${c.droppedCount} old tool results`))}if(S=Ie(S,Ce).messages,x.promptTokens>0){let i=D.contextWindowTokens*.75,c=e.runtimePorts.getActiveContextCompressionEngine(),u;c?u=await c.compressAsync(S,i,{model:s.currentModel,sessionId:l}):u=e.runtimePorts.compressMessages(S,{budget:i,model:s.currentModel}),u.droppedCount>0&&(S=u.messages,o.info(`autocompact: ${u.strategy}, dropped ${u.droppedCount}`),yield{type:"recovery",turnId:n,action:"autocompact",detail:`${u.strategy}: ${u.droppedCount} dropped`},s.hasAttemptedReactiveCompact=!1,k?.invoke("context.after_compact",{...M,removedCount:u.droppedCount}).catch(()=>{}))}S=Vt(S);let lo=e.toolChoice==="required"&&he?"auto":e.toolChoice??"auto",re=Ne({tools:A,toolChoice:lo}),J=fe({maxRounds:$,replayMessages:S,lastStopReason:L.lastStopReason,options:{stopReason:L.lastStopReason}}),nt=re.extraSystemPrompt?[{role:"system",content:re.extraSystemPrompt},...J.state.replayMessages]:J.state.replayMessages;L=J.state,J.recoveryActions.length>0&&o.debug(`tool loop recovery: ${J.recoveryActions.map(i=>i.detail??i.kind).join("; ")}`),o.debug(`turn ${V}, messages: ${nt.length}`),k?.invoke("turn.before_inference",{...M,model:s.currentModel}).catch(()=>{});let ke=!1,Re=[],rt=new Map,st="stop",P,y=null,se=!1,Z=[],I=[];try{for await(let i of t.stream({model:s.currentModel,messages:nt,tools:re.tools,toolChoice:re.normalizedToolChoice??"auto",temperature:h,maxTokens:(ot??x.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:s.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,j))switch(i.type){case"delta":Re.push(i.text);break;case"tool_call_delta":ke=!0,Ye(rt,i);break;case"reasoning_delta":Z.push(i.text);break;case"reasoning_block_complete":i.signature&&I.push({thinking:Z.join(""),signature:i.signature}),Z.length=0;break;case"usage":P={inputTokens:i.promptTokens,outputTokens:i.completionTokens,reasoningTokens:i.reasoningTokens,cacheRead:i.cacheReadTokens,cacheWrite:i.cacheCreationTokens};break;case"response_id":s.lastResponseId=i.id;break;case"annotations":yield{type:"annotations",turnId:n,annotations:i.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:n,message:`${i.toolType}: ${i.event}`};break;case"done":st=i.finishReason;break}if(ke||k?.invoke("turn.after_inference",{...M,model:s.currentModel}).catch(()=>{}),e.postSamplingHooks&&e.postSamplingHooks.length>0){let i=s.currentModel;for(let c of e.postSamplingHooks)try{c({messages:[...S],model:i,sessionId:l})}catch{}}}catch(i){if(i instanceof oe&&e.fallbackModel){o.info(`model fallback triggered: ${i.originalModel} -> ${i.fallbackModel}`),yield{type:"recovery",turnId:n,action:"model_fallback",detail:`${i.originalModel} -> ${i.fallbackModel}`},s={...s,currentModel:i.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let c=i instanceof Error?i.message:String(i),u=typeof i?.status=="number"?i.status:void 0;if(!u&&c&&(c.includes("ECONNRESET")||c.includes("EPIPE"))){let g=(s.consecutiveApiRetries??0)+1;if(g>te){o.info(`stale connection retry limit reached (${te}), aborting`),yield{type:"error",turnId:n,error:c,code:"RETRIES_EXHAUSTED",usage:s.totalUsage};return}o.info(`stale connection (${c.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:n,action:"stale_connection_retry",detail:c.slice(0,80)},s={...s,consecutiveApiRetries:g,transition:void 0};continue}let p=eo({status:u,message:c});if(p!==null){o.info(`max_tokens overflow: adjusting to ${p}`),x.currentMaxOutputTokens=p,s={...s,maxOutputTokensOverride:p,transition:void 0};continue}if(Ge(u)){s.consecutive529Errors++;let g=2,v=e.fallbackModel&&s.currentModel!==e.fallbackModel;if(s.consecutive529Errors>g&&!v&&!Te()){o.info(`transient ${u} \u8133 ${s.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:n,error:`API unavailable after ${s.consecutive529Errors} consecutive ${u} errors`,code:"API_ERROR",usage:s.totalUsage};return}if(s.consecutive529Errors>=wt&&e.fallbackModel&&s.currentModel!==e.fallbackModel){o.info(`529 \u8133 ${s.consecutive529Errors}: triggering fallback to ${e.fallbackModel}`),yield{type:"recovery",turnId:n,action:"model_fallback",detail:`529 \u8133 ${s.consecutive529Errors}`},s={...s,currentModel:e.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(Te()){let E=ye(s.consecutive529Errors);o.info(`persistent retry: waiting ${E}ms (attempt ${s.consecutive529Errors})`);let O=E;for(;O>0;){if(j?.aborted){yield{type:"error",turnId:n,error:"Aborted during retry wait",code:"ABORTED",usage:s.totalUsage};return}yield{type:"heartbeat",turnId:n,message:`Retrying in ${Math.ceil(O/1e3)}s (${u})`};let B=Math.min(O,It);await new Promise(xe=>setTimeout(xe,B)),O-=B}s={...s,transition:void 0};continue}if(je(w)){let O=Qt({status:u,message:c})??ye(s.consecutive529Errors);o.info(`transient ${u}: retry in ${O}ms`),yield{type:"recovery",turnId:n,action:"retry",detail:`${u} retry in ${O}ms`},await new Promise(B=>setTimeout(B,O)),s={...s,transition:void 0};continue}o.info(`background source ${w}: not retrying ${u}`)}y={status:u,message:c}}if(y&&k?.invoke("turn.after_inference",{...M,model:s.currentModel,response:{error:y.message}}).catch(()=>{}),y)if(Je(y))se=!0,o.info(`withheld prompt_too_long error (status=${y.status})`);else if(Ze(y))se=!0,o.info(`withheld media_size error (status=${y.status})`);else{let i=ze({status:y.status??500,message:y.message},x,D);if(i.action==="reactive_compact"&&W(U)&&(U.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:n,action:"reactive_compact",detail:`API ${y.status??500}: ${y.message}`}),i.action==="retry"){let u=(s.consecutiveApiRetries??0)+1;if(u>te){o.info(`API retry limit reached (${te}), aborting`);let p=K(y.status,y.message);yield{type:"error",turnId:n,error:y.message,code:p,usage:s.totalUsage};return}yield{type:"recovery",turnId:n,action:"retry",detail:i.reason},s={...s,consecutiveApiRetries:u,transition:void 0};continue}let c=K(y.status,y.message);k?.invoke("stop.failure",{sessionId:l,reason:c,error:y.message}).catch(()=>{}),yield{type:"error",turnId:n,error:y.message,code:c,usage:s.totalUsage};return}P&&(s.totalUsage.inputTokens+=P.inputTokens,s.totalUsage.outputTokens+=P.outputTokens,P.reasoningTokens&&(s.totalUsage.reasoningTokens=(s.totalUsage.reasoningTokens??0)+P.reasoningTokens),P.cacheRead&&(s.totalUsage.cacheRead=(s.totalUsage.cacheRead??0)+P.cacheRead),P.cacheWrite&&(s.totalUsage.cacheWrite=(s.totalUsage.cacheWrite??0)+P.cacheWrite)),P?.inputTokens&&(x.promptTokens=P.inputTokens);let it=Re.join(""),F=[...rt.values()].map(i=>({id:i.id||`tc_${n}_${V}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:i.name,arguments:i.arguments}}));if(F.length===0&&!ke){if(it&&(s.finalText=it),e.toolChoice==="required"&&!he&&A.length>0&&Qe<2){Qe++;let u=A.map(p=>p.function.name).filter(Boolean).slice(0,8).join(", ");s={...s,messages:[...f,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${u}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(se&&y&&Je(y)){if(s.transition?.reason!=="collapse_drain_retry"){let u=we(S,Ce);if(u.committed>0){o.info(`collapse drain: committed ${u.committed} stages`),yield{type:"recovery",turnId:n,action:"collapse_drain",detail:`${u.committed} stages committed`},s={...s,messages:u.messages,transition:{reason:"collapse_drain_retry",committed:u.committed}};continue}}if(W(U)){U.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:n,action:"reactive_compact",detail:"withheld prompt_too_long"},s={...s,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),k?.invoke("stop.failure",{sessionId:l,reason:"prompt_too_long",error:y.message}).catch(()=>{}),yield{type:"error",turnId:n,error:y.message,code:"PROMPT_TOO_LONG",usage:s.totalUsage};return}if(se&&y&&Ze(y)){if(W(U)){U.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:n,action:"reactive_compact",detail:"media error strip-retry"},s={...s,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),k?.invoke("stop.failure",{sessionId:l,reason:"media_error",error:y.message}).catch(()=>{}),yield{type:"error",turnId:n,error:y.message,code:"IMAGE_ERROR",usage:s.totalUsage};return}if(Zt(st)){x.consecutiveTruncations+=1;let u=e.modelMaxOutputTokens??Mt,p=Ke(x,D,u);if(p.shouldEscalate&&ot===void 0){x.currentMaxOutputTokens=p.newMax,o.info(`max_output_tokens escalate: ${p.newMax} tokens`),yield{type:"recovery",turnId:n,action:"output_escalation",detail:`${p.newMax} tokens`},s={...s,maxOutputTokensOverride:vt,transition:{reason:"max_output_tokens_escalate"}};continue}if(Y<At){let g={role:"user",content:"Output token limit hit. Resume directly - 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."};o.info(`max_output_tokens recovery #${Y+1}`),yield{type:"recovery",turnId:n,action:"max_output_tokens_recovery",detail:`attempt ${Y+1}`},s={...s,messages:[...S,g],maxOutputTokensRecoveryCount:Y+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:Y+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else x.consecutiveTruncations=0;if(L=ge(L,{replayMessages:f,lastStopReason:"completed"}),k){let u=await k.invoke("stop",{sessionId:l,reason:"completed"});if(u.action==="prevent"){o.info(`stop hook prevented continuation: ${u.reason??"no reason"}`),yield{type:"end",turnId:n,content:s.finalText,usage:s.totalUsage,model:s.currentModel};return}if(u.action==="abort"){let p=u.reason??"Stop hook requested continuation";o.info(`stop hook blocking: ${p}`);let g={role:"user",content:p},v={role:"assistant",content:s.finalText,...I.length>0&&{thinkingBlocks:[...I]}};s={...s,messages:[...f,v,g],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(e.tokenBudget&&e.tokenBudget>0&&s.budgetContinuationCount<5){let u=s.totalUsage.inputTokens+s.totalUsage.outputTokens+(s.totalUsage.reasoningTokens??0),p=u/e.tokenBudget*100,g=u-s.lastBudgetGlobalTokens,v=s.budgetContinuationCount>=Et&&g<Le&&s.lastBudgetDeltaTokens<Le;if(v&&o.info(`token budget early stop: diminishing returns at ${Math.round(p)}% (delta=${g})`),!v&&p<90){let E=s.budgetContinuationCount+1,O={role:"user",content:e.runtimePorts.getBudgetContinuationMessage(p,u,e.tokenBudget)};o.info(`token budget continuation #${E}: ${Math.round(p)}% used`),yield{type:"recovery",turnId:n,action:"budget_continuation",detail:`${Math.round(p)}% used (#${E})`};let B={role:"assistant",content:s.finalText,...I.length>0&&{thinkingBlocks:[...I]}};s={...s,messages:[...f,B,O],budgetContinuationCount:E,lastBudgetDeltaTokens:g,lastBudgetGlobalTokens:u,transition:{reason:"token_budget_continuation"}};continue}}if(!s.stopHookActive){let u=d.find(E=>E.role==="user"),p=typeof u?.content=="string"?u.content:"",g=/create\s+(?:a\s+)?file|write\s+(?:a\s+)?file|make\s+(?:a\s+)?file|fix|implement|modify|update|repair|generate\s+(?:a\s+)?file|new\s+file/i.test(p),v=_.has("write")||_.has("edit");if(g&&!v){if(o.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),C>0){let B=[...f].reverse().find(xe=>xe.role==="tool");B&&typeof B.content=="string"&&(B.content+=`
|
|
5
5
|
|
|
6
|
-
\u923F\u72C5\u7B0D NOTE: You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail silently or produce incorrect results on this platform. Please use the 'write' tool directly to create the requested file with the correct content.`)}let E={role:"user",content:C===0?"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 - actually make them.":"You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail on this platform. Please use the write tool directly to create the requested file with the correct content."},O={role:"assistant",content:s.finalText,...I.length>0&&{thinkingBlocks:[...I]}};s={...s,messages:[...f,O,E],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(!s.stopHookActive&&C>=3&&_.has("write")){let u=0;for(let p of f){let g=p,v=g.is_error===!0||typeof g.content=="string"&&g.content.startsWith("Error:");g.role==="tool"&&typeof g.content=="string"&&!v&&u++}if(u>=3){o.info("AP3 verification nudge: 3+ files created, injecting completeness check");let p={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."},g={role:"assistant",content:s.finalText,...I.length>0&&{thinkingBlocks:[...I]}};s={...s,messages:[...f,g,p],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(C>0){let u={ok:!0,toolCallCount:C,distinctToolCount:_.size,multiStep:C>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},p=
|
|
7
|
-
`)}function vn(e){let t=e.filter(n=>n.source==="l1-project-md").flatMap(n=>no(n.text)),r=e.filter(n=>n.source==="l2-long-term").flatMap(n=>no(n.text)),o=[];for(let n of t)for(let l of r)n.entity===l.entity&&n.predicate===l.predicate&&n.amount!==l.amount&&o.push({entity:n.entity,predicate:n.predicate,l1Amount:n.amount,l2Amount:l.amount,l1Text:n.text,l2Text:l.text});return Ln(o)}function no(e){let t=[];for(let r of e.split(/\r?\n/)){let o=r.trim();if(o)for(let n of An){if(n==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let l=new RegExp(`${Pn(n)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let d of o.matchAll(l)){let a=In(d[1]);a!==null&&t.push({entity:En(o,n),predicate:n,amount:a,text:o})}}}return t}function En(e,t){if(/Galaxy\s+Tech/i.test(e))return"Galaxy Tech";if(e.includes("\u7528\u6237"))return"\u7528\u6237";let r=e.toLowerCase().indexOf(t.toLowerCase()),n=(r>=0?e.slice(0,r):"").replace(/[#*`:\-,。;;,.]/g," ").trim().split(/\s+/).filter(Boolean);return n[n.length-1]??"unknown"}function In(e){let t=e.replace(/,/g,"").replace(/\s+/g,"").trim(),r=t.endsWith("\u4E07")?1e4:/k$/i.test(t)?1e3:1,o=Number(t.replace(/[万kK]$/u,""));return Number.isFinite(o)?o*r:null}function wn(e){if(e.label)return e.label;switch(e.source){case"l1-project-md":return"L1 project MD";case"l2-long-term":return"L2 long-term";case"skill":return"Skill";case"system":return"System";default:return"Memory"}}function ro(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function Ln(e){let t=new Set;return e.filter(r=>{let o=`${r.entity}\0${r.predicate}\0${r.l1Amount}\0${r.l2Amount}`;return t.has(o)?!1:(t.add(o),!0)})}function Pn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ao=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;projectRoot;runtimePorts;constructor(t){this.transport=t.llmTransport,this.apiKey=t.apiKey,this.toolInvoker=t.toolInvoker,this.log=t.log,this.hooks=t.hooks,this.projectRoot=t.projectRoot,this.runtimePorts=t.runtimePorts,this.maxRounds=Math.min(t.maxRounds??25,100)}async*run(t,r){let{turnId:o,messages:n,tools:l,systemPrompt:d,config:a}=t,m={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},this.hooks?.invoke("turn.submitted",{...m,prompt:n[n.length-1]?.content??void 0}).catch(()=>{});let T=
|
|
8
|
-
${C}`})}}this.hooks.invoke("memory.after_recall",{sessionId:t.sessionId,turnId:o,blockCount:b?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let k=a?.model??"",j=Math.min(a?.maxRounds??this.maxRounds,100);try{let M=async N=>{let $=this.runtimePorts.resolveModelForPurpose("smallModel");if(!$)return null;try{let D=N.map(A=>`${A.name}(${A.arguments.slice(0,200)})`).join(", "),_=this.transport.stream({model:$,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:D}],tools:[],maxTokens:60},a?.apiKey??this.apiKey),C="";for await(let A of _)A.type==="delta"&&(C+=A.text);return C.trim()||null}catch{return null}},R=a?.reasoning;a?.reasoning?.effort==="auto"&&(R={...a?.reasoning,effort:"medium"});let w={turnId:o,sessionId:t.sessionId,messages:h,tools:l,model:k,apiKey:a?.apiKey??this.apiKey,temperature:a?.temperature,maxRounds:j,contextWindowTokens:a?.contextWindowTokens,maxOutputTokens:a?.maxOutputTokens,modelMaxOutputTokens:a?.modelMaxOutputTokens,toolChoice:a?.toolChoice,parentDepth:a?.parentDepth,hooks:this.hooks,fallbackModel:a?.fallbackModel,maxTurns:a?.maxTurns,tokenBudget:a?.tokenBudget,maxConcurrentTools:a?.maxConcurrentTools,streamRequired:a?.streamRequired,reasoning:R,promptCacheKey:a?.promptCacheKey,promptCacheRetention:a?.promptCacheRetention,serviceTier:a?.serviceTier,openaiBuiltinTools:a?.openaiBuiltinTools,maxToolCalls:a?.maxToolCalls,parallelToolCalls:a?.parallelToolCalls,textVerbosity:a?.textVerbosity,projectRoot:this.projectRoot,generateToolUseSummary:M,runtimePorts:this.runtimePorts.toolLoop,signal:r},b;for await(let N of oo(w,this.transport,this.toolInvoker,this.log))b=N,yield N;b?.type==="end"?this.hooks?.invoke("turn.completed",{...m}).catch(()=>{}):b?.type==="error"&&this.hooks?.invoke("turn.failed",{...m,code:b.code,error:b.error}).catch(()=>{})}catch(M){if(r?.aborted)this.hooks?.invoke("turn.failed",{...m,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let R=M instanceof Error?M.message:String(M),w=typeof M?.status=="number"?M.status:void 0,b=K(w,R);this.log.error(`turn ${o} error [${b}, retryable=${
|
|
6
|
+
\u923F\u72C5\u7B0D NOTE: You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail silently or produce incorrect results on this platform. Please use the 'write' tool directly to create the requested file with the correct content.`)}let E={role:"user",content:C===0?"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 - actually make them.":"You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail on this platform. Please use the write tool directly to create the requested file with the correct content."},O={role:"assistant",content:s.finalText,...I.length>0&&{thinkingBlocks:[...I]}};s={...s,messages:[...f,O,E],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(!s.stopHookActive&&C>=3&&_.has("write")){let u=0;for(let p of f){let g=p,v=g.is_error===!0||typeof g.content=="string"&&g.content.startsWith("Error:");g.role==="tool"&&typeof g.content=="string"&&!v&&u++}if(u>=3){o.info("AP3 verification nudge: 3+ files created, injecting completeness check");let p={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."},g={role:"assistant",content:s.finalText,...I.length>0&&{thinkingBlocks:[...I]}};s={...s,messages:[...f,g,p],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(C>0){let u={ok:!0,toolCallCount:C,distinctToolCount:_.size,multiStep:C>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},p=me(u,{tools:[..._],projectRoot:e.projectRoot});p&&(yield{type:"skill_instruction",turnId:n,instruction:p})}let c=s.finalText||X(f,o);for(let u of Re)yield{type:"delta",turnId:n,text:u};yield{type:"end",turnId:n,content:c,usage:s.totalUsage,model:s.currentModel};return}let co=I.length===0&&Z.length>0?Z.join(""):void 0;f.push(Se(F,void 0,I.length>0?I:void 0,co)),L=$e(L,{replayMessages:f,pendingToolCallIds:F.map(i=>i.id),completedToolCallIds:L.completedToolCallIds,lastStopReason:"tool_calls"});let ie=s.identicalCallCounts,at=[],ae=[],lt=!1;for(let i of F){let c=`${i.function.name}::${i.function.arguments}`,u=ie.get(c)??0;ie.set(c,u+1),u+1>bt?(ae.push(i),lt||(lt=!0,o.info(`AP4 blocked: ${i.function.name} repeated ${u+1}x`))):at.push(i)}let le=[];for(let i of ae){let c=ie.get(`${i.function.name}::${i.function.arguments}`),u=Ve(f,i.function.name),p=u?`This exact tool call has been attempted ${c} times. Last error: ${u}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${c} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,g=ue(i.id,{ok:!1,error:p});f.push(g),le.push(i.id),_.add(i.function.name),C++,yield{type:"tool_result",turnId:n,callId:i.id,name:i.function.name,ok:!1,error:p}}if(ae.length>0){let i=Ve(f,ae[0].function.name),c={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(i?`The error was: "${i}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};f.push(c)}let ce=[],be=[];for(let i of at)(s.toolFailureCounts.get(i.function.name)??0)>=de?be.push(i):ce.push(i);if(be.length>0){for(let c of be){let u=s.toolFailureCounts.get(c.function.name),p=`Tool "${c.function.name}" has failed ${u} times this turn with different arguments. The target likely does not exist. Stop trying variations and report the issue to the user.`,g=ue(c.id,{ok:!1,error:p});f.push(g),le.push(c.id),_.add(c.function.name),C++,yield{type:"tool_result",turnId:n,callId:c.id,name:c.function.name,ok:!1,error:p},o.info(`AP4-variant blocked: ${c.function.name} failed ${u}x with different args`)}let i={role:"user",content:"Tool calls were blocked because the tool has failed too many times with different arguments. The resource you are looking for does not exist. Stop trying variations and tell the user what happened."};f.push(i)}for(let i of ce){let c=i.function.arguments,u=A.find(p=>p.function.name===i.function.name);if(u?.backfillObservableInput)try{let p=JSON.parse(i.function.arguments),g={...p};u.backfillObservableInput(g),Object.keys(g).some(E=>!(E in p))&&(c=JSON.stringify(g))}catch{}yield{type:"tool_call",turnId:n,callId:i.id,name:i.function.name,arguments:c,inputSummary:Jt(c)}}let uo=new Map(s.toolFailureCounts);try{let i=e.runtimePorts.createStreamingToolExecutor({toolInvoker:r,hooks:k,sessionId:l,turnId:n,log:o,signal:j,maxConcurrentTools:e?.maxConcurrentTools});for(let c of ce)i.addTool(c);for await(let c of i.getRemainingResults()){c.blocked&&(yield{type:"tool_blocked",turnId:n,callId:c.callId,name:c.toolName,reason:c.blockReason??"blocked"}),f.push(c.message),le.push(c.callId),_.add(c.toolName),C++;let u=c.ok&&Xt(c);if(!c.ok||u){let g=(s.toolFailureCounts.get(c.toolName)??0)+1;s.toolFailureCounts.set(c.toolName,g)}if(c.ok&&c.toolName==="read"){let p=ce.find(g=>g.id===c.callId);if(p)try{let g=JSON.parse(p.function.arguments),v=g.file_path??g.path??g.filePath??"";if(v){let E=s.fileReadCounts.get(v)??0;s.fileReadCounts.set(v,E+1)}}catch{}}yield Kt(n,c);for(let p of Wt({turnId:n,result:c,toolCalls:F}))yield p}}catch(i){let c=i instanceof Error?i.message:String(i);yield{type:"error",turnId:n,error:c,code:"TOOL_EXECUTION_ERROR",usage:s.totalUsage};return}for(let[i,c]of s.toolFailureCounts)c>=de&&(uo.get(i)??0)<de&&f.push({role:"user",content:`Tool "${i}" has now failed/returned empty results ${c} times with different arguments. The target clearly does not exist. Do NOT call "${i}" again. Report the result to the user immediately.`});if(L=ge(L,{replayMessages:f,completedToolCallIds:[...L.completedToolCallIds,...le],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&F.length>0&&(he=!0),e.generateToolUseSummary&&F.length>0){let i=F.map(c=>({name:c.function.name,arguments:c.function.arguments}));ne=e.generateToolUseSummary(i).catch(()=>null)}let po=F.length>0&&F.every(i=>{let c=f.find(p=>p?.role==="tool"&&p?.tool_call_id===i.id);if(!c)return!0;let u=c.content;return typeof u=="string"&&u.startsWith("Error: ")}),Q=s.consecutiveFailedRounds;if(po){if(Q+=1,Q>=Rt){let i=s.finalText||X(f,o);o.info(`early exit: ${Q} consecutive failed rounds, returning ${s.finalText?"partial":"fallback"} response`),yield{type:"end",turnId:n,content:i,usage:s.totalUsage,model:s.currentModel};return}}else Q=0;let mo=3,ct=[...s.fileReadCounts.entries()].filter(([,i])=>i>=mo);if(ct.length>0){let i=ct.map(([u])=>u).join(", ");o.info(`AP5: file read cycle detected on ${i}, injecting nudge`);let c={role:"user",content:`You are reading the same files repeatedly (${i}). This indicates a circular dependency or cycle. Stop reading files, summarize your findings so far, and explain the circular structure to the user.`};f.push(c),s.fileReadCounts.clear()}let _e=V+1;if(R>0&&_e>R){if(o.info(`max turns reached (${R}), completing`),k){let c=await k.invoke("stop",{sessionId:l,reason:"max_turns"});if(c.action==="abort"){let u=c.reason??"Stop hook requested continuation after max_turns",p={role:"assistant",content:s.finalText,...I.length>0&&{thinkingBlocks:[...I]}};s={...s,messages:[...f,p,{role:"user",content:u}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let i=s.finalText||X(f,o);yield{type:"end",turnId:n,content:i,usage:s.totalUsage,model:s.currentModel};return}if(_e>$){if(o.info(`tool loop budget exhausted (${$} rounds), returning`),C>0){let c={ok:!0,toolCallCount:C,distinctToolCount:_.size,multiStep:C>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},u=me(c,{tools:[..._],projectRoot:e.projectRoot});u&&(yield{type:"skill_instruction",turnId:n,instruction:u})}let i=s.finalText||X(f,o);yield{type:"end",turnId:n,content:i,usage:s.totalUsage,model:s.currentModel};return}s={messages:f,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:_e,transition:{reason:"next_turn"},guardState:x,reactiveCompactState:U,toolLoopState:L,consecutiveFailedRounds:Q,finalText:s.finalText,totalUsage:s.totalUsage,collapseStore:Ce,currentModel:s.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:s.stopHookActive,lastResponseId:s.lastResponseId,snipRemovedIds:s.snipRemovedIds,contentReplacementState:s.contentReplacementState,budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:ie,toolFailureCounts:s.toolFailureCounts,fileReadCounts:s.fileReadCounts}}}var An=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function so(e){let t=vn(e),r=["[Recalled memories]","- L1 project MD is project-scoped working memory.","- L2 long-term memory is cross-project canonical memory.","- If L1 and L2 conflict on the same entity/fact, do not silently merge or choose. Surface the conflict and ask the user to confirm. For current-project operational tasks, use L1 only as a project-scoped clue until confirmed into L2."];if(t.length>0){r.push("[Memory conflict detected]");for(let o of t)r.push(`- entity: ${o.entity}; fact: ${o.predicate}; L1 project MD says: ${ro(o.l1Amount)}; L2 long-term says: ${ro(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let n=wn(o);r.push(`- [${n}] ${o.text}`)}return r.join(`
|
|
7
|
+
`)}function vn(e){let t=e.filter(n=>n.source==="l1-project-md").flatMap(n=>no(n.text)),r=e.filter(n=>n.source==="l2-long-term").flatMap(n=>no(n.text)),o=[];for(let n of t)for(let l of r)n.entity===l.entity&&n.predicate===l.predicate&&n.amount!==l.amount&&o.push({entity:n.entity,predicate:n.predicate,l1Amount:n.amount,l2Amount:l.amount,l1Text:n.text,l2Text:l.text});return Ln(o)}function no(e){let t=[];for(let r of e.split(/\r?\n/)){let o=r.trim();if(o)for(let n of An){if(n==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let l=new RegExp(`${Pn(n)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let d of o.matchAll(l)){let a=In(d[1]);a!==null&&t.push({entity:En(o,n),predicate:n,amount:a,text:o})}}}return t}function En(e,t){if(/Galaxy\s+Tech/i.test(e))return"Galaxy Tech";if(e.includes("\u7528\u6237"))return"\u7528\u6237";let r=e.toLowerCase().indexOf(t.toLowerCase()),n=(r>=0?e.slice(0,r):"").replace(/[#*`:\-,。;;,.]/g," ").trim().split(/\s+/).filter(Boolean);return n[n.length-1]??"unknown"}function In(e){let t=e.replace(/,/g,"").replace(/\s+/g,"").trim(),r=t.endsWith("\u4E07")?1e4:/k$/i.test(t)?1e3:1,o=Number(t.replace(/[万kK]$/u,""));return Number.isFinite(o)?o*r:null}function wn(e){if(e.label)return e.label;switch(e.source){case"l1-project-md":return"L1 project MD";case"l2-long-term":return"L2 long-term";case"skill":return"Skill";case"system":return"System";default:return"Memory"}}function ro(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function Ln(e){let t=new Set;return e.filter(r=>{let o=`${r.entity}\0${r.predicate}\0${r.l1Amount}\0${r.l2Amount}`;return t.has(o)?!1:(t.add(o),!0)})}function Pn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ao=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;projectRoot;runtimePorts;constructor(t){this.transport=t.llmTransport,this.apiKey=t.apiKey,this.toolInvoker=t.toolInvoker,this.log=t.log,this.hooks=t.hooks,this.projectRoot=t.projectRoot,this.runtimePorts=t.runtimePorts,this.maxRounds=Math.min(t.maxRounds??25,100)}async*run(t,r){let{turnId:o,messages:n,tools:l,systemPrompt:d,config:a}=t,m={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},this.hooks?.invoke("turn.submitted",{...m,prompt:n[n.length-1]?.content??void 0}).catch(()=>{});let T=Ue(n),h=[];if(d&&h.push({role:"system",content:d}),h.push(...T),this.hooks){let M=T.filter(w=>w.role==="user").pop(),R=typeof M?.content=="string"?M.content.slice(0,500):void 0;if(R)try{let w=this.runtimePorts.detectRecallCategories(R),b=await this.hooks.invoke("memory.before_recall",{sessionId:t.sessionId,turnId:o,query:R,preferredCategories:w.preferred.length>0?w.preferred:void 0,deprioritizedCategories:w.deprioritized.length>0?w.deprioritized:void 0}),N=b?.context?.recalledMemories;if(N&&N.length>0){let D=0,_=[];for(let C of N){let A=(C.text?.length??0)*2;if(D+A>8192)break;_.push(C),D+=A}if(_.length>0){let C=so(_);h.splice(d?1:0,0,{role:"system",content:`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
|
|
8
|
+
${C}`})}}this.hooks.invoke("memory.after_recall",{sessionId:t.sessionId,turnId:o,blockCount:b?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let k=a?.model??"",j=Math.min(a?.maxRounds??this.maxRounds,100);try{let M=async N=>{let $=this.runtimePorts.resolveModelForPurpose("smallModel");if(!$)return null;try{let D=N.map(A=>`${A.name}(${A.arguments.slice(0,200)})`).join(", "),_=this.transport.stream({model:$,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:D}],tools:[],maxTokens:60},a?.apiKey??this.apiKey),C="";for await(let A of _)A.type==="delta"&&(C+=A.text);return C.trim()||null}catch{return null}},R=a?.reasoning;a?.reasoning?.effort==="auto"&&(R={...a?.reasoning,effort:"medium"});let w={turnId:o,sessionId:t.sessionId,messages:h,tools:l,model:k,apiKey:a?.apiKey??this.apiKey,temperature:a?.temperature,maxRounds:j,contextWindowTokens:a?.contextWindowTokens,maxOutputTokens:a?.maxOutputTokens,modelMaxOutputTokens:a?.modelMaxOutputTokens,toolChoice:a?.toolChoice,parentDepth:a?.parentDepth,hooks:this.hooks,fallbackModel:a?.fallbackModel,maxTurns:a?.maxTurns,tokenBudget:a?.tokenBudget,maxConcurrentTools:a?.maxConcurrentTools,streamRequired:a?.streamRequired,reasoning:R,promptCacheKey:a?.promptCacheKey,promptCacheRetention:a?.promptCacheRetention,serviceTier:a?.serviceTier,openaiBuiltinTools:a?.openaiBuiltinTools,maxToolCalls:a?.maxToolCalls,parallelToolCalls:a?.parallelToolCalls,textVerbosity:a?.textVerbosity,projectRoot:this.projectRoot,generateToolUseSummary:M,runtimePorts:this.runtimePorts.toolLoop,signal:r},b;for await(let N of oo(w,this.transport,this.toolInvoker,this.log))b=N,yield N;b?.type==="end"?this.hooks?.invoke("turn.completed",{...m}).catch(()=>{}):b?.type==="error"&&this.hooks?.invoke("turn.failed",{...m,code:b.code,error:b.error}).catch(()=>{})}catch(M){if(r?.aborted)this.hooks?.invoke("turn.failed",{...m,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let R=M instanceof Error?M.message:String(M),w=typeof M?.status=="number"?M.status:void 0,b=K(w,R);this.log.error(`turn ${o} error [${b}, retryable=${Ae(b)}]: ${R}`),this.hooks?.invoke("turn.failed",{...m,code:b,error:R}).catch(()=>{}),yield{type:"error",turnId:o,error:R,code:b}}}}};export{ao as Agent};
|