qlogicagent 2.12.3 → 2.12.5

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.
Files changed (44) hide show
  1. package/dist/agent.js +6 -6
  2. package/dist/cli.js +344 -316
  3. package/dist/index.js +344 -316
  4. package/dist/orchestration.js +1 -1
  5. package/dist/protocol.js +1 -1
  6. package/dist/types/cli/acp-extended-handlers.d.ts +0 -1
  7. package/dist/types/cli/agent-runtime-bootstrap.d.ts +2 -0
  8. package/dist/types/cli/conversation-context.d.ts +30 -0
  9. package/dist/types/cli/core-tool-coordinator.d.ts +6 -1
  10. package/dist/types/cli/core-tools/agent-tool-service.d.ts +12 -0
  11. package/dist/types/cli/core-tools/registry.d.ts +1 -1
  12. package/dist/types/cli/core-tools/team-registry.d.ts +62 -0
  13. package/dist/types/cli/core-tools/team-tool-bootstrap.d.ts +3 -1
  14. package/dist/types/cli/core-tools/team-tool-service.d.ts +12 -1
  15. package/dist/types/cli/core-tools/utility-tool-bootstrap.d.ts +3 -1
  16. package/dist/types/cli/dream-host-adapter.d.ts +1 -0
  17. package/dist/types/cli/handlers/config-handler.d.ts +2 -0
  18. package/dist/types/cli/handlers/dream-handler.d.ts +2 -0
  19. package/dist/types/cli/runtime-hook-bootstrap.d.ts +2 -0
  20. package/dist/types/cli/session-coordinator.d.ts +7 -6
  21. package/dist/types/cli/session-history-coordinator.d.ts +2 -0
  22. package/dist/types/cli/stdio-agent-session-bootstrap.d.ts +2 -0
  23. package/dist/types/cli/stdio-server.d.ts +10 -0
  24. package/dist/types/cli/tool-bootstrap.d.ts +7 -12
  25. package/dist/types/contracts/fire-hook.d.ts +14 -0
  26. package/dist/types/protocol/wire/acp-protocol.d.ts +0 -1
  27. package/dist/types/runtime/execution/dream-agent.d.ts +30 -5
  28. package/dist/types/runtime/execution/fork-context.d.ts +14 -0
  29. package/dist/types/runtime/infra/background-tasks.d.ts +89 -0
  30. package/dist/types/runtime/infra/task-runtime.d.ts +1 -38
  31. package/dist/types/runtime/tasks/task-types.d.ts +22 -8
  32. package/dist/types/skills/memory/local-memory-provider.d.ts +15 -0
  33. package/dist/types/skills/memory/local-store.d.ts +11 -0
  34. package/dist/types/skills/memory/memory-consolidation.d.ts +7 -0
  35. package/dist/types/skills/tools/agent-tool.d.ts +21 -10
  36. package/dist/types/skills/tools/exec-tool.d.ts +13 -0
  37. package/dist/types/skills/tools/monitor-tool.d.ts +3 -3
  38. package/dist/types/skills/tools/send-message-tool.d.ts +6 -0
  39. package/dist/types/skills/tools/shell/index.d.ts +1 -1
  40. package/dist/types/skills/tools/shell/task-output.d.ts +0 -1
  41. package/dist/types/skills/tools/task-tool.d.ts +37 -5
  42. package/dist/types/skills/tools/team-tool.d.ts +5 -0
  43. package/dist/types/transport/acp-server.d.ts +0 -1
  44. package/package.json +1 -1
package/dist/agent.js CHANGED
@@ -1,8 +1,8 @@
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 fo=/\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]},yo=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,To=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,ho=512,Co=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var ko=new Set([500,502,503,504,521,522,523,524,529]),Ro=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],bo=["upgrade your plan","upgrade plan","current plan","subscription"],_o=["daily","weekly","monthly"],xo=["try again","retry","temporary","cooldown"],So=["usage limit","rate limit","organization usage"],Mo=["organization","workspace"],Ao=["billing period","exceeded","reached","exhausted"],vo=/["']?(?: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,Eo=/^(?: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 Io(e){return z(e,q.format)}function ut(e){return z(e,q.rateLimit)}function wo(e){return z(e,q.timeout)}function Lo(e){return fo.test(e)}function Me(e){let t=e.toLowerCase();return t?e.length>ho?To.test(t):z(t,q.billing)?!0:yo.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 Po(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 Oo(e){return H(e,Ro)||H(e,bo)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function No(e){let t=H(e,_o),r=e.includes("spend limit")||e.includes("spending limit"),o=H(e,Mo);return H(e,xo)&&H(e,So)||t&&(e.includes("usage limit")||r)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(r||H(e,Ao))}function Do(e){return e.trim().toLowerCase().replace(Eo,"").trim()}function mt(e){let t=Do(e);return!t||Oo(t)?"billing":ut(t)||No(t)?"rate_limit":"billing"}function Fo(e){return vo.test(e)?mt(e):null}function gt(e){let t=e.match(Co);if(!t)return null;let r=Number(t[1]);return Number.isFinite(r)?{code:r,rest:(t[2]??"").trim()}:null}function Bo(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Uo(e){let t=e.trim();if(!t)return!1;let r=gt(t);return r?ko.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 $o(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 jo(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(jo(e))return"session_expired";if($o(e))return"model_not_found";let t=Fo(e);return t||(Lo(e)?Me(e)?"billing":"rate_limit":ut(e)?"rate_limit":pt(e)?"overloaded":Uo(e)?gt(e.trim())?.code===529?"overloaded":"timeout":Bo(e)?"timeout":Io(e)?"format":Me(e)?"billing":wo(e)?"timeout":dt(e)?"auth_permanent":Po(e)?"auth":null)}var Go={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"},Ho=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function K(e,t){let r=ft(e,t)??(t?yt(t):null);return r?Go[r]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Ae(e){return Ho.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 qo=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||!qo.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=zo(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 zo(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 Ko,readdirSync as $t,mkdirSync as Wo}from"node:fs";import{join as Oe,dirname as Xo}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 qn=300*1e3;var zn=3600*1e3;var Kn=50*1024,Wn=500*1024,Xn=500*1024*1024,Yn=50*1024*1024;var Vn=60*1024;var jt=0;var Yo="skill-patterns.json";function Gt(e){return Oe(e,".qlogicagent",Yo)}function Vo(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);Wo(Xo(r),{recursive:!0}),Ko(r,JSON.stringify(t,null,2),"utf8")}function Jo(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=Vo(e);Jo(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 Zo(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 Qo(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 en(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<Pt||e.distinctToolCount<Ot||Date.now()-jt<Nt||t?.projectSkillsDir&&(Qo(t.projectSkillsDir)>=Lt||t.tools.length>0&&Zo(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Ht(t.projectRoot,t.tools))}function tn(e){return e.existingSkillName?e.feedback==="negative":!1}function me(e,t){return tn(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:en(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 on(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function nn(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function rn(e){if(!e.eligibility?.length)return[...e.tools];let t=nn(e.eligibility);return e.tools.filter(r=>{let o=qt(r);if(!o)return!1;let n=t.get(o);return!n||on(n.status)})}function sn(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=sn({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),r=t.normalizedToolChoice,o=[...t.warnings],n=rn({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 an=["stop","aborted","timeout","cancelled","interrupted","error"],ln=["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 cn(e,t){return{...e,content:[...zt(e.content),...zt(t.content)]}}function un(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 dn(e){return new Set((e??an).map(t=>t.trim().toLowerCase()))}function pn(e,t){return e?dn(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=>un(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]=cn(m,a);continue}d.push(a)}return d}function Fe(e,t){return pn(t?.stopReason,t?.forcedStopReasons)?e.map(r=>{if(r.role!=="assistant")return{...r};let o={...r};for(let n of ln)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 mn(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 gn(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 fn(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:fn({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:n,pendingToolCallIds:mn(n),completedToolCallIds:gn(n)}),recoveryActions:t}}var yn=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function je(e){return e?yn.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 lr={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 hn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Xe(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function W(e,t=hn){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}}function Wt(e,t){if(!t.ok)return[];let r=t.details;if(!r)return[];let o=Cn(r);return o?(Array.isArray(r.mediaUrls)?r.mediaUrls.filter(l=>typeof l=="string"&&l.trim().length>0):[]).map(l=>({type:"media_result",turnId:e,mediaType:o,url:l,model:typeof r.model=="string"?r.model:void 0,provider:typeof r.provider=="string"?r.provider:void 0,durationSeconds:typeof r.durationMs=="number"?r.durationMs/1e3:void 0,taskId:typeof r.taskId=="string"?r.taskId:void 0})):[]}function Cn(e){let t=typeof e.type=="string"?e.type:"";if(!t)return null;if(t==="three_d_generate")return"3d";let r=t.split("_")[0];return r==="image"||r==="tts"||r==="video"||r==="music"?r:null}var kn=new Set(["write","edit","patch","apply_patch"]);function Xt(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=Rn(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}),kn.has(r.toolName)){let a=bn(d);a&&l.push({type:"artifact",turnId:t,artifactId:`artifact-${r.callId}`,artifactType:_n(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:xn(a)})}return l}function Rn(e){try{return JSON.parse(e)}catch{return null}}function bn(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 _n(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 xn(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 Mn=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,An=new Set(["search","web_search","grep","glob","find","list","read","exec"]);function Yt(e){if(!An.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&Mn.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 Vt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.round(e),100):kt}function Jt(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 de(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 yo=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,z={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]},To=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,ho=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Co=512,ko=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Ro=new Set([500,502,503,504,521,522,523,524,529]),bo=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],_o=["upgrade your plan","upgrade plan","current plan","subscription"],xo=["daily","weekly","monthly"],Mo=["try again","retry","temporary","cooldown"],So=["usage limit","rate limit","organization usage"],Ao=["organization","workspace"],vo=["billing period","exceeded","reached","exhausted"],Eo=/["']?(?: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,Io=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function K(e,t){if(!e)return!1;let r=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(r):r.includes(o))}function wo(e){return K(e,z.format)}function dt(e){return K(e,z.rateLimit)}function Lo(e){return K(e,z.timeout)}function Po(e){return yo.test(e)}function Ae(e){let t=e.toLowerCase();return t?e.length>Co?ho.test(t):K(t,z.billing)?!0:To.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function pt(e){return K(e,z.authPermanent)}function Oo(e){return K(e,z.auth)}function mt(e){return K(e,z.overloaded)}function q(e,t){return t.some(r=>e.includes(r))}function No(e){return q(e,bo)||q(e,_o)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Do(e){let t=q(e,xo),r=e.includes("spend limit")||e.includes("spending limit"),o=q(e,Ao);return q(e,Mo)&&q(e,So)||t&&(e.includes("usage limit")||r)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(r||q(e,vo))}function Fo(e){return e.trim().toLowerCase().replace(Io,"").trim()}function gt(e){let t=Fo(e);return!t||No(t)?"billing":dt(t)||Do(t)?"rate_limit":"billing"}function Bo(e){return Eo.test(e)?gt(e):null}function ft(e){let t=e.match(ko);if(!t)return null;let r=Number(t[1]);return Number.isFinite(r)?{code:r,rest:(t[2]??"").trim()}:null}function Uo(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function $o(e){let t=e.trim();if(!t)return!1;let r=ft(t);return r?Ro.has(r.code):!1}function yt(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?gt(t):"billing":e===429?"rate_limit":e===401||e===403?t&&pt(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&mt(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&Ae(t)?"billing":"format":null}function jo(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 Ho(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 Tt(e){if(Ho(e))return"session_expired";if(jo(e))return"model_not_found";let t=Bo(e);return t||(Po(e)?Ae(e)?"billing":"rate_limit":dt(e)?"rate_limit":mt(e)?"overloaded":$o(e)?ft(e.trim())?.code===529?"overloaded":"timeout":Uo(e)?"timeout":wo(e)?"format":Ae(e)?"billing":Lo(e)?"timeout":pt(e)?"auth_permanent":Oo(e)?"auth":null)}var Go={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"},qo=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function W(e,t){let r=yt(e,t)??(t?Tt(t):null);return r?Go[r]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function ve(e){return qo.has(e)}function ht(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var zo=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"]),te=class{constructor(t=20,r=ht){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||!zo.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 Ee(e,t,r=ht){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 Ie(){return{stages:[]}}function we(e,t,r){let o=r?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let l=Ct(e,t),d=Ko(l,t,o);if(d.length===0)return{messages:l,stagedCount:0};for(let a of d)t.stages.push(a);return l=Ct(e,t),{messages:l,stagedCount:d.length}}function Le(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:kt(e,t),committed:r}}function Ct(e,t){return t.stages.filter(o=>o.committed).length===0?e:kt(e,t)}function kt(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 Ko(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 Oe,readFileSync as $t,writeFileSync as Wo,readdirSync as jt,mkdirSync as Xo}from"node:fs";import{join as Ne,dirname as Yo}from"node:path";var Rt=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),bt=3,_t=2,pe=2,xt=128e3,Mt=13e3,St=16384,At=65536,vt=3,Et=65536,Pe=500,It=3;var wt=3e4,Lt=3,oe=2;var Pt=20;var Ot=3,Nt=2,Dt=300*1e3,Ft=3,Bt=720*60*60*1e3;var zn=300*1e3;var Kn=3600*1e3;var Wn=50*1024,Xn=500*1024,Yn=500*1024*1024,Vn=50*1024*1024;var Jn=60*1024;var Ht=0;var Vo="skill-patterns.json";function Gt(e){return Ne(e,".qlogicagent",Vo)}function Jo(e){let t=Gt(e);try{return JSON.parse($t(t,"utf8"))}catch{return{version:1,patterns:{}}}}function Ut(e,t){let r=Gt(e);Xo(Yo(r),{recursive:!0}),Wo(r,JSON.stringify(t,null,2),"utf8")}function Zo(e){let t=Date.now()-Bt;for(let[r,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[r]}function qt(e,t){if(t.length===0)return!1;let r=me(t),o=Jo(e);Zo(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 Ut(e,o),!1;l.count++,l.lastSeen=n;let d=l.count>=Ft;return d&&(l.promoted=!0),Ut(e,o),d}function me(e){return[...e].sort().join("+")}function Qo(e,t){if(!Oe(t))return null;let r=me(e);try{let o=jt(t,{withFileTypes:!0});for(let n of o){if(!n.isDirectory())continue;let l=Ne(t,n.name,"SKILL.md");try{let a=$t(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(me(m)===r)return n.name}}catch{}}}catch{}return null}function en(e){if(!Oe(e))return 0;try{return jt(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&Oe(Ne(e,t.name,"SKILL.md"))).length}catch{return 0}}function tn(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<Ot||e.distinctToolCount<Nt||Date.now()-Ht<Dt||t?.projectSkillsDir&&(en(t.projectSkillsDir)>=Pt||t.tools.length>0&&Qo(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!qt(t.projectRoot,t.tools))}function on(e){return e.existingSkillName?e.feedback==="negative":!1}function ge(e,t){return on(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:tn(e,t)?(Ht=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function zt(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function nn(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function rn(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function sn(e){if(!e.eligibility?.length)return[...e.tools];let t=rn(e.eligibility);return e.tools.filter(r=>{let o=zt(r);if(!o)return!1;let n=t.get(o);return!n||nn(n.status)})}function an(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 De(e){let t=an({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),r=t.normalizedToolChoice,o=[...t.warnings],n=sn({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=>zt(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 ln=["stop","aborted","timeout","cancelled","interrupted","error"],cn=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Kt(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function un(e,t){return{...e,content:[...Kt(e.content),...Kt(t.content)]}}function dn(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 pn(e){return new Set((e??ln).map(t=>t.trim().toLowerCase()))}function mn(e,t){return e?pn(t).has(e.trim().toLowerCase()):!1}function Fe(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=>dn(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]=un(m,a);continue}d.push(a)}return d}function Be(e,t){return mn(t?.stopReason,t?.forcedStopReasons)?e.map(r=>{if(r.role!=="assistant")return{...r};let o={...r};for(let n of cn)delete o[n];return o}):[...e]}function Ue(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 $e(e,t){let r=Fe(e),o=Be(r,t);return Ue(o,t)}function gn(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 fn(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 yn(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function je(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 fe(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 ye(e){let t=[],r=Fe(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=Be(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=Ue(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:yn({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:n,pendingToolCallIds:gn(n),completedToolCallIds:fn(n)}),recoveryActions:t}}var Tn=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function He(e){return e?Tn.has(e):!0}function Ge(e){return e===429||e===529}function Te(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 cr={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function he(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var ne=class extends Error{constructor(r,o){super(`Model fallback triggered: ${r} -> ${o}`);this.originalModel=r;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function qe(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function ze(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 Ke(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 We(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 Xe(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Cn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Ye(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function X(e,t=Cn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function Ve(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 I(e,t,r,o){e?.invoke(t,r).catch(n=>{let l=n instanceof Error?n.message:String(n);o.warn(`[hook:${t}] handler failed: ${l}`)})}function Wt(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}}function Xt(e,t){if(!t.ok)return[];let r=t.details;if(!r)return[];let o=kn(r);return o?(Array.isArray(r.mediaUrls)?r.mediaUrls.filter(l=>typeof l=="string"&&l.trim().length>0):[]).map(l=>({type:"media_result",turnId:e,mediaType:o,url:l,model:typeof r.model=="string"?r.model:void 0,provider:typeof r.provider=="string"?r.provider:void 0,durationSeconds:typeof r.durationMs=="number"?r.durationMs/1e3:void 0,taskId:typeof r.taskId=="string"?r.taskId:void 0})):[]}function kn(e){let t=typeof e.type=="string"?e.type:"";if(!t)return null;if(t==="three_d_generate")return"3d";let r=t.split("_")[0];return r==="image"||r==="tts"||r==="video"||r==="music"?r:null}var Rn=new Set(["write","edit","patch","apply_patch"]);function Yt(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=bn(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}),Rn.has(r.toolName)){let a=_n(d);a&&l.push({type:"artifact",turnId:t,artifactId:`artifact-${r.callId}`,artifactType:xn(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:Mn(a)})}return l}function bn(e){try{return JSON.parse(e)}catch{return null}}function _n(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 xn(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 Mn(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 An=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,vn=new Set(["search","web_search","grep","glob","find","list","read","exec"]);function Vt(e){if(!vn.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&An.test(t)}function Je(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 Jt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.round(e),100):Rt}function Zt(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function Y(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 Zt(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 Qt(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 eo(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 to(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*oo(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*no(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*oo(n,m,d,T,h,j,t,o);return}let $=Vt(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:Fn,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=Jt(S);let co=e.toolChoice==="required"&&he?"auto":e.toolChoice??"auto",re=Ne({tools:A,toolChoice:co}),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=to({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=eo({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(Qt(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+=`
4
+ `)):""}function Qt(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 Ze(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 eo(e){return e==="length"||e==="max_tokens"}function Qe(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 to(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 oo(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*no(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*ro(e,t,r,o){let{turnId:n,sessionId:l,messages:d,tools:a,model:m,apiKey:T,temperature:h=0,hooks:k,signal:H}=e,S={sessionId:l,turnId:n},R=e.maxTurns??0,L=e.querySource,b=e.runtimePorts.resolveToolEligibility(a,e.toolEligibilityContext),D=b.eligibleTools;for(let f of b.blockedTools)yield{type:"tool_blocked",turnId:n,callId:"",name:f.toolName,reason:"blocked-by-policy"};if(!D.length){yield*no(n,m,d,T,h,H,t,o);return}let j=Jt(e.maxRounds),F={contextWindowTokens:e.contextWindowTokens??xt,responseBufferTokens:Mt,maxOutputTokens:e.maxOutputTokens??St,abortSignal:H,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},_=new Set,C=0,A=D,re,Ce=!1,et=0,s={messages:[...d],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:qe(F),reactiveCompactState:Ye(),toolLoopState:ye({maxRounds:j,replayMessages:[...d]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:Ie(),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},tt=Math.max(R*5,200),ot=0;for(;;){if(ot++,ot>tt){o.info(`hard iteration cap reached (${tt}), forcing completion`);let i=s.finalText||Y(s.messages,o);yield{type:"end",turnId:n,content:i,usage:s.totalUsage,model:s.currentModel};return}let{messages:f,maxOutputTokensRecoveryCount:V,hasAttemptedReactiveCompact:Bn,maxOutputTokensOverride:nt,turnCount:J,guardState:x,reactiveCompactState:$,collapseStore:ke}=s,{toolLoopState:P}=s;if(re){try{let i=await re;i&&(yield{type:"tool_use_summary",turnId:n,summary:i})}catch{}re=void 0}if(e.refreshTools&&J>1){let i=e.refreshTools();i!==A&&(A=i,o.debug(`tools refreshed: ${i.length} tools`))}if(Xe(x,F)){o.info(`turn aborted by guard at turn ${J}`),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED",usage:s.totalUsage};return}let G=ze(x,F);if(G.level==="blocking"){G.reason==="prompt_too_long"&&X($)&&($.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 M;{let i=await e.runtimePorts.enforceToolResultBudget(f,s.contentReplacementState,l);M=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=Ee(M,s.snipRemovedIds);M=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 te().compress(M,0);c.droppedCount>0&&(M=c.messages,o.info(`microcompact: cleared ${c.droppedCount} old tool results`))}if(M=we(M,ke).messages,x.promptTokens>0){let i=F.contextWindowTokens*.75,c=e.runtimePorts.getActiveContextCompressionEngine(),u;c?u=await c.compressAsync(M,i,{model:s.currentModel,sessionId:l}):u=e.runtimePorts.compressMessages(M,{budget:i,model:s.currentModel}),u.droppedCount>0&&(M=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,I(k,"context.after_compact",{...S,removedCount:u.droppedCount},o))}M=Zt(M);let uo=e.toolChoice==="required"&&Ce?"auto":e.toolChoice??"auto",se=De({tools:A,toolChoice:uo}),Z=ye({maxRounds:j,replayMessages:M,lastStopReason:P.lastStopReason,options:{stopReason:P.lastStopReason}}),rt=se.extraSystemPrompt?[{role:"system",content:se.extraSystemPrompt},...Z.state.replayMessages]:Z.state.replayMessages;P=Z.state,Z.recoveryActions.length>0&&o.debug(`tool loop recovery: ${Z.recoveryActions.map(i=>i.detail??i.kind).join("; ")}`),o.debug(`turn ${J}, messages: ${rt.length}`),I(k,"turn.before_inference",{...S,model:s.currentModel},o);let Re=!1,be=[],st=new Map,it="stop",O,y=null,ie=!1,Q=[],w=[];try{for await(let i of t.stream({model:s.currentModel,messages:rt,tools:se.tools,toolChoice:se.normalizedToolChoice??"auto",temperature:h,maxTokens:(nt??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,H))switch(i.type){case"delta":be.push(i.text);break;case"tool_call_delta":Re=!0,Ve(st,i);break;case"reasoning_delta":Q.push(i.text);break;case"reasoning_block_complete":i.signature&&w.push({thinking:Q.join(""),signature:i.signature}),Q.length=0;break;case"usage":O={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":it=i.finishReason;break}if(Re||I(k,"turn.after_inference",{...S,model:s.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let i=s.currentModel;for(let c of e.postSamplingHooks)try{c({messages:[...M],model:i,sessionId:l})}catch{}}}catch(i){if(i instanceof ne&&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>oe){o.info(`stale connection retry limit reached (${oe}), 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=oo({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&&!he()){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>=Lt&&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(he()){let E=Te(s.consecutive529Errors);o.info(`persistent retry: waiting ${E}ms (attempt ${s.consecutive529Errors})`);let N=E;for(;N>0;){if(H?.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(N/1e3)}s (${u})`};let U=Math.min(N,wt);await new Promise(Me=>setTimeout(Me,U)),N-=U}s={...s,transition:void 0};continue}if(He(L)){let N=to({status:u,message:c})??Te(s.consecutive529Errors);o.info(`transient ${u}: retry in ${N}ms`),yield{type:"recovery",turnId:n,action:"retry",detail:`${u} retry in ${N}ms`},await new Promise(U=>setTimeout(U,N)),s={...s,transition:void 0};continue}o.info(`background source ${L}: not retrying ${u}`)}y={status:u,message:c}}if(y&&I(k,"turn.after_inference",{...S,model:s.currentModel,response:{error:y.message}},o),y)if(Ze(y))ie=!0,o.info(`withheld prompt_too_long error (status=${y.status})`);else if(Qe(y))ie=!0,o.info(`withheld media_size error (status=${y.status})`);else{let i=Ke({status:y.status??500,message:y.message},x,F);if(i.action==="reactive_compact"&&X($)&&($.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>oe){o.info(`API retry limit reached (${oe}), aborting`);let p=W(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=W(y.status,y.message);I(k,"stop.failure",{sessionId:l,reason:c,error:y.message},o),yield{type:"error",turnId:n,error:y.message,code:c,usage:s.totalUsage};return}O&&(s.totalUsage.inputTokens+=O.inputTokens,s.totalUsage.outputTokens+=O.outputTokens,O.reasoningTokens&&(s.totalUsage.reasoningTokens=(s.totalUsage.reasoningTokens??0)+O.reasoningTokens),O.cacheRead&&(s.totalUsage.cacheRead=(s.totalUsage.cacheRead??0)+O.cacheRead),O.cacheWrite&&(s.totalUsage.cacheWrite=(s.totalUsage.cacheWrite??0)+O.cacheWrite)),O?.inputTokens&&(x.promptTokens=O.inputTokens);let at=be.join(""),B=[...st.values()].map(i=>({id:i.id||`tc_${n}_${J}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:i.name,arguments:i.arguments}}));if(B.length===0&&!Re){if(at&&(s.finalText=at),e.toolChoice==="required"&&!Ce&&A.length>0&&et<2){et++;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(ie&&y&&Ze(y)){if(s.transition?.reason!=="collapse_drain_retry"){let u=Le(M,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(X($)){$.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"),I(k,"stop.failure",{sessionId:l,reason:"prompt_too_long",error:y.message},o),yield{type:"error",turnId:n,error:y.message,code:"PROMPT_TOO_LONG",usage:s.totalUsage};return}if(ie&&y&&Qe(y)){if(X($)){$.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"),I(k,"stop.failure",{sessionId:l,reason:"media_error",error:y.message},o),yield{type:"error",turnId:n,error:y.message,code:"IMAGE_ERROR",usage:s.totalUsage};return}if(eo(it)){x.consecutiveTruncations+=1;let u=e.modelMaxOutputTokens??At,p=We(x,F,u);if(p.shouldEscalate&&nt===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:Et,transition:{reason:"max_output_tokens_escalate"}};continue}if(V<vt){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 #${V+1}`),yield{type:"recovery",turnId:n,action:"max_output_tokens_recovery",detail:`attempt ${V+1}`},s={...s,messages:[...M,g],maxOutputTokensRecoveryCount:V+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:V+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else x.consecutiveTruncations=0;if(P=fe(P,{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,...w.length>0&&{thinkingBlocks:[...w]}};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>=It&&g<Pe&&s.lastBudgetDeltaTokens<Pe;if(v&&o.info(`token budget early stop: diminishing returns at ${Math.round(p)}% (delta=${g})`),!v&&p<90){let E=s.budgetContinuationCount+1,N={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 U={role:"assistant",content:s.finalText,...w.length>0&&{thinkingBlocks:[...w]}};s={...s,messages:[...f,U,N],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 U=[...f].reverse().find(Me=>Me.role==="tool");U&&typeof U.content=="string"&&(U.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=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 uo=I.length===0&&Z.length>0?Z.join(""):void 0;f.push(Se(F,void 0,I.length>0?I:void 0,uo)),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:Zt(c)}}let po=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&&Yt(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(n,c))yield p;for(let p of Xt({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&&(po.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 mo=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(mo){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 go=3,ct=[...s.fileReadCounts.entries()].filter(([,i])=>i>=go);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 En=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function io(e){let t=In(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: ${so(o.l1Amount)}; L2 long-term says: ${so(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let n=Pn(o);r.push(`- [${n}] ${o.text}`)}return r.join(`
7
- `)}function In(e){let t=e.filter(n=>n.source==="l1-project-md").flatMap(n=>ro(n.text)),r=e.filter(n=>n.source==="l2-long-term").flatMap(n=>ro(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 On(o)}function ro(e){let t=[];for(let r of e.split(/\r?\n/)){let o=r.trim();if(o)for(let n of En){if(n==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let l=new RegExp(`${Nn(n)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let d of o.matchAll(l)){let a=Ln(d[1]);a!==null&&t.push({entity:wn(o,n),predicate:n,amount:a,text:o})}}}return t}function wn(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 Ln(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 Pn(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 so(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function On(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 Nn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var lo=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=io(_);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 no(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{lo as Agent};
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."},N={role:"assistant",content:s.finalText,...w.length>0&&{thinkingBlocks:[...w]}};s={...s,messages:[...f,N,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,...w.length>0&&{thinkingBlocks:[...w]}};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=ge(u,{tools:[..._],projectRoot:e.projectRoot});p&&(yield{type:"skill_instruction",turnId:n,instruction:p})}let c=s.finalText||Y(f,o);for(let u of be)yield{type:"delta",turnId:n,text:u};yield{type:"end",turnId:n,content:c,usage:s.totalUsage,model:s.currentModel};return}let po=w.length===0&&Q.length>0?Q.join(""):void 0;f.push(Se(B,void 0,w.length>0?w:void 0,po)),P=je(P,{replayMessages:f,pendingToolCallIds:B.map(i=>i.id),completedToolCallIds:P.completedToolCallIds,lastStopReason:"tool_calls"});let ae=s.identicalCallCounts,lt=[],le=[],ct=!1;for(let i of B){let c=`${i.function.name}::${i.function.arguments}`,u=ae.get(c)??0;ae.set(c,u+1),u+1>_t?(le.push(i),ct||(ct=!0,o.info(`AP4 blocked: ${i.function.name} repeated ${u+1}x`))):lt.push(i)}let ce=[];for(let i of le){let c=ae.get(`${i.function.name}::${i.function.arguments}`),u=Je(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=de(i.id,{ok:!1,error:p});f.push(g),ce.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(le.length>0){let i=Je(f,le[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 ue=[],_e=[];for(let i of lt)(s.toolFailureCounts.get(i.function.name)??0)>=pe?_e.push(i):ue.push(i);if(_e.length>0){for(let c of _e){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=de(c.id,{ok:!1,error:p});f.push(g),ce.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 ue){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:Qt(c)}}let mo=new Map(s.toolFailureCounts);try{let i=e.runtimePorts.createStreamingToolExecutor({toolInvoker:r,hooks:k,sessionId:l,turnId:n,log:o,signal:H,maxConcurrentTools:e?.maxConcurrentTools});for(let c of ue)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),ce.push(c.callId),_.add(c.toolName),C++;let u=c.ok&&Vt(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=ue.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 Wt(n,c);for(let p of Xt(n,c))yield p;for(let p of Yt({turnId:n,result:c,toolCalls:B}))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>=pe&&(mo.get(i)??0)<pe&&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(P=fe(P,{replayMessages:f,completedToolCallIds:[...P.completedToolCallIds,...ce],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&B.length>0&&(Ce=!0),e.generateToolUseSummary&&B.length>0){let i=B.map(c=>({name:c.function.name,arguments:c.function.arguments}));re=e.generateToolUseSummary(i).catch(()=>null)}let go=B.length>0&&B.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: ")}),ee=s.consecutiveFailedRounds;if(go){if(ee+=1,ee>=bt){let i=s.finalText||Y(f,o);o.info(`early exit: ${ee} consecutive failed rounds, returning ${s.finalText?"partial":"fallback"} response`),yield{type:"end",turnId:n,content:i,usage:s.totalUsage,model:s.currentModel};return}}else ee=0;let fo=3,ut=[...s.fileReadCounts.entries()].filter(([,i])=>i>=fo);if(ut.length>0){let i=ut.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 xe=J+1;if(R>0&&xe>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,...w.length>0&&{thinkingBlocks:[...w]}};s={...s,messages:[...f,p,{role:"user",content:u}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let i=s.finalText||Y(f,o);yield{type:"end",turnId:n,content:i,usage:s.totalUsage,model:s.currentModel};return}if(xe>j){if(o.info(`tool loop budget exhausted (${j} rounds), returning`),C>0){let c={ok:!0,toolCallCount:C,distinctToolCount:_.size,multiStep:C>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},u=ge(c,{tools:[..._],projectRoot:e.projectRoot});u&&(yield{type:"skill_instruction",turnId:n,instruction:u})}let i=s.finalText||Y(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:xe,transition:{reason:"next_turn"},guardState:x,reactiveCompactState:$,toolLoopState:P,consecutiveFailedRounds:ee,finalText:s.finalText,totalUsage:s.totalUsage,collapseStore:ke,currentModel:s.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:s.stopHookActive,lastResponseId:s.lastResponseId,snipRemovedIds:s.snipRemovedIds,contentReplacementState:s.contentReplacementState,budgetContinuationCount:s.budgetContinuationCount,lastBudgetDeltaTokens:s.lastBudgetDeltaTokens,lastBudgetGlobalTokens:s.lastBudgetGlobalTokens,identicalCallCounts:ae,toolFailureCounts:s.toolFailureCounts,fileReadCounts:s.fileReadCounts}}}var In=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function ao(e){let t=wn(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: ${io(o.l1Amount)}; L2 long-term says: ${io(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let n=On(o);r.push(`- [${n}] ${o.text}`)}return r.join(`
7
+ `)}function wn(e){let t=e.filter(n=>n.source==="l1-project-md").flatMap(n=>so(n.text)),r=e.filter(n=>n.source==="l2-long-term").flatMap(n=>so(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 Nn(o)}function so(e){let t=[];for(let r of e.split(/\r?\n/)){let o=r.trim();if(o)for(let n of In){if(n==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let l=new RegExp(`${Dn(n)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let d of o.matchAll(l)){let a=Pn(d[1]);a!==null&&t.push({entity:Ln(o,n),predicate:n,amount:a,text:o})}}}return t}function Ln(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 Pn(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 On(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 io(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function Nn(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 Dn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var co=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},I(this.hooks,"turn.submitted",{...m,prompt:n[n.length-1]?.content??void 0},this.log);let T=$e(n),h=[];if(d&&h.push({role:"system",content:d}),h.push(...T),this.hooks){let S=T.filter(L=>L.role==="user").pop(),R=typeof S?.content=="string"?S.content.slice(0,500):void 0;if(R)try{let L=this.runtimePorts.detectRecallCategories(R),b=await this.hooks.invoke("memory.before_recall",{sessionId:t.sessionId,turnId:o,query:R,preferredCategories:L.preferred.length>0?L.preferred:void 0,deprioritizedCategories:L.deprioritized.length>0?L.deprioritized:void 0}),D=b?.context?.recalledMemories;if(D&&D.length>0){let F=0,_=[];for(let C of D){let A=(C.text?.length??0)*2;if(F+A>8192)break;_.push(C),F+=A}if(_.length>0){let C=ao(_);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}`})}}I(this.hooks,"memory.after_recall",{sessionId:t.sessionId,turnId:o,blockCount:b?.context?.recalledMemories?.length??0},this.log)}catch{}}let k=a?.model??"",H=Math.min(a?.maxRounds??this.maxRounds,100);try{let S=async D=>{let j=this.runtimePorts.resolveModelForPurpose("smallModel");if(!j)return null;try{let F=D.map(A=>`${A.name}(${A.arguments.slice(0,200)})`).join(", "),_=this.transport.stream({model:j,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:F}],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 L={turnId:o,sessionId:t.sessionId,messages:h,tools:l,model:k,apiKey:a?.apiKey??this.apiKey,temperature:a?.temperature,maxRounds:H,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:S,runtimePorts:this.runtimePorts.toolLoop,signal:r},b;for await(let D of ro(L,this.transport,this.toolInvoker,this.log))b=D,yield D;b?.type==="end"?I(this.hooks,"turn.completed",{...m},this.log):b?.type==="error"&&I(this.hooks,"turn.failed",{...m,code:b.code,error:b.error},this.log)}catch(S){if(r?.aborted)I(this.hooks,"turn.failed",{...m,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let R=S instanceof Error?S.message:String(S),L=typeof S?.status=="number"?S.status:void 0,b=W(L,R);this.log.error(`turn ${o} error [${b}, retryable=${ve(b)}]: ${R}`),I(this.hooks,"turn.failed",{...m,code:b,error:R},this.log),yield{type:"error",turnId:o,error:R,code:b}}}}};export{co as Agent};