qlogicagent 2.13.10 → 2.14.1

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 (48) hide show
  1. package/dist/agent.js +10 -6
  2. package/dist/cli.js +362 -347
  3. package/dist/index.js +361 -346
  4. package/dist/orchestration.js +14 -14
  5. package/dist/protocol.js +1 -1
  6. package/dist/types/agent/agent.d.ts +1 -0
  7. package/dist/types/agent/tool-loop/completion-action-policy.d.ts +28 -1
  8. package/dist/types/agent/tool-loop/loop-helpers.d.ts +3 -1
  9. package/dist/types/agent/types.d.ts +7 -0
  10. package/dist/types/cli/acp-extended-handlers.d.ts +1 -0
  11. package/dist/types/cli/base-tool-bootstrap.d.ts +3 -0
  12. package/dist/types/cli/handlers/turn-handler.d.ts +8 -1
  13. package/dist/types/cli/product-coordinator.d.ts +2 -2
  14. package/dist/types/cli/session-query-service.d.ts +3 -0
  15. package/dist/types/cli/stdio-runtime-bootstrap.d.ts +1 -0
  16. package/dist/types/cli/stdio-runtime-services.d.ts +1 -0
  17. package/dist/types/cli/tool-bootstrap-community-registration.d.ts +6 -0
  18. package/dist/types/cli/tool-bootstrap-core-registration.d.ts +3 -0
  19. package/dist/types/cli/tool-bootstrap-media-registration.d.ts +2 -0
  20. package/dist/types/cli/tool-bootstrap.d.ts +3 -0
  21. package/dist/types/orchestration/agent-instance.d.ts +3 -2
  22. package/dist/types/orchestration/product-worktree.d.ts +2 -0
  23. package/dist/types/protocol/wire/agent-events.d.ts +2 -2
  24. package/dist/types/protocol/wire/gateway-rpc.d.ts +4 -2
  25. package/dist/types/runtime/community/activity-event-emitter.d.ts +7 -0
  26. package/dist/types/runtime/community/activity-event.d.ts +3 -1
  27. package/dist/types/runtime/community/community-consent-client.d.ts +14 -0
  28. package/dist/types/runtime/community/pet-activity-sink.d.ts +36 -0
  29. package/dist/types/runtime/config/tunable-defaults.d.ts +3 -0
  30. package/dist/types/runtime/execution/streaming-tool-executor.d.ts +3 -0
  31. package/dist/types/runtime/infra/agent-process.d.ts +16 -0
  32. package/dist/types/runtime/infra/codex-llmrouter-compat-proxy.d.ts +4 -0
  33. package/dist/types/runtime/infra/media-persistence.d.ts +17 -0
  34. package/dist/types/runtime/ports/agent-runtime-ports.d.ts +1 -0
  35. package/dist/types/runtime/ports/tool-contracts.d.ts +3 -0
  36. package/dist/types/runtime/prompt/fresh-workspace-evidence.d.ts +1 -0
  37. package/dist/types/runtime/session/session-deletion-guard.d.ts +4 -0
  38. package/dist/types/runtime/session/session-transcript-store.d.ts +1 -0
  39. package/dist/types/runtime/session/session-write-queue.d.ts +1 -0
  40. package/dist/types/skills/tools/community-seek-tool.d.ts +9 -0
  41. package/dist/types/skills/tools/file-tool-arguments.d.ts +5 -0
  42. package/dist/types/skills/tools/image-generate-tool.d.ts +24 -0
  43. package/dist/types/skills/tools/read-tool.d.ts +2 -0
  44. package/dist/types/skills/tools/shell/host-paths.d.ts +2 -0
  45. package/dist/types/skills/tools/task-tool.d.ts +2 -0
  46. package/dist/types/skills/tools/team-tool.d.ts +0 -4
  47. package/dist/vendor/hatch-pet/scripts/prepare_pet_run.py +8 -4
  48. package/package.json +2 -2
package/dist/agent.js CHANGED
@@ -1,8 +1,12 @@
1
- function _e(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function ue(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var Io=/\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]},wo=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Lo=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Po=512,Oo=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var No=new Set([500,502,503,504,521,522,523,524,529]),Do=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Bo=["upgrade your plan","upgrade plan","current plan","subscription"],Fo=["daily","weekly","monthly"],Uo=["try again","retry","temporary","cooldown"],jo=["usage limit","rate limit","organization usage"],$o=["organization","workspace"],Ho=["billing period","exceeded","reached","exhausted"],Go=/["']?(?: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,qo=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function K(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Ko(e){return K(e,q.format)}function pt(e){return K(e,q.rateLimit)}function zo(e){return K(e,q.timeout)}function Wo(e){return Io.test(e)}function Se(e){let t=e.toLowerCase();return t?e.length>Po?Lo.test(t):K(t,q.billing)?!0:wo.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function mt(e){return K(e,q.authPermanent)}function Xo(e){return K(e,q.auth)}function gt(e){return K(e,q.overloaded)}function G(e,t){return t.some(n=>e.includes(n))}function Yo(e){return G(e,Do)||G(e,Bo)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Vo(e){let t=G(e,Fo),n=e.includes("spend limit")||e.includes("spending limit"),o=G(e,$o);return G(e,Uo)&&G(e,jo)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||G(e,Ho))}function Jo(e){return e.trim().toLowerCase().replace(qo,"").trim()}function ft(e){let t=Jo(e);return!t||Yo(t)?"billing":pt(t)||Vo(t)?"rate_limit":"billing"}function Qo(e){return Go.test(e)?ft(e):null}function yt(e){let t=e.match(Oo);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Zo(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function en(e){let t=e.trim();if(!t)return!1;let n=yt(t);return n?No.has(n.code):!1}function Tt(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?ft(t):"billing":e===429?"rate_limit":e===401||e===403?t&&mt(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&gt(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&Se(t)?"billing":"format":null}function tn(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 on(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 ht(e){if(on(e))return"session_expired";if(tn(e))return"model_not_found";let t=Qo(e);return t||(Wo(e)?Se(e)?"billing":"rate_limit":pt(e)?"rate_limit":gt(e)?"overloaded":en(e)?yt(e.trim())?.code===529?"overloaded":"timeout":Zo(e)?"timeout":Ko(e)?"format":Se(e)?"billing":zo(e)?"timeout":mt(e)?"auth_permanent":Xo(e)?"auth":null)}var nn={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"},rn=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function W(e,t){let n=Tt(e,t)??(t?ht(t):null);return n?nn[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Me(e){return rn.has(e)}function Ct(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var sn=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,n=Ct){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=t.length-this.preserveRecentCount,r=0,i=0;return{messages:t.map((s,d)=>{if(d>=o||s.role!=="tool"||typeof s.content!="string"||!s.name||!sn.has(s.name)||s.content.length<=200)return s;let g=this.estimateTokens(s);return i+=g,r++,{...s,content:`[result cleared \u2014 ${s.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function Ae(e,t,n=Ct){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let s of e){let d=s.tool_call_id??"";if(d&&t.has(d)){o+=n(s),r++,t.delete(d);continue}i.push(s)}let c=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:c}}function ve(){return{stages:[]}}function Ee(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=kt(e,t),c=an(i,t,o);if(c.length===0)return{messages:i,stagedCount:0};for(let s of c)t.stages.push(s);return i=kt(e,t),{messages:i,stagedCount:c.length}}function Ie(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:Rt(e,t),committed:n}}function kt(e,t){return t.stages.filter(o=>o.committed).length===0?e:Rt(e,t)}function Rt(e,t){let n=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),o=[...e];for(let r of n){let[i,c]=r.range;if(i>=o.length)continue;let s=Math.min(c,o.length),d={role:"system",content:r.summary};o.splice(i,s-i,d)}return o}function an(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(d=>`${d.range[0]}-${d.range[1]}`)),c=-1,s=0;for(let d=0;d<o;d++){let g=e[d];if(g.role==="tool"||g.role==="assistant"&&typeof g.content=="string"&&g.content==="")c<0&&(c=d),s++;else{if(s>=3){let p=`${c}-${c+s}`;i.has(p)||r.push({id:`collapse_${c}_${c+s}`,range:[c,c+s],summary:`[${s} tool results collapsed]`,committed:!1})}c=-1,s=0}}if(s>=3){let d=`${c}-${c+s}`;i.has(d)||r.push({id:`collapse_${c}_${c+s}`,range:[c,c+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}import{existsSync as Le,readFileSync as $t,writeFileSync as ln,readdirSync as Ht,mkdirSync as cn}from"node:fs";import{join as Pe,dirname as un}from"node:path";var bt=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),xt=3,_t=2,de=2,St=128e3,Mt=13e3,At=16384,vt=65536,Et=3,It=65536,we=500,wt=3;var Lt=3e4,Pt=3,X=2;var Ot=20;var Nt=3,Dt=2,Bt=300*1e3,Ft=3,Ut=720*60*60*1e3;var pr=300*1e3;var mr=3600*1e3;var gr=50*1024,fr=500*1024,yr=500*1024*1024,Tr=50*1024*1024;var hr=60*1024;var Gt=0;var dn="skill-patterns.json";function qt(e){return Pe(e,".qlogicagent",dn)}function pn(e){let t=qt(e);try{return JSON.parse($t(t,"utf8"))}catch{return{version:1,patterns:{}}}}function jt(e,t){let n=qt(e);cn(un(n),{recursive:!0}),ln(n,JSON.stringify(t,null,2),"utf8")}function mn(e){let t=Date.now()-Ut;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function Kt(e,t){if(t.length===0)return!1;let n=pe(t),o=pn(e);mn(o);let r=new Date().toISOString(),i=o.patterns[n];if(i||(i={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=i),i.promoted)return jt(e,o),!1;i.count++,i.lastSeen=r;let c=i.count>=Ft;return c&&(i.promoted=!0),jt(e,o),c}function pe(e){return[...e].sort().join("+")}function gn(e,t){if(!Le(t))return null;let n=pe(e);try{let o=Ht(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let i=Pe(t,r.name,"SKILL.md");try{let s=$t(i,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(s){let d=s[1].split(`
2
- `).map(g=>g.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(pe(d)===n)return r.name}}catch{}}}catch{}return null}function fn(e){if(!Le(e))return 0;try{return Ht(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&Le(Pe(e,t.name,"SKILL.md"))).length}catch{return 0}}function yn(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<Nt||e.distinctToolCount<Dt||Date.now()-Gt<Bt||t?.projectSkillsDir&&(fn(t.projectSkillsDir)>=Ot||t.tools.length>0&&gn(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Kt(t.projectRoot,t.tools))}function Tn(e){return e.existingSkillName?e.feedback==="negative":!1}function Oe(e,t){return Tn(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:yn(e,t)?(Gt=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 hn(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Cn(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function kn(e){if(!e.eligibility?.length)return[...e.tools];let t=Cn(e.eligibility);return e.tools.filter(n=>{let o=zt(n);if(!o)return!1;let r=t.get(o);return!r||hn(r.status)})}function Rn(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function Ne(e){let t=Rn({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=kn({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,c=typeof i?.name=="string"?i.name.trim():"";if(!c)throw new Error("tool_choice.function.name is required");let s=r.filter(d=>zt(d)===c);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${c}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:c}},extraSystemPrompt:`You must call the ${c} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var bn=["stop","aborted","timeout","cancelled","interrupted","error"],xn=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Wt(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function _n(e,t){return{...e,content:[...Wt(e.content),...Wt(t.content)]}}function Sn(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 Mn(e){return new Set((e??bn).map(t=>t.trim().toLowerCase()))}function An(e,t){return e?Mn(t).has(e.trim().toLowerCase()):!1}function De(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(s=>{if(s.role==="assistant"&&Array.isArray(s.tool_calls)){let d=s.tool_calls.filter(g=>Sn(g));return{...s,...d.length>0?{tool_calls:d}:{tool_calls:void 0}}}return{...s}}),n=new Set;for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let d of s.tool_calls)typeof d.id=="string"&&d.id&&n.add(d.id);let o=t.filter(s=>s.role!=="tool"?!0:!!(s.tool_call_id&&n.has(s.tool_call_id))),r=new Set;for(let s of o)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&r.add(s.tool_call_id);let i=[];for(let s of o){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let d=s.tool_calls.filter(g=>typeof g.id=="string"&&r.has(g.id));if(d.length===0){let{tool_calls:g,...T}=s;T.content!=null&&T.content!==""&&i.push(T);continue}if(d.length<s.tool_calls.length){i.push({...s,tool_calls:d});continue}}i.push(s)}let c=[];for(let s of i){let d=c.length>0?c[c.length-1]:void 0;if(s.role==="user"&&d?.role==="user"){c[c.length-1]=_n(d,s);continue}c.push(s)}return c}function Be(e,t){return An(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of xn)delete o[r];return o}):[...e]}function Fe(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&o.add(i.tool_call_id);let r=[];for(let i of e)if(r.push({...i}),!(i.role!=="assistant"||!Array.isArray(i.tool_calls)||i.tool_calls.length===0))for(let c of i.tool_calls)typeof c.id!="string"||!c.id||o.has(c.id)||(o.add(c.id),r.push({role:"tool",tool_call_id:c.id,content:n}));return r}function Ue(e,t){let n=De(e),o=Be(n,t);return Fe(o,t)}function vn(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function En(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function In(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 me(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 ge(e){let t=[],n=De(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=Be(n,e.options);o.some((i,c)=>i!==n[c])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=Fe(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:In({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:vn(r),completedToolCallIds:En(r)}),recoveryActions:t}}var wn=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function $e(e){return e?wn.has(e):!0}function He(e){return e===429||e===529}function fe(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var Ir={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function ye(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var oe=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function Ge(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function qe(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function Ke(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function ze(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function We(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Pn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Xe(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Y(e,t=Pn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function Ye(e,t){let n=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(n.id=t.id),t.name&&(n.name=t.name),n.arguments+=t.arguments??"",e.set(t.index,n)}function M(e,t,n,o){e?.invoke(t,n).catch(r=>{let i=r instanceof Error?r.message:String(r);o.warn(`[hook:${t}] handler failed: ${i}`)})}function Xt(e,t){let n=typeof t.message?.content=="string"?t.message.content:"",o=n?n.slice(0,2e3):void 0,r=t.details,i=typeof r?.stdout=="string"?r.stdout.slice(0,8e3):void 0,c=typeof r?.stderr=="string"?r.stderr.slice(0,4e3):void 0,s=typeof r?.exitCode=="number"?r.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:s,stdout:i,stderr:c,details:r}}function Yt(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=On(n);return o?(Array.isArray(n.mediaUrls)?n.mediaUrls.filter(i=>typeof i=="string"&&i.trim().length>0):[]).map(i=>({type:"media_result",turnId:e,mediaType:o,url:i,model:typeof n.model=="string"?n.model:void 0,provider:typeof n.provider=="string"?n.provider:void 0,durationSeconds:typeof n.durationMs=="number"?n.durationMs/1e3:void 0,taskId:typeof n.taskId=="string"?n.taskId:void 0})):[]}function On(e){let t=typeof e.type=="string"?e.type:"";if(!t)return null;if(t==="three_d_generate")return"3d";let n=t.split("_")[0];return n==="image"||n==="tts"||n==="video"||n==="music"?n:null}var Nn=new Set(["write","edit","patch"]);function Vt(e){let{turnId:t,result:n,toolCalls:o}=e;if(!n.ok)return[];let r=o.find(s=>s.id===n.callId);if(!r)return[];let i=[],c=Dn(r.function.arguments);if(!c)return i;if(n.toolName==="plan_mode"&&c.action==="exit"&&typeof c.plan=="string"&&c.plan.length>0&&i.push({type:"plan_update",turnId:t,slug:"approved-plan",content:c.plan}),Nn.has(n.toolName)){let s=Bn(c);s&&i.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:Fn(s),title:s.split(/[\\/]/).pop()||s,filePath:s,language:Un(s)})}return i}function Dn(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 Fn(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 Un(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 $n=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,Hn=new Set(["search","web_search","grep","glob","find","list","read","exec"]);function Jt(e){if(!Hn.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&$n.test(t)}function Ve(e,t){for(let n=e.length-1;n>=0;n--){let o=e[n];if(!o||o.role!=="tool")continue;let r=typeof o.content=="string"?o.content:"";if(r.startsWith("Error: "))return r.slice(7).trim()}}function Qt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.round(e),100):bt}function Zt(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function V(e,t){let n=[];for(let o=e.length-1;o>=0;o--){let r=e[o];if(r.role==="tool"&&typeof r.content=="string")n.unshift(r.content.slice(0,500));else if(r.role==="assistant"){if(typeof r.content=="string"&&r.content.trim())return t.info("synthesizeFallbackContent: found assistant text, using it"),r.content;break}else break}return n.length>0?(t.info(`synthesizeFallbackContent: synthesized from ${n.length} tool result(s)`),n.join(`
1
+ function Ge(e,t,o,n){return{role:"assistant",content:t||null,tool_calls:e,...o&&o.length>0?{thinkingBlocks:o}:{},...n?{reasoning_content:n}:{}}}function W(e,t){let o=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:o,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var _n=/\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]},Mn=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,An=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,vn=512,Sn=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var En=new Set([500,502,503,504,521,522,523,524,529]),wn=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],In=["upgrade your plan","upgrade plan","current plan","subscription"],Pn=["daily","weekly","monthly"],Ln=["try again","retry","temporary","cooldown"],On=["usage limit","rate limit","organization usage"],Fn=["organization","workspace"],Nn=["billing period","exceeded","reached","exhausted"],Dn=/["']?(?: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,Bn=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function J(e,t){if(!e)return!1;let o=e.toLowerCase();return t.some(n=>n instanceof RegExp?n.test(o):o.includes(n))}function $n(e){return J(e,Z.format)}function Gt(e){return J(e,Z.rateLimit)}function Un(e){return J(e,Z.timeout)}function jn(e){return _n.test(e)}function Ke(e){let t=e.toLowerCase();return t?e.length>vn?An.test(t):J(t,Z.billing)?!0:Mn.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Kt(e){return J(e,Z.authPermanent)}function qn(e){return J(e,Z.auth)}function Wt(e){return J(e,Z.overloaded)}function V(e,t){return t.some(o=>e.includes(o))}function zn(e){return V(e,wn)||V(e,In)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Hn(e){let t=V(e,Pn),o=e.includes("spend limit")||e.includes("spending limit"),n=V(e,Fn);return V(e,Ln)&&V(e,On)||t&&(e.includes("usage limit")||o)||t&&e.includes("limit")&&e.includes("reset")||n&&e.includes("limit")&&(o||V(e,Nn))}function Gn(e){return e.trim().toLowerCase().replace(Bn,"").trim()}function Xt(e){let t=Gn(e);return!t||zn(t)?"billing":Gt(t)||Hn(t)?"rate_limit":"billing"}function Kn(e){return Dn.test(e)?Xt(e):null}function Yt(e){let t=e.match(Sn);if(!t)return null;let o=Number(t[1]);return Number.isFinite(o)?{code:o,rest:(t[2]??"").trim()}:null}function Wn(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Xn(e){let t=e.trim();if(!t)return!1;let o=Yt(t);return o?En.has(o.code):!1}function Vt(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?Xt(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Kt(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&Wt(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&Ke(t)?"billing":"format":null}function Yn(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 Vn(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 Zt(e){if(Vn(e))return"session_expired";if(Yn(e))return"model_not_found";let t=Kn(e);return t||(jn(e)?Ke(e)?"billing":"rate_limit":Gt(e)?"rate_limit":Wt(e)?"overloaded":Xn(e)?Yt(e.trim())?.code===529?"overloaded":"timeout":Wn(e)?"timeout":$n(e)?"format":Ke(e)?"billing":Un(e)?"timeout":Kt(e)?"auth_permanent":qn(e)?"auth":null)}var Zn={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"},Jn=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ne(e,t){let o=Vt(e,t)??(t?Zt(t):null);return o?Zn[o]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function We(e){return Jn.has(e)}function Jt(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var Qn=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"]),me=class{constructor(t=20,o=Jt){this.preserveRecentCount=t;this.estimateTokens=o}preserveRecentCount;estimateTokens;compress(t,o){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let n=t.length-this.preserveRecentCount,r=0,s=0;return{messages:t.map((a,d)=>{if(d>=n||a.role!=="tool"||typeof a.content!="string"||!a.name||!Qn.has(a.name)||a.content.length<=200)return a;let p=this.estimateTokens(a);return s+=p,r++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function Xe(e,t,o=Jt){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let n=0,r=0,s=[];for(let a of e){let d=a.tool_call_id??"";if(d&&t.has(d)){n+=o(a),r++,t.delete(d);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:n,removedCount:r,boundaryMessage:i}}function Ye(){return{stages:[]}}function Ve(e,t,o){let n=o?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=n)return{messages:e,stagedCount:0};let s=Qt(e,t),i=er(s,t,n);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=Qt(e,t),{messages:s,stagedCount:i.length}}function Ze(e,t){let o=0;for(let n of t.stages)n.committed||(n.committed=!0,o++);return o===0?{messages:e,committed:0}:{messages:eo(e,t),committed:o}}function Qt(e,t){return t.stages.filter(n=>n.committed).length===0?e:eo(e,t)}function eo(e,t){let o=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),n=[...e];for(let r of o){let[s,i]=r.range;if(s>=n.length)continue;let a=Math.min(i,n.length),d={role:"system",content:r.summary};n.splice(s,a-s,d)}return n}function er(e,t,o){let n=Math.max(0,e.length-Math.floor(o/2)),r=[],s=new Set(t.stages.map(d=>`${d.range[0]}-${d.range[1]}`)),i=-1,a=0;for(let d=0;d<n;d++){let p=e[d];if(p.role==="tool"||p.role==="assistant"&&typeof p.content=="string"&&p.content==="")i<0&&(i=d),a++;else{if(a>=3){let m=`${i}-${i+a}`;s.has(m)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let d=`${i}-${i+a}`;s.has(d)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{existsSync as et,readFileSync as Ro,writeFileSync as tr,readdirSync as bo,mkdirSync as or}from"node:fs";import{join as tt,dirname as nr}from"node:path";var Je=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),to=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),oo=3,no=2,be=2,ro=128e3,so=13e3,io=16384,ao=65536,lo=3,co=65536,Qe=500,uo=3;var po=3e4,mo=3,re=2;var fo=20;var go=3,yo=2,ho=300*1e3,To=3,Co=720*60*60*1e3;var Ps=300*1e3;var Ls=3600*1e3;var Os=50*1024,Fs=500*1024,Ns=500*1024*1024,Ds=50*1024*1024;var Bs=60*1024;var xo=0;var rr="skill-patterns.json";function _o(e){return tt(e,".qlogicagent",rr)}function sr(e){let t=_o(e);try{return JSON.parse(Ro(t,"utf8"))}catch{return{version:1,patterns:{}}}}function ko(e,t){let o=_o(e);or(nr(o),{recursive:!0}),tr(o,JSON.stringify(t,null,2),"utf8")}function ir(e){let t=Date.now()-Co;for(let[o,n]of Object.entries(e.patterns))new Date(n.lastSeen).getTime()<t&&delete e.patterns[o]}function Mo(e,t){if(t.length===0)return!1;let o=xe(t),n=sr(e);ir(n);let r=new Date().toISOString(),s=n.patterns[o];if(s||(s={signature:o,count:0,firstSeen:r,lastSeen:r,promoted:!1},n.patterns[o]=s),s.promoted)return ko(e,n),!1;s.count++,s.lastSeen=r;let i=s.count>=To;return i&&(s.promoted=!0),ko(e,n),i}function xe(e){return[...e].sort().join("+")}function ar(e,t){if(!et(t))return null;let o=xe(e);try{let n=bo(t,{withFileTypes:!0});for(let r of n){if(!r.isDirectory())continue;let s=tt(t,r.name,"SKILL.md");try{let a=Ro(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let d=a[1].split(`
2
+ `).map(p=>p.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(xe(d)===o)return r.name}}catch{}}}catch{}return null}function lr(e){if(!et(e))return 0;try{return bo(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&et(tt(e,t.name,"SKILL.md"))).length}catch{return 0}}function cr(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<go||e.distinctToolCount<yo||Date.now()-xo<ho||t?.projectSkillsDir&&(lr(t.projectSkillsDir)>=fo||t.tools.length>0&&ar(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Mo(t.projectRoot,t.tools))}function ur(e){return e.existingSkillName?e.feedback==="negative":!1}function ot(e,t){return ur(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:cr(e,t)?(xo=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 Ao(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 dr(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function pr(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function mr(e){if(!e.eligibility?.length)return[...e.tools];let t=pr(e.eligibility);return e.tools.filter(o=>{let n=Ao(o);if(!n)return!1;let r=t.get(n);return!r||dr(r.status)})}function fr(e){let t=[],o=e.compatibility??{},n=e.toolChoice;if(e.thinkingEnabled&&o.requireAutoWhenThinking){let r=typeof n=="object"&&n&&!Array.isArray(n)?String(n.type??""):n;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),n="auto")}if(n==="required"&&o.allowRequiredToolChoice===!1){let r=o.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),n=r}if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&o.allowNamedToolChoice===!1){let r=o.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),n=r}return{normalizedToolChoice:n,warnings:t}}function nt(e){let t=fr({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),o=t.normalizedToolChoice,n=[...t.warnings],r=mr({tools:e.tools,eligibility:e.eligibility});if(!o||o==="auto")return{tools:r,normalizedToolChoice:o,warnings:n};if(o==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(o==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:n}}if(typeof o=="object"&&!Array.isArray(o)&&o.type==="function"){let s=o.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(d=>Ao(d)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:n}}return{tools:r,normalizedToolChoice:o,warnings:n}}var gr=["stop","aborted","timeout","cancelled","interrupted","error"],yr=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function vo(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function hr(e,t){return{...e,content:[...vo(e.content),...vo(t.content)]}}function Tr(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let o of e.tool_calls)typeof o.id=="string"&&o.id&&t.add(o.id);return t}function Cr(e){let t=new Set,o=[];for(let n=0;n<e.length;n+=1){if(t.has(n))continue;let r=e[n];if(!r)continue;o.push(r);let s=Tr(r);if(s.size!==0)for(let i=n+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(o.push(a),t.add(i))}}return o}function kr(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 Rr(e){return new Set((e??gr).map(t=>t.trim().toLowerCase()))}function br(e,t){return e?Rr(t).has(e.trim().toLowerCase()):!1}function rt(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(d=>{if(d.role==="assistant"&&Array.isArray(d.tool_calls)){let p=d.tool_calls.filter(f=>kr(f));return{...d,...p.length>0?{tool_calls:p}:{tool_calls:void 0}}}return{...d}}),o=new Set;for(let d of t)if(!(d.role!=="assistant"||!Array.isArray(d.tool_calls)))for(let p of d.tool_calls)typeof p.id=="string"&&p.id&&o.add(p.id);let n=t.filter(d=>d.role!=="tool"?!0:!!(d.tool_call_id&&o.has(d.tool_call_id))),r=new Set;for(let d of n)d.role==="tool"&&typeof d.tool_call_id=="string"&&d.tool_call_id&&r.add(d.tool_call_id);let s=[];for(let d of n){if(d.role==="assistant"&&Array.isArray(d.tool_calls)&&d.tool_calls.length>0){let p=d.tool_calls.filter(f=>typeof f.id=="string"&&r.has(f.id));if(p.length===0){let{tool_calls:f,...m}=d;m.content!=null&&m.content!==""&&s.push(m);continue}if(p.length<d.tool_calls.length){s.push({...d,tool_calls:p});continue}}s.push(d)}let i=Cr(s),a=[];for(let d of i){let p=a.length>0?a[a.length-1]:void 0;if(d.role==="user"&&p?.role==="user"){a[a.length-1]=hr(p,d);continue}a.push(d)}return a}function st(e,t){return br(t?.stopReason,t?.forcedStopReasons)?e.map(o=>{if(o.role!=="assistant")return{...o};let n={...o};for(let r of yr)delete n[r];return n}):[...e]}function it(e,t){let o=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",n=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&n.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||n.has(i.id)||(n.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:o}));return r}function at(e,t){let o=rt(e),n=st(o,t);return it(n,t)}function xr(e){let t=new Set,o=new Set;for(let n of e){if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let r of n.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&o.add(n.tool_call_id)}return[...t].filter(n=>!o.has(n))}function _r(e){let t=new Set;for(let o of e)o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&t.add(o.tool_call_id);return[...t]}function Mr(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function lt(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 _e(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Me(e){let t=[],o=rt(e.replayMessages);o.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let n=st(o,e.options);n.some((s,i)=>s!==o[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=it(n,e.options);return r.length>n.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Mr({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:xr(r),completedToolCallIds:_r(r)}),recoveryActions:t}}var Ar=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function ct(e){return e?Ar.has(e):!0}function ut(e){return e===429||e===529}function Ae(e,t=500,o=32e3){let n=Math.min(t*Math.pow(2,e-1),o);return n+Math.floor(Math.random()*n*.25)}var Vs={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function ve(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var fe=class extends Error{constructor(o,n){super(`Model fallback triggered: ${o} -> ${n}`);this.originalModel=o;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function dt(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function pt(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let o=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,n=o>0?e.promptTokens/o*100:100;return e.promptTokens>=o?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:n>=85?{level:"warning",usagePercent:n,remainingTokens:o-e.promptTokens}:{level:"ok"}}function mt(e,t,o){let n=e.message?.toLowerCase()??"",r=e.status??0;return r===413||n.includes("prompt_too_long")||n.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&o.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:n||"unknown_error"}}function ft(e,t,o){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let n=Math.min(e.currentMaxOutputTokens*2,o);return n<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:n}}function gt(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Sr={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function yt(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function se(e,t=Sr){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function ht(e,t){let o=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(o.id=t.id),t.name&&(o.name=t.name),o.arguments+=t.arguments??"",e.set(t.index,o)}function S(e,t,o,n){e?.invoke(t,o).catch(r=>{let s=r instanceof Error?r.message:String(r);n.warn(`[hook:${t}] handler failed: ${s}`)})}function So(e,t){let o=typeof t.message?.content=="string"?t.message.content:"",n=o?o.slice(0,2e3):void 0,r=t.details,s=typeof r?.stdout=="string"?r.stdout.slice(0,8e3):void 0,i=typeof r?.stderr=="string"?r.stderr.slice(0,4e3):void 0,a=typeof r?.exitCode=="number"?r.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:n,durationMs:t.durationMs,exitCode:a,stdout:s,stderr:i,details:r}}function Eo(e,t){if(!t.ok)return[];let o=t.details;if(!o)return[];let n=Er(o);return n?(Array.isArray(o.mediaUrls)?o.mediaUrls.filter(s=>typeof s=="string"&&s.trim().length>0):[]).map(s=>({type:"media_result",turnId:e,mediaType:n,url:s,model:typeof o.model=="string"?o.model:void 0,provider:typeof o.provider=="string"?o.provider:void 0,durationSeconds:typeof o.durationMs=="number"?o.durationMs/1e3:void 0,taskId:typeof o.taskId=="string"?o.taskId:void 0})):[]}function Er(e){let t=typeof e.type=="string"?e.type:"";if(!t)return null;if(t==="three_d_generate")return"3d";let o=t.split("_")[0];return o==="image"||o==="tts"||o==="video"||o==="music"?o:null}var wr=new Set(["write","edit","patch"]);function wo(e){let{turnId:t,result:o,toolCalls:n}=e;if(!o.ok)return[];let r=n.find(a=>a.id===o.callId);if(!r)return[];let s=[],i=Ir(r.function.arguments);if(!i)return s;if(o.toolName==="plan_mode"&&i.action==="exit"&&typeof i.plan=="string"&&i.plan.length>0&&s.push({type:"plan_update",turnId:t,slug:"approved-plan",content:i.plan}),wr.has(o.toolName)){let a=Pr(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${o.callId}`,artifactType:Lr(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:Or(a)})}return s}function Ir(e){try{return JSON.parse(e)}catch{return null}}function Pr(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 Lr(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 Or(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 Fr=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,Nr=new Set(["search","web_search","grep","glob","find","list","read","exec"]),Dr=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,Br=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])((?:[A-Za-z0-9._-]+[\\/])+[A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,$r=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,Ur=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i;function Po(e){if(!Nr.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&Fr.test(t)}function Tt(e,t){for(let o=e.length-1;o>=0;o--){let n=e[o];if(!n||n.role!=="tool")continue;let r=typeof n.content=="string"?n.content:"";if(r.startsWith("Error: "))return r.slice(7).trim()}}function Lo(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let o=Ee(t);return o>=3?Math.min(Math.max(25,20+o*15),100):25}function Ee(e){if(!e)return 0;let t=new Set,o=new Set,n=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase();t.add(`path:${s}`);let i=s.split("/").pop();i&&o.add(i)};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content;for(let i of r.content.matchAll(Dr))n(i[0]);if(Ur.test(s)){for(let i of s.matchAll(Br)){let a=i[1]?.toLowerCase();if(!a)continue;t.add(`relative:${a.replace(/\\/g,"/")}`);let d=a.replace(/\\/g,"/").split("/").pop();d&&o.add(d)}for(let i of s.matchAll($r)){let a=i[1]?.toLowerCase();!a||o.has(a)||t.add(`name:${a}`)}}}return t.size}function Oo(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let o=Ee(t);return o>=3?Math.min(Math.max(Je,20+o*15),100):Je}function Fo(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function Ct(e,t){let o=[];for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="tool"&&typeof r.content=="string")o.unshift(r.content.slice(0,500));else if(r.role==="assistant"){if(typeof r.content=="string"&&r.content.trim())return t.info("synthesizeFallbackContent: found assistant text, using it"),r.content;break}else break}return o.length>0?(t.info(`synthesizeFallbackContent: synthesized from ${o.length} tool result(s)`),o.join(`
3
3
 
4
- `)):""}function eo(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(i=>typeof i=="string"&&i.trim().length>0);if(typeof o=="string")return o.trim().slice(0,240);let r=Object.keys(t);return r.length>0?r.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 to(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 oo(e){let t=e.headers;if(!t)return null;let n=t["retry-after"]??t["Retry-After"];if(!n)return null;let o=parseInt(n,10);return!isNaN(o)&&o>0?o*1e3:null}function no(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 n=parseInt(t[1],10),o=parseInt(t[3],10);if(isNaN(n)||isNaN(o))return null;let r=o-n-1e3;return r>=3e3?r:null}async function*ro(e,t,n,o,r,i,c,s){let d=[],g,T=!1;s.debug(`single LLM round, messages: ${n.length}`);for await(let p of c.stream({model:t,messages:n,temperature:r},o,i))switch(p.type){case"delta":d.push(p.text),yield{type:"delta",turnId:e,text:p.text};break;case"usage":g={inputTokens:p.promptTokens,outputTokens:p.completionTokens,reasoningTokens:p.reasoningTokens,cacheRead:p.cacheReadTokens,cacheWrite:p.cacheCreationTokens};break;case"done":T=!0;break}if(!T){yield{type:"error",turnId:e,error:"LLM stream closed before a terminal event; the response was likely truncated upstream.",code:"RETRYABLE_TRANSIENT",usage:g??{inputTokens:0,outputTokens:0}};return}yield{type:"end",turnId:e,content:d.join(""),usage:g??{inputTokens:0,outputTokens:0},model:t}}async function*so(e){let{messages:t,contentReplacementState:n,snipRemovedIds:o,collapseStore:r,guardState:i,guardConfig:c,runtimePorts:s,hooks:d,hookCtx:g,sessionId:T,currentModel:p,log:b,recovery:h,onAutocompact:x}=e,C;{let m=await s.enforceToolResultBudget(t,n,T);C=m.messages,m.newlyReplacedCount>0&&(b.info(`tool-result-budget: persisted ${m.newlyReplacedCount} oversized tool results`),yield h("tool_result_budget",`${m.newlyReplacedCount} persisted`))}{let m=Ae(C,o);C=m.messages,m.removedCount>0&&(b.info(`snip: removed ${m.removedCount} messages, freed ~${m.tokensFreed} tokens`),yield h("snip",`${m.removedCount} messages`))}{let _=new te().compress(C,0);_.droppedCount>0&&(C=_.messages,b.info(`microcompact: cleared ${_.droppedCount} old tool results`))}if(C=Ee(C,r).messages,i.promptTokens>0){let m=c.contextWindowTokens*.75,_=s.getActiveContextCompressionEngine(),S;_?S=await _.compressAsync(C,m,{model:p,sessionId:T}):S=s.compressMessages(C,{budget:m,model:p}),S.droppedCount>0&&(C=S.messages,b.info(`autocompact: ${S.strategy}, dropped ${S.droppedCount}`),yield h("autocompact",`${S.strategy}: ${S.droppedCount} dropped`),x(),M(d,"context.after_compact",{...g,removedCount:S.droppedCount},b))}return C=Zt(C),C}async function*io(e,t){let{state:n,guardState:o,fallbackModel:r,signal:i,querySource:c,turnId:s,log:d,emitRecovery:g}=t;if(e instanceof oe&&r)return d.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield g("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let T=e instanceof Error?e.message:String(e),p=typeof e?.status=="number"?e.status:void 0;if(!p&&T&&(T.includes("ECONNRESET")||T.includes("EPIPE"))){let h=(n.consecutiveApiRetries??0)+1;return h>X?(d.info(`stale connection retry limit reached (${X}), aborting`),yield{type:"error",turnId:s,error:T,code:"RETRIES_EXHAUSTED",usage:n.totalUsage},{kind:"return"}):(d.info(`stale connection (${T.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield g("stale_connection_retry",T.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:h,transition:void 0}})}let b=no({status:p,message:T});if(b!==null)return d.info(`max_tokens overflow: adjusting to ${b}`),o.currentMaxOutputTokens=b,{kind:"continue",patch:{maxOutputTokensOverride:b,transition:void 0}};if(He(p)){n.consecutive529Errors++;let h=2,x=r&&n.currentModel!==r;if(n.consecutive529Errors>h&&!x&&!ye())return d.info(`transient ${p} \u8133 ${n.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:s,error:`API unavailable after ${n.consecutive529Errors} consecutive ${p} errors`,code:"API_ERROR",usage:n.totalUsage},{kind:"return"};if(n.consecutive529Errors>=Pt&&r&&n.currentModel!==r)return d.info(`529 \u8133 ${n.consecutive529Errors}: triggering fallback to ${r}`),yield g("model_fallback",`529 \u8133 ${n.consecutive529Errors}`),{kind:"continue",patch:{currentModel:r,consecutive529Errors:0,transition:void 0}};if(ye()){let C=fe(n.consecutive529Errors);d.info(`persistent retry: waiting ${C}ms (attempt ${n.consecutive529Errors})`);let m=C;for(;m>0;){if(i?.aborted)return yield{type:"error",turnId:s,error:"Aborted during retry wait",code:"ABORTED",usage:n.totalUsage},{kind:"return"};yield{type:"heartbeat",turnId:s,message:`Retrying in ${Math.ceil(m/1e3)}s (${p})`};let _=Math.min(m,Lt);await new Promise(S=>setTimeout(S,_)),m-=_}return{kind:"continue",patch:{transition:void 0}}}if($e(c)){let m=oo({status:p,message:T})??fe(n.consecutive529Errors);return d.info(`transient ${p}: retry in ${m}ms`),yield g("retry",`${p} retry in ${m}ms`),await new Promise(_=>setTimeout(_,m)),{kind:"continue",patch:{transition:void 0}}}d.info(`background source ${c}: not retrying ${p}`)}return{kind:"streamError",streamError:{status:p,message:T}}}var Gn=/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;function ao(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function qn(e){let t=e,n=t.is_error===!0||typeof t.content=="string"&&t.content.startsWith("Error:");return t.role==="tool"&&typeof t.content=="string"&&!n}function Kn(e){let t=[...e].reverse().find(n=>n.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
4
+ `)):""}function No(e){try{let t=JSON.parse(e),n=[t.description,t.command,t.query,t.url,t.path,t.file_path,t.filePath,t.pattern,t.model].find(s=>typeof s=="string"&&s.trim().length>0);if(typeof n=="string")return n.trim().slice(0,240);let r=Object.keys(t);return r.length>0?r.slice(0,5).join(" / "):void 0}catch{return}}function kt(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 Do(e){return e==="length"||e==="max_tokens"}function Rt(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 Bo(e){let t=e.headers;if(!t)return null;let o=t["retry-after"]??t["Retry-After"];if(!o)return null;let n=parseInt(o,10);return!isNaN(n)&&n>0?n*1e3:null}function $o(e){if(e.status!==400)return null;let t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!t?.[1]||!t?.[3])return null;let o=parseInt(t[1],10),n=parseInt(t[3],10);if(isNaN(o)||isNaN(n))return null;let r=n-o-1e3;return r>=3e3?r:null}async function*Uo(e){let{messages:t,contentReplacementState:o,snipRemovedIds:n,collapseStore:r,guardConfig:s,runtimePorts:i,hooks:a,hookCtx:d,sessionId:p,currentModel:f,log:m,recovery:b,onAutocompact:T}=e,h;{let k=await i.enforceToolResultBudget(t,o,p);h=k.messages,k.newlyReplacedCount>0&&(m.info(`tool-result-budget: persisted ${k.newlyReplacedCount} oversized tool results`),yield b("tool_result_budget",`${k.newlyReplacedCount} persisted`))}{let k=Xe(h,n);h=k.messages,k.removedCount>0&&(m.info(`snip: removed ${k.removedCount} messages, freed ~${k.tokensFreed} tokens`),yield b("snip",`${k.removedCount} messages`))}{let _=new me().compress(h,0);_.droppedCount>0&&(h=_.messages,m.info(`microcompact: cleared ${_.droppedCount} old tool results`))}if(h=Ve(h,r).messages,s.contextWindowTokens>0){let k=s.contextWindowTokens*.75,_=i.getActiveContextCompressionEngine(),R;_?R=await _.compressAsync(h,k,{model:f,sessionId:p}):R=i.compressMessages(h,{budget:k,model:f}),R.droppedCount>0&&(h=R.messages,m.info(`autocompact: ${R.strategy}, dropped ${R.droppedCount}`),yield b("autocompact",`${R.strategy}: ${R.droppedCount} dropped`),T(),S(a,"context.after_compact",{...d,removedCount:R.droppedCount},m))}return h=Fo(h),h}async function*jo(e,t){let{state:o,guardState:n,fallbackModel:r,signal:s,querySource:i,turnId:a,log:d,emitRecovery:p}=t;if(e instanceof fe&&r)return d.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield p("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let f=e instanceof Error?e.message:String(e),m=typeof e?.status=="number"?e.status:void 0;if(!m&&f&&(f.includes("ECONNRESET")||f.includes("EPIPE"))){let T=(o.consecutiveApiRetries??0)+1;return T>re?(d.info(`stale connection retry limit reached (${re}), aborting`),yield{type:"error",turnId:a,error:f,code:"RETRIES_EXHAUSTED",usage:o.totalUsage},{kind:"return"}):(d.info(`stale connection (${f.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield p("stale_connection_retry",f.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:T,transition:void 0}})}let b=$o({status:m,message:f});if(b!==null)return d.info(`max_tokens overflow: adjusting to ${b}`),n.currentMaxOutputTokens=b,{kind:"continue",patch:{maxOutputTokensOverride:b,transition:void 0}};if(ut(m)){o.consecutive529Errors++;let T=2,h=r&&o.currentModel!==r;if(o.consecutive529Errors>T&&!h&&!ve())return d.info(`transient ${m} \u8133 ${o.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:a,error:`API unavailable after ${o.consecutive529Errors} consecutive ${m} errors`,code:"API_ERROR",usage:o.totalUsage},{kind:"return"};if(o.consecutive529Errors>=mo&&r&&o.currentModel!==r)return d.info(`529 \u8133 ${o.consecutive529Errors}: triggering fallback to ${r}`),yield p("model_fallback",`529 \u8133 ${o.consecutive529Errors}`),{kind:"continue",patch:{currentModel:r,consecutive529Errors:0,transition:void 0}};if(ve()){let k=Ae(o.consecutive529Errors);d.info(`persistent retry: waiting ${k}ms (attempt ${o.consecutive529Errors})`);let _=k;for(;_>0;){if(s?.aborted)return yield{type:"error",turnId:a,error:"Aborted during retry wait",code:"ABORTED",usage:o.totalUsage},{kind:"return"};yield{type:"heartbeat",turnId:a,message:`Retrying in ${Math.ceil(_/1e3)}s (${m})`};let R=Math.min(_,po);await new Promise(P=>setTimeout(P,R)),_-=R}return{kind:"continue",patch:{transition:void 0}}}if(ct(i)){let _=Bo({status:m,message:f})??Ae(o.consecutive529Errors);return d.info(`transient ${m}: retry in ${_}ms`),yield p("retry",`${m} retry in ${_}ms`),await new Promise(R=>setTimeout(R,_)),{kind:"continue",patch:{transition:void 0}}}d.info(`background source ${i}: not retrying ${m}`)}return{kind:"streamError",streamError:{status:m,message:f}}}import{readdirSync as Go,statSync as Ie}from"node:fs";var jr=/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,qr=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,qo=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,zr=/\b(?:in|into|under|to|at|output(?:\s+to)?|save(?:\s+to)?|saved?\s+under)\s+([A-Za-z]:[\\/][^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+)/gi,Hr=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,Gr=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*(?:[\\/][A-Za-z0-9][A-Za-z0-9._-]*)+\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},.;:\uFF0C\u3001\uFF1B\u3002])/gi,Kr=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*(?:[\\/][A-Za-z0-9][A-Za-z0-9._-]*)+)[\\/]?(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,Wr=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i,Xr=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i;function B(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase()}function Ko(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function zo(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function Ho(e,t,o){let n=Math.max(e.lastIndexOf(".",t),e.lastIndexOf(`
5
+ `,t),e.lastIndexOf(";",t),e.lastIndexOf("\u3002",t),e.lastIndexOf("\uFF1B",t))+1,r=e.slice(n,t).toLowerCase();if(/\b(?:do\s+not|don't|never)\s+(?:leave|create|write|include|keep|produce|add|generate)\b/i.test(r)||/\b(?:remove|delete|exclude)\b/i.test(r))return!0;let s=e.slice(Math.max(0,t-16),t+o.length);return new RegExp(`\\bno\\s+${Pe(o)}\\b`,"i").test(s)}function Le(e){let t=new Set,o=[],n=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B]+$/u,""),i=B(s);t.has(i)||(t.add(i),o.push(s))};for(let r of e)if(!(r.role!=="user"||typeof r.content!="string"))for(let s of r.content.matchAll(qr)){let i=s[0];n(i);let a=(s.index??0)+i.length,d=i.replace(/\\/g,"/"),p=d.lastIndexOf("/");if(p>=0){let f=d.slice(0,p+1);qo.lastIndex=a;let m;for(;(m=qo.exec(r.content))!==null;)n(`${f}${m[1]}`)}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content;if(!Wr.test(s))continue;let i=Array.from(s.matchAll(zr)).map(d=>Ko(d[1]??"")).filter(d=>d&&!zo(d));if(i.length===0)continue;let a=i[i.length-1];for(let d of s.matchAll(Hr)){let p=d[1];p&&(Ho(s,d.index??0,p)||n(`${a}/${p}`))}for(let d of s.matchAll(Gr)){let p=d[1];p&&(Ho(s,d.index??0,p)||n(`${a}/${p}`))}for(let d of s.matchAll(Kr)){let p=d[1];p&&(zo(p)||/(?:assets[\\/]generated|screenshots(?:[\\/]|$)|previews(?:[\\/]|$))/i.test(p)&&/\b(?:generated|bitmap|png|screenshots?|preview|previews|evidence|assets?|containing)\b/i.test(s)&&n(`${a}/${p}/*`))}Xr.test(s)&&n(`${a}/previews/*`)}return o}function Wo(e){if(e.role!=="tool")return!1;let t=typeof e.content=="string"?e.content:"";return e.is_error!==!0&&!t.startsWith("Error:")}function Xo(e){let t=new Set,o=new Map,n=[];for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let d=a,p=d.id,f=d.function;typeof p=="string"&&typeof f?.name=="string"&&o.set(p,f.name)}}for(let r of e){let s=r;if(Wo(s)){let i=s.tool_call_id;typeof i=="string"&&t.add(i),(typeof i=="string"?o.get(i):void 0)==="exec"&&typeof s.content=="string"&&n.push(s.content)}}for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let d=a,p=d.id;if(typeof p=="string"&&t.size>0&&!t.has(p))continue;let f=d.function;if(!(typeof f?.name!="string"||typeof f.arguments!="string"))try{let m=JSON.parse(f.arguments);if(f.name==="write"||f.name==="edit"){for(let b of["path","filePath","file_path"]){let T=m[b];typeof T=="string"&&n.push(T)}continue}if(f.name==="exec"){let b=m.command;typeof b=="string"&&n.push(b)}}catch{f.name==="exec"&&n.push(f.arguments)}}}return n.join(`
6
+ `).replace(/\\/g,"/").toLowerCase()}function xt(e){try{if(e.endsWith("/*")){let o=e.slice(0,-2);return Go(o,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return Ie(`${o}/${r.name}`).size>0}catch{return!1}})}let t=Ie(e);return t.isFile()&&t.size>0}catch{return!1}}function Yr(e,t){let o=B(t);if(!o.endsWith("/*"))return e.includes(o);let n=o.slice(0,-1);return e.includes(n)}function Vr(e){let t=Mt(e);return/\b(?:exactly|only)\b[^.\n]*(?:artifacts?|files?|outputs?|deliverables?)/i.test(t)||/(?:artifacts?|files?|outputs?|deliverables?)[^.\n]*\b(?:exactly|only)\b/i.test(t)}function Zr(e){let t=Ko(e),o=t.lastIndexOf("/");return o>=0?t.slice(0,o):""}function Jr(e){if(e.length===0)return"";let t=e.map(n=>Zr(n).split("/")),o=[];for(let n=0;n<t[0].length;n++){let r=t[0][n];if(t.every(s=>s[n]?.toLowerCase()===r.toLowerCase()))o.push(r);else break}return o.join("/")}function Qr(e,t){let o=B(e);return t.some(n=>{let r=B(n);return r.endsWith("/*")?o.startsWith(r.slice(0,-1)):o===r})}function es(e){let t=new Set,o=new Map;for(let n of e){let r=n,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,d=a.id,p=a.function;if(typeof d!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let f=Qo(p.arguments);if(!f)continue;let m=en(f);m&&o.set(d,m)}}for(let n of e){let r=n;if(!Wo(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...o.entries()].filter(([n])=>t.has(n)).map(([,n])=>n)}function ts(e){let t=[],o=n=>{let r;try{r=Go(n,{withFileTypes:!0})}catch{return}for(let s of r){let i=`${n}/${s.name}`;if(s.isDirectory()){o(i);continue}if(s.isFile())try{Ie(i).size>0&&t.push(i)}catch{}}};try{if(!Ie(e).isDirectory())return[]}catch{return[]}return o(e),t}function Yo(e,t){if(!Vr(e))return[];let o=Le(e),n=o.filter(i=>!B(i).endsWith("/*"));if(n.length<2)return[];let r=Jr(n);if(!r||r.split("/").length<3)return[];let s=B(r);return[...new Set([...es(t),...ts(r)])].filter(i=>B(i).startsWith(`${s}/`)&&!Qr(i,o)&&xt(i))}function _t(e,t){let o=Le(e);if(o.length===0)return[];let n=Xo(t);return o.filter(r=>!Yr(n,r))}function bt(e){return ge(e).fail}function os(e){return e.replace(/[.,;:]+$/u,"")}function we(e){if(!e)return!1;let t=os(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function ge(e){let t=r=>r.replace(/[.,;:]+$/u,""),o,n;for(let r of e)if(!(r.role!=="user"||typeof r.content!="string")){for(let s of r.content.matchAll(/\b(DONE|PASS)\s+([A-Za-z0-9_.:-]+)/gi))we(s[2])&&(o=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))we(s[1])&&(n=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))we(s[1])&&(o=`${t(s[1])} ${s[2].toUpperCase()}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+FAIL\b/gi))we(s[1])&&(n=`${t(s[1])} FAIL`)}return{done:o,fail:n}}function Vo(e){let t=n=>n.replace(/[.,;:]+$/u,""),o;for(let n of e){if(n.role!=="user"||typeof n.content!="string")continue;let r=n.content;for(let s of r.matchAll(/\bMarker\s*:\s*([A-Za-z0-9_.:-]+)/gi))o=t(s[1]);for(let s of r.matchAll(/\b(?:include|with|contains?)\s+marker\s+([A-Za-z0-9_.:-]+)/gi))o=t(s[1])}return o}function Mt(e){for(let t=e.length-1;t>=0;t--){let o=e[t];if(o.role==="user"&&typeof o.content=="string")return o.content}return""}function Pe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zo(e,t){let o=Mt(e);for(let n of[t.done,t.fail]){if(!n)continue;let s=new RegExp(`\\bfinal\\s+(?:answer|response|reply)\\s+exactly\\s*:?\\s*${Pe(n)}([^\\n]*)`,"i").exec(o);if(s){let p=(s[1]??"").trimStart();if(p===""||/^[.!?]/u.test(p))return n}let a=new RegExp(`\\b(?:reply|respond)\\s+exactly(?:\\s+with)?\\s*:?\\s*${Pe(n)}([^\\n]*)`,"i").exec(o);if(!a)continue;let d=(a[1]??"").trimStart();if(d===""||/^[.!?。!?]/u.test(d))return n}}function ns(e,t,o){let n=Mt(e),r=[t.done,t.fail,o].filter(s=>typeof s=="string"&&s.length>0);return[...new Set(r)].filter(s=>new RegExp(`\\bstarts?\\s+with\\s+${Pe(s)}\\b`,"i").test(n))}function te(e){let t=_t(e.inputMessages,e.messages).filter(n=>!xt(n));return t.length===0?void 0:`${bt(e.inputMessages)??"FAIL"} ${e.reason}. Missing required output file evidence: ${t.join(", ")}`}function Oe(e){let t=ge(e.inputMessages);if(!t.done){let n=Vo(e.inputMessages);return n?`FAIL ${n} ${e.reason}. The model did not produce the requested final marker ${n}.`:void 0}return`${t.fail??"FAIL"} ${e.reason}. The model did not produce the requested final marker ${t.done}.`}function Jo(e){let t=ge(e.inputMessages),o=Zo(e.inputMessages,t);if(!(!o||Le(e.inputMessages).length===0||_t(e.inputMessages,e.messages).filter(i=>!xt(i)).length>0||Yo(e.inputMessages,e.messages).length>0))return o}function Qo(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function en(e){for(let t of["path","filePath","file_path"]){let o=e[t];if(typeof o=="string"&&o.trim())return o}}function rs(e){for(let t of["content","newContent","replacement","text"]){let o=e[t];if(typeof o=="string")return o}return""}function tn(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let o=ge(e.inputMessages);if(!o.done)return;let n=Qo(e.toolCall.function.arguments);if(!n)return;let r=en(n),s=rs(n);if(!r||!s.includes(o.done))return;let i=Le(e.inputMessages);if(i.length<2)return;let a=B(r);if(!i.some(m=>B(m)===a))return;let p=Xo(e.messages),f=i.filter(m=>B(m)!==a).filter(m=>!p.includes(B(m)));if(f.length!==0)return`Premature completion artifact blocked: this write/edit attempted to store the requested DONE marker in ${r} before evidence existed for sibling required output files: ${f.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function Q(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function ss(e){let t=e,o=t.is_error===!0||typeof t.content=="string"&&t.content.startsWith("Error:");return t.role==="tool"&&typeof t.content=="string"&&!o}function is(e){let t=[...e].reverse().find(o=>o.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
5
7
 
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.`)}function lo(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function co(e){if(e.stopHookActive)return null;let t=e.inputMessages.find(i=>i.role==="user"),n=typeof t?.content=="string"?t.content:"",o=Gn.test(n),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit");if(o&&!r){e.log.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),e.totalToolCallCount>0&&Kn(e.messages);let i={role:"user",content:e.totalToolCallCount===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."};return lo("file_action_verification",e.messages,ao(e.finalText,e.thinkingBlocks),i)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(qn).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let c={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."};return lo("multi_file_skeleton_verification",e.messages,ao(e.finalText,e.thinkingBlocks),c)}return null}function zn(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function uo(e){if(!e.hooks)return null;let t=await e.hooks.invoke("stop",{sessionId:e.sessionId,reason:"completed"});if(t.action==="prevent")return e.log.info(`stop hook prevented continuation: ${t.reason??"no reason"}`),{action:"end",content:e.finalText};if(t.action==="abort"){let n=t.reason??"Stop hook requested continuation";e.log.info(`stop hook blocking: ${n}`);let o={role:"user",content:n};return{action:"continue",messages:[...e.messages,zn(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var Wn=5;function Xn(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function Yn(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function po(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=Wn)return null;let t=Xn(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=wt&&o<we&&e.lastBudgetDeltaTokens<we)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(n)}% (delta=${o})`),null;if(n>=90)return null;let i=e.budgetContinuationCount+1,c={role:"user",content:e.getBudgetContinuationMessage(n,t,e.tokenBudget)};return e.log.info(`token budget continuation #${i}: ${Math.round(n)}% used`),{messages:[...e.messages,Yn(e.finalText,e.thinkingBlocks),c],budgetContinuationCount:i,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${i})`,transition:{reason:"token_budget_continuation"}}}function Ze(e){if(e.totalToolCallCount<=0)return null;let t={ok:!0,toolCallCount:e.totalToolCallCount,distinctToolCount:e.distinctToolNames.size,multiStep:e.totalToolCallCount>=2,hasSubAgent:!1,feedback:null,existingSkillName:null};return Oe(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function mo(e,t){let n=[],o=[];for(let r of e){let i=t.get(r.function.name)??0;i>=de?o.push({call:r,failCount:i,error:`Tool "${r.function.name}" has failed ${i} times this turn with different arguments. The target likely does not exist. Stop trying variations and report the issue to the user.`}):n.push(r)}return{allowed:n,blocked:o}}function go(){return{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."}}function fo(e){if(e.ok&&!e.softEmpty)return;let t=e.toolFailureCounts.get(e.toolName)??0;e.toolFailureCounts.set(e.toolName,t+1)}function yo(e){let t=[];for(let[n,o]of e.toolFailureCounts)o>=de&&(e.snapshot.get(n)??0)<de&&t.push({role:"user",content:`Tool "${n}" has now failed/returned empty results ${o} times with different arguments. The target clearly does not exist. Do NOT call "${n}" again. Report the result to the user immediately.`});return t}async function*To(e,t,n,o){let{turnId:r,sessionId:i,messages:c,tools:s,model:d,apiKey:g,temperature:T=0,hooks:p,signal:b}=e,h={sessionId:i,turnId:r},x=e.maxTurns??0,C=e.querySource,m=e.runtimePorts.resolveToolEligibility(s,e.toolEligibilityContext),_=m.eligibleTools;for(let f of m.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:f.toolName,reason:"blocked-by-policy"};if(!_.length){yield*ro(r,d,c,g,T,b,t,o);return}let S=Qt(e.maxRounds),F={contextWindowTokens:e.contextWindowTokens??St,responseBufferTokens:Mt,maxOutputTokens:e.maxOutputTokens??At,abortSignal:b,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},U=new Set,N=0,E=_,ne,Te=!1,et=0,l={messages:[...c],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Ge(F),reactiveCompactState:Xe(),toolLoopState:ge({maxRounds:S,replayMessages:[...c]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:ve(),currentModel:d,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,recoveryTrace:new Map},tt=Math.max(x*5,200),ot=0,L=(f,$)=>(l.recoveryTrace.set(f,(l.recoveryTrace.get(f)??0)+1),{type:"recovery",turnId:r,action:f,detail:$}),z=f=>({type:"end",turnId:r,content:f,usage:l.totalUsage,model:l.currentModel,...l.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(l.recoveryTrace)}:{}});for(;;){if(ot++,ot>tt){o.info(`hard iteration cap reached (${tt}), forcing completion`);let a=l.finalText||V(l.messages,o);yield z(a);return}let{messages:f,maxOutputTokensRecoveryCount:$,maxOutputTokensOverride:nt,turnCount:J,guardState:A,reactiveCompactState:D,collapseStore:he}=l,{toolLoopState:I}=l;if(ne){try{let a=await ne;a&&(yield{type:"tool_use_summary",turnId:r,summary:a})}catch{}ne=void 0}if(e.refreshTools&&J>1){let a=e.refreshTools();a!==E&&(E=a,o.debug(`tools refreshed: ${a.length} tools`))}if(We(A,F)){o.info(`turn aborted by guard at turn ${J}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:l.totalUsage};return}let H=qe(A,F);if(H.level==="blocking"){H.reason==="prompt_too_long"&&Y(D)&&(D.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${H.reason}), reactive compact needed`),yield L("reactive_compact","token budget pre-check")),o.info(`token budget blocking (${H.reason}), ending tool loop`);break}H.level==="warning"&&o.info(`token budget warning: ${H.usagePercent}% used, ${H.remainingTokens} remaining`);let re=yield*so({messages:f,contentReplacementState:l.contentReplacementState,snipRemovedIds:l.snipRemovedIds,collapseStore:he,guardState:A,guardConfig:F,runtimePorts:e.runtimePorts,hooks:p,hookCtx:h,sessionId:i,currentModel:l.currentModel,log:o,recovery:L,onAutocompact:()=>{l.hasAttemptedReactiveCompact=!1}}),_o=e.toolChoice==="required"&&Te?"auto":e.toolChoice??"auto",se=Ne({tools:E,toolChoice:_o}),Q=ge({maxRounds:S,replayMessages:re,lastStopReason:I.lastStopReason,options:{stopReason:I.lastStopReason}}),rt=se.extraSystemPrompt?[{role:"system",content:se.extraSystemPrompt},...Q.state.replayMessages]:Q.state.replayMessages;I=Q.state,Q.recoveryActions.length>0&&o.debug(`tool loop recovery: ${Q.recoveryActions.map(a=>a.detail??a.kind).join("; ")}`),o.debug(`turn ${J}, messages: ${rt.length}`),M(p,"turn.before_inference",{...h,model:l.currentModel},o);let Ce=!1,ke=[],st=new Map,it="stop",w,k=null,ie=!1,at=!1,Z=[],B=[];try{for await(let a of t.stream({model:l.currentModel,messages:rt,tools:se.tools,toolChoice:se.normalizedToolChoice??"auto",temperature:T,maxTokens:(nt??A.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:l.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},g,b))switch(a.type){case"delta":ke.push(a.text);break;case"tool_call_delta":Ce=!0,Ye(st,a);break;case"reasoning_delta":Z.push(a.text);break;case"reasoning_block_complete":a.signature&&B.push({thinking:Z.join(""),signature:a.signature}),Z.length=0;break;case"usage":w={inputTokens:a.promptTokens,outputTokens:a.completionTokens,reasoningTokens:a.reasoningTokens,cacheRead:a.cacheReadTokens,cacheWrite:a.cacheCreationTokens};break;case"response_id":l.lastResponseId=a.id;break;case"annotations":yield{type:"annotations",turnId:r,annotations:a.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${a.toolType}: ${a.event}`};break;case"done":at=!0,it=a.finishReason;break}if(Ce||M(p,"turn.after_inference",{...h,model:l.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let a=l.currentModel;for(let u of e.postSamplingHooks)try{u({messages:[...re],model:a,sessionId:i})}catch{}}}catch(a){let u=yield*io(a,{state:l,guardState:A,fallbackModel:e.fallbackModel,signal:b,querySource:C,turnId:r,log:o,emitRecovery:L});if(u.kind==="return")return;if(u.kind==="continue"){l={...l,...u.patch};continue}k=u.streamError}if(!k&&!at){let a="LLM stream closed before a terminal event; the response was likely truncated upstream.";M(p,"stop.failure",{sessionId:i,reason:"RETRYABLE_TRANSIENT",error:a},o),yield{type:"error",turnId:r,error:a,code:"RETRYABLE_TRANSIENT",usage:l.totalUsage};return}if(k&&M(p,"turn.after_inference",{...h,model:l.currentModel,response:{error:k.message}},o),k)if(Je(k))ie=!0,o.info(`withheld prompt_too_long error (status=${k.status})`);else if(Qe(k))ie=!0,o.info(`withheld media_size error (status=${k.status})`);else{let a=Ke({status:k.status??500,message:k.message},A,F);if(a.action==="reactive_compact"&&Y(D)&&(D.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,yield L("reactive_compact",`API ${k.status??500}: ${k.message}`)),a.action==="retry"){let y=(l.consecutiveApiRetries??0)+1;if(y>X){o.info(`API retry limit reached (${X}), aborting`);let R=W(k.status,k.message);yield{type:"error",turnId:r,error:k.message,code:R,usage:l.totalUsage};return}yield L("retry",a.reason),l={...l,consecutiveApiRetries:y,transition:void 0};continue}let u=W(k.status,k.message);M(p,"stop.failure",{sessionId:i,reason:u,error:k.message},o),yield{type:"error",turnId:r,error:k.message,code:u,usage:l.totalUsage};return}w&&(l.totalUsage.inputTokens+=w.inputTokens,l.totalUsage.outputTokens+=w.outputTokens,w.reasoningTokens&&(l.totalUsage.reasoningTokens=(l.totalUsage.reasoningTokens??0)+w.reasoningTokens),w.cacheRead&&(l.totalUsage.cacheRead=(l.totalUsage.cacheRead??0)+w.cacheRead),w.cacheWrite&&(l.totalUsage.cacheWrite=(l.totalUsage.cacheWrite??0)+w.cacheWrite)),w?.inputTokens&&(A.promptTokens=w.inputTokens);let lt=ke.join(""),O=[...st.values()].map(a=>({id:a.id||`tc_${r}_${J}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:a.name,arguments:a.arguments}}));if(O.length===0&&!Ce){if(lt&&(l.finalText=lt),e.toolChoice==="required"&&!Te&&E.length>0&&et<2){et++;let v=E.map(j=>j.function.name).filter(Boolean).slice(0,8).join(", ");l={...l,messages:[...f,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${v}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(ie&&k&&Je(k)){if(l.transition?.reason!=="collapse_drain_retry"){let v=Ie(re,he);if(v.committed>0){o.info(`collapse drain: committed ${v.committed} stages`),yield L("collapse_drain",`${v.committed} stages committed`),l={...l,messages:v.messages,transition:{reason:"collapse_drain_retry",committed:v.committed}};continue}}if(Y(D)){D.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield L("reactive_compact","withheld prompt_too_long"),l={...l,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),M(p,"stop.failure",{sessionId:i,reason:"prompt_too_long",error:k.message},o),yield{type:"error",turnId:r,error:k.message,code:"PROMPT_TOO_LONG",usage:l.totalUsage};return}if(ie&&k&&Qe(k)){if(Y(D)){D.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield L("reactive_compact","media error strip-retry"),l={...l,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),M(p,"stop.failure",{sessionId:i,reason:"media_error",error:k.message},o),yield{type:"error",turnId:r,error:k.message,code:"IMAGE_ERROR",usage:l.totalUsage};return}if(to(it)){A.consecutiveTruncations+=1;let v=e.modelMaxOutputTokens??vt,j=ze(A,F,v);if(j.shouldEscalate&&nt===void 0){A.currentMaxOutputTokens=j.newMax,o.info(`max_output_tokens escalate: ${j.newMax} tokens`),yield L("output_escalation",`${j.newMax} tokens`),l={...l,maxOutputTokensOverride:It,transition:{reason:"max_output_tokens_escalate"}};continue}if($<Et){let Eo={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 #${$+1}`),yield L("max_output_tokens_recovery",`attempt ${$+1}`),l={...l,messages:[...re,Eo],maxOutputTokensRecoveryCount:$+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:$+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else A.consecutiveTruncations=0;I=me(I,{replayMessages:f,lastStopReason:"completed"});let a=await uo({hooks:p,sessionId:i,messages:f,finalText:l.finalText,thinkingBlocks:B,log:o});if(a?.action==="end"){yield z(a.content);return}if(a?.action==="continue"){l={...l,messages:a.messages,stopHookActive:a.stopHookActive,transition:a.transition};continue}let u=po({tokenBudget:e.tokenBudget,totalUsage:l.totalUsage,budgetContinuationCount:l.budgetContinuationCount,lastBudgetDeltaTokens:l.lastBudgetDeltaTokens,lastBudgetGlobalTokens:l.lastBudgetGlobalTokens,messages:f,finalText:l.finalText,thinkingBlocks:B,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o});if(u){yield L("budget_continuation",u.recoveryDetail),l={...l,messages:u.messages,budgetContinuationCount:u.budgetContinuationCount,lastBudgetDeltaTokens:u.lastBudgetDeltaTokens,lastBudgetGlobalTokens:u.lastBudgetGlobalTokens,transition:u.transition};continue}let y=co({inputMessages:c,messages:f,finalText:l.finalText,thinkingBlocks:B,stopHookActive:l.stopHookActive,totalToolCallCount:N,distinctToolNames:U,log:o});if(y){l={...l,messages:y.messages,stopHookActive:y.stopHookActive,transition:y.transition};continue}let R=Ze({totalToolCallCount:N,distinctToolNames:U,projectRoot:e.projectRoot});R&&(yield{type:"skill_instruction",turnId:r,instruction:R});let P=l.finalText||V(f,o);for(let v of ke)yield{type:"delta",turnId:r,text:v};yield z(P);return}let So=B.length===0&&Z.length>0?Z.join(""):void 0;f.push(_e(O,void 0,B.length>0?B:void 0,So)),I=je(I,{replayMessages:f,pendingToolCallIds:O.map(a=>a.id),completedToolCallIds:I.completedToolCallIds,lastStopReason:"tool_calls"});let ae=l.identicalCallCounts,ct=[],le=[],ut=!1;for(let a of O){let u=`${a.function.name}::${a.function.arguments}`,y=ae.get(u)??0;ae.set(u,y+1),y+1>_t?(le.push(a),ut||(ut=!0,o.info(`AP4 blocked: ${a.function.name} repeated ${y+1}x`))):ct.push(a)}let ce=[];for(let a of le){let u=ae.get(`${a.function.name}::${a.function.arguments}`),y=Ve(f,a.function.name),R=y?`This exact tool call has been attempted ${u} times. Last error: ${y}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${u} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,P=ue(a.id,{ok:!1,error:R});f.push(P),ce.push(a.id),U.add(a.function.name),N++,yield{type:"tool_result",turnId:r,callId:a.id,name:a.function.name,ok:!1,error:R}}if(le.length>0){let a=Ve(f,le[0].function.name),u={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(a?`The error was: "${a}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};f.push(u)}let Re=mo(ct,l.toolFailureCounts),be=Re.allowed;if(Re.blocked.length>0){for(let a of Re.blocked){let u=a.call,y=ue(u.id,{ok:!1,error:a.error});f.push(y),ce.push(u.id),U.add(u.function.name),N++,yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!1,error:a.error},o.info(`variant tool blocked: ${u.function.name} failed ${a.failCount}x with different args`)}f.push(go())}for(let a of be){let u=a.function.arguments,y=E.find(R=>R.function.name===a.function.name);if(y?.backfillObservableInput)try{let R=JSON.parse(a.function.arguments),P={...R};y.backfillObservableInput(P),Object.keys(P).some(j=>!(j in R))&&(u=JSON.stringify(P))}catch{}yield{type:"tool_call",turnId:r,callId:a.id,name:a.function.name,arguments:u,inputSummary:eo(u)}}let Mo=new Map(l.toolFailureCounts);try{let a=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:p,sessionId:i,turnId:r,log:o,signal:b,maxConcurrentTools:e?.maxConcurrentTools});for(let u of be)a.addTool(u);for await(let u of a.getRemainingResults()){if(u.blocked&&(yield{type:"tool_blocked",turnId:r,callId:u.callId,name:u.toolName,reason:u.blockReason??"blocked"}),f.push(u.message),ce.push(u.callId),U.add(u.toolName),N++,fo({toolFailureCounts:l.toolFailureCounts,toolName:u.toolName,ok:u.ok,softEmpty:u.ok&&Jt(u)}),u.ok&&u.toolName==="read"){let y=be.find(R=>R.id===u.callId);if(y)try{let R=JSON.parse(y.function.arguments),P=R.file_path??R.path??R.filePath??"";if(P){let v=l.fileReadCounts.get(P)??0;l.fileReadCounts.set(P,v+1)}}catch{}}yield Xt(r,u);for(let y of Yt(r,u))yield y;for(let y of Vt({turnId:r,result:u,toolCalls:O}))yield y}}catch(a){let u=a instanceof Error?a.message:String(a);yield{type:"error",turnId:r,error:u,code:"TOOL_EXECUTION_ERROR",usage:l.totalUsage};return}if(f.push(...yo({toolFailureCounts:l.toolFailureCounts,snapshot:Mo})),I=me(I,{replayMessages:f,completedToolCallIds:[...I.completedToolCallIds,...ce],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&O.length>0&&(Te=!0),e.generateToolUseSummary&&O.length>0){let a=O.map(u=>({name:u.function.name,arguments:u.function.arguments}));ne=e.generateToolUseSummary(a).catch(()=>null)}let Ao=O.length>0&&O.every(a=>{let u=f.find(R=>R?.role==="tool"&&R?.tool_call_id===a.id);if(!u)return!0;let y=u.content;return typeof y=="string"&&y.startsWith("Error: ")}),ee=l.consecutiveFailedRounds;if(Ao){if(ee+=1,ee>=xt){let a=l.finalText||V(f,o);o.info(`early exit: ${ee} consecutive failed rounds, returning ${l.finalText?"partial":"fallback"} response`),yield z(a);return}}else ee=0;let vo=3,dt=[...l.fileReadCounts.entries()].filter(([,a])=>a>=vo);if(dt.length>0){let a=dt.map(([y])=>y).join(", ");o.info(`AP5: file read cycle detected on ${a}, injecting nudge`);let u={role:"user",content:`You are reading the same files repeatedly (${a}). 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(u),l.fileReadCounts.clear()}let xe=J+1;if(x>0&&xe>x){if(o.info(`max turns reached (${x}), completing`),p){let u=await p.invoke("stop",{sessionId:i,reason:"max_turns"});if(u.action==="abort"){let y=u.reason??"Stop hook requested continuation after max_turns",R={role:"assistant",content:l.finalText,...B.length>0&&{thinkingBlocks:[...B]}};l={...l,messages:[...f,R,{role:"user",content:y}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let a=l.finalText||V(f,o);yield z(a);return}if(xe>S){o.info(`tool loop budget exhausted (${S} rounds), returning`);let a=Ze({totalToolCallCount:N,distinctToolNames:U,projectRoot:e.projectRoot});a&&(yield{type:"skill_instruction",turnId:r,instruction:a});let u=l.finalText||V(f,o);yield z(u);return}l={messages:f,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:xe,transition:{reason:"next_turn"},guardState:A,reactiveCompactState:D,toolLoopState:I,consecutiveFailedRounds:ee,finalText:l.finalText,totalUsage:l.totalUsage,collapseStore:he,currentModel:l.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:l.stopHookActive,lastResponseId:l.lastResponseId,snipRemovedIds:l.snipRemovedIds,contentReplacementState:l.contentReplacementState,budgetContinuationCount:l.budgetContinuationCount,lastBudgetDeltaTokens:l.lastBudgetDeltaTokens,lastBudgetGlobalTokens:l.lastBudgetGlobalTokens,identicalCallCounts:ae,toolFailureCounts:l.toolFailureCounts,fileReadCounts:l.fileReadCounts,recoveryTrace:l.recoveryTrace}}}var Jn=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function ko(e){let t=Qn(e),n=["[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){n.push("[Memory conflict detected]");for(let o of t)n.push(`- entity: ${o.entity}; fact: ${o.predicate}; L1 project MD says: ${Co(o.l1Amount)}; L2 long-term says: ${Co(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=tr(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
7
- `)}function Qn(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>ho(r.text)),n=e.filter(r=>r.source==="l2-long-term").flatMap(r=>ho(r.text)),o=[];for(let r of t)for(let i of n)r.entity===i.entity&&r.predicate===i.predicate&&r.amount!==i.amount&&o.push({entity:r.entity,predicate:r.predicate,l1Amount:r.amount,l2Amount:i.amount,l1Text:r.text,l2Text:i.text});return or(o)}function ho(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim();if(o)for(let r of Jn){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let i=new RegExp(`${nr(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let c of o.matchAll(i)){let s=er(c[1]);s!==null&&t.push({entity:Zn(o,r),predicate:r,amount:s,text:o})}}}return t}function Zn(e,t){if(/Galaxy\s+Tech/i.test(e))return"Galaxy Tech";if(e.includes("\u7528\u6237"))return"\u7528\u6237";let n=e.toLowerCase().indexOf(t.toLowerCase()),r=(n>=0?e.slice(0,n):"").replace(/[#*`:\-,。;;,.]/g," ").trim().split(/\s+/).filter(Boolean);return r[r.length-1]??"unknown"}function er(e){let t=e.replace(/,/g,"").replace(/\s+/g,"").trim(),n=t.endsWith("\u4E07")?1e4:/k$/i.test(t)?1e3:1,o=Number(t.replace(/[万kK]$/u,""));return Number.isFinite(o)?o*n:null}function tr(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 Co(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function or(e){let t=new Set;return e.filter(n=>{let o=`${n.entity}\0${n.predicate}\0${n.l1Amount}\0${n.l2Amount}`;return t.has(o)?!1:(t.add(o),!0)})}function nr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var rr=8192;async function Ro(e){let{hooks:t,detectRecallCategories:n,log:o,sessionId:r,turnId:i,query:c}=e;try{let s=n(c),g=(await t.invoke("memory.before_recall",{sessionId:r,turnId:i,query:c,preferredCategories:s.preferred.length>0?s.preferred:void 0,deprioritizedCategories:s.deprioritized.length>0?s.deprioritized:void 0}))?.context?.recalledMemories,T=null;if(g&&g.length>0){let p=0,b=[];for(let h of g){let x=(h.text?.length??0)*2;if(p+x>rr)break;b.push(h),p+=x}b.length>0&&(T=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
8
- ${ko(b)}`)}return M(t,"memory.after_recall",{sessionId:r,turnId:i,blockCount:g?.length??0},o),T}catch{return null}}var xo=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,n){let{turnId:o,messages:r,tools:i,systemPrompt:c,config:s}=t,d={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},M(this.hooks,"turn.submitted",{...d,prompt:r[r.length-1]?.content??void 0},this.log);let g=Ue(r),T=[];if(c&&T.push({role:"system",content:c}),T.push(...g),this.hooks){let h=g.filter(C=>C.role==="user").pop(),x=typeof h?.content=="string"?h.content.slice(0,500):void 0;if(x){let C=await Ro({hooks:this.hooks,detectRecallCategories:m=>this.runtimePorts.detectRecallCategories(m),log:this.log,sessionId:t.sessionId,turnId:o,query:x});C&&T.splice(c?1:0,0,{role:"system",content:C})}}let p=s?.model??"",b=Math.min(s?.maxRounds??this.maxRounds,100);try{let h=async _=>{let S=this.runtimePorts.resolveModelForPurpose("smallModel");if(!S)return null;try{let F=_.map(E=>`${E.name}(${E.arguments.slice(0,200)})`).join(", "),U=this.transport.stream({model:S,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},s?.apiKey??this.apiKey),N="";for await(let E of U)E.type==="delta"&&(N+=E.text);return N.trim()||null}catch{return null}},x=s?.reasoning;s?.reasoning?.effort==="auto"&&(x={...s?.reasoning,effort:"medium"});let C={turnId:o,sessionId:t.sessionId,messages:T,tools:i,model:p,apiKey:s?.apiKey??this.apiKey,temperature:s?.temperature,maxRounds:b,contextWindowTokens:s?.contextWindowTokens,maxOutputTokens:s?.maxOutputTokens,modelMaxOutputTokens:s?.modelMaxOutputTokens,toolChoice:s?.toolChoice,parentDepth:s?.parentDepth,hooks:this.hooks,fallbackModel:s?.fallbackModel,maxTurns:s?.maxTurns,tokenBudget:s?.tokenBudget,maxConcurrentTools:s?.maxConcurrentTools,streamRequired:s?.streamRequired,reasoning:x,promptCacheKey:s?.promptCacheKey,promptCacheRetention:s?.promptCacheRetention,serviceTier:s?.serviceTier,openaiBuiltinTools:s?.openaiBuiltinTools,maxToolCalls:s?.maxToolCalls,parallelToolCalls:s?.parallelToolCalls,textVerbosity:s?.textVerbosity,projectRoot:this.projectRoot,generateToolUseSummary:h,runtimePorts:this.runtimePorts.toolLoop,signal:n},m;for await(let _ of To(C,this.transport,this.toolInvoker,this.log))m=_,yield _;m?.type==="end"?M(this.hooks,"turn.completed",{...d},this.log):m?.type==="error"&&M(this.hooks,"turn.failed",{...d,code:m.code,error:m.error},this.log)}catch(h){if(n?.aborted)M(this.hooks,"turn.failed",{...d,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let x=h instanceof Error?h.message:String(h),C=typeof h?.status=="number"?h.status:void 0,m=W(C,x);this.log.error(`turn ${o} error [${m}, retryable=${Me(m)}]: ${x}`),M(this.hooks,"turn.failed",{...d,code:m,error:x},this.log),yield{type:"error",turnId:o,error:x,code:m}}}}};export{xo as Agent};
8
+ \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.`)}function ee(e,t,o,n){return{reason:e,messages:[...t,o,n],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function At(e){let t=e.inputMessages.find(T=>T.role==="user"),o=typeof t?.content=="string"?t.content:"",n=jr.test(o),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=ge(e.inputMessages),i=Vo(e.inputMessages),a=ns(e.inputMessages,s,i),d=s.done!==void 0&&e.finalText.includes(s.done)||s.fail!==void 0&&e.finalText.includes(s.fail)||i!==void 0&&e.finalText.includes(i),p=a.length===0||a.some(T=>e.finalText.trimStart().startsWith(T)),f=Zo(e.inputMessages,s),m=_t(e.inputMessages,e.messages);if(m.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${m.length} file(s) missing`);let T=bt(e.inputMessages),h={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${m.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${T??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return ee("explicit_required_file_verification",e.messages,Q(e.finalText,e.thinkingBlocks),h)}let b=Yo(e.inputMessages,e.messages);if(b.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${b.length} unexpected file(s)`);let T=bt(e.inputMessages),h={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${b.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${T??"FAIL"} and the real reason. Do not claim completion while extra deliverables remain.`};return ee("explicit_extra_file_verification",e.messages,Q(e.finalText,e.thinkingBlocks),h)}if(a.length>0&&e.totalToolCallCount>0&&!p){e.log.info("final marker verification: explicit final marker was not at the start of the response");let T={role:"user",content:`The requested output file evidence is present, but your final response did not start with the explicit completion marker. Your final response must start with one of the requested final markers: ${a.join(" or ")}. No preface, heading, markdown emphasis, or summary may appear before the marker.`};return ee("final_marker_verification",e.messages,Q(e.finalText,e.thinkingBlocks),T)}if((s.done!==void 0||i!==void 0)&&e.totalToolCallCount>0&&!d){e.log.info("final marker verification: explicit final DONE/FAIL marker missing");let T=s.done??i,h={role:"user",content:"The requested output file evidence is present, but your final response omitted the explicit completion marker. "+(s.done?`If you have verified the artifacts, Reply exactly with ${s.done}. `:`Your final response must include marker ${T} and clearly say whether the run passed or failed. `)+(s.fail?`If verification failed, reply with ${s.fail} and the real reason. `:`If verification failed, reply with FAIL ${T??""} and the real reason. `)+"Do not end the turn without one of the requested final markers."};return ee("final_marker_verification",e.messages,Q(e.finalText,e.thinkingBlocks),h)}if(f!==void 0&&e.totalToolCallCount>0&&e.finalText.trim()!==f){e.log.info("final marker verification: exact-only final marker response had extra text");let T={role:"user",content:`Reply exactly with ${f} and no other text.`};return ee("final_marker_verification",e.messages,Q(e.finalText,e.thinkingBlocks),T)}if(d&&r||e.stopHookActive)return null;if(n&&!r){e.log.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),e.totalToolCallCount>0&&is(e.messages);let T={role:"user",content:e.totalToolCallCount===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."};return ee("file_action_verification",e.messages,Q(e.finalText,e.thinkingBlocks),T)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(ss).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let h={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."};return ee("multi_file_skeleton_verification",e.messages,Q(e.finalText,e.thinkingBlocks),h)}return null}function as(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function on(e){if(!e.hooks)return null;let t=await e.hooks.invoke("stop",{sessionId:e.sessionId,reason:"completed"});if(t.action==="prevent")return e.log.info(`stop hook prevented continuation: ${t.reason??"no reason"}`),{action:"end",content:e.finalText};if(t.action==="abort"){let o=t.reason??"Stop hook requested continuation";e.log.info(`stop hook blocking: ${o}`);let n={role:"user",content:o};return{action:"continue",messages:[...e.messages,as(e.finalText,e.thinkingBlocks),n],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var ls=5;function cs(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function us(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function nn(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=ls)return null;let t=cs(e.totalUsage),o=t/e.tokenBudget*100,n=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=uo&&n<Qe&&e.lastBudgetDeltaTokens<Qe)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(o)}% (delta=${n})`),null;if(o>=90)return null;let s=e.budgetContinuationCount+1,i={role:"user",content:e.getBudgetContinuationMessage(o,t,e.tokenBudget)};return e.log.info(`token budget continuation #${s}: ${Math.round(o)}% used`),{messages:[...e.messages,us(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:n,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(o)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function vt(e){if(e.totalToolCallCount<=0)return null;let t={ok:!0,toolCallCount:e.totalToolCallCount,distinctToolCount:e.distinctToolNames.size,multiStep:e.totalToolCallCount>=2,hasSubAgent:!1,feedback:null,existingSkillName:null};return ot(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function rn(e,t){let o=[],n=[];for(let r of e){let s=t.get(r.function.name)??0;s>=be?n.push({call:r,failCount:s,error:`Tool "${r.function.name}" has failed ${s} times this turn with different arguments. The target likely does not exist. Stop trying variations and report the issue to the user.`}):o.push(r)}return{allowed:o,blocked:n}}function sn(){return{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."}}function an(e){if(e.ok&&!e.softEmpty)return;let t=e.toolFailureCounts.get(e.toolName)??0;e.toolFailureCounts.set(e.toolName,t+1)}function ln(e){let t=[];for(let[o,n]of e.toolFailureCounts)n>=be&&(e.snapshot.get(o)??0)<be&&t.push({role:"user",content:`Tool "${o}" has now failed/returned empty results ${n} times with different arguments. The target clearly does not exist. Do NOT call "${o}" again. Report the result to the user immediately.`});return t}function ps(e,t){if(e.length!==1||e[0]?.function.name!=="stt")return!1;let o=[...t].reverse().find(i=>i.role==="user");if(!o)return!1;let n=Array.isArray(o.audioUrls)&&o.audioUrls.some(i=>typeof i=="string"&&i.trim()),r=typeof o.content=="string"?o.content:"",s=/\b(?:stt|speech[-\s]?to[-\s]?text|transcribe|transcription|audio[-\s]?to[-\s]?text)\b|转写|转录|语音转文字|音频转文字|听写/i.test(r);return n&&s}function ms(e,t){let o=fs(t);if(!o)return null;let n=gs(o);if(!n)return null;let r=[...e].reverse().find(a=>a.role==="user"),s=typeof r?.content=="string"?r.content:"",i=/\bAUDIO_STT_RESULT\s+([^\s<]+)\s+<transcription\b/i.exec(s);return i?.[1]?`AUDIO_STT_RESULT ${i[1]} ${n}`:n}function fs(e){let t=[e.details?.transcription,e.details?.text,e.details?.preview];for(let n of t)if(typeof n=="string"&&n.trim())return n.trim();let o=e.message?.content;return typeof o=="string"?o.trim():""}function gs(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}var St=new Set(["read","search"]),ys=new Set(["write","edit","patch","image_generate"]);function hs(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let o=t.slice(0,t.indexOf("::"));St.has(o)&&e.identicalCallCounts.delete(t)}}async function*cn(e,t,o,n){let{turnId:r,sessionId:s,messages:i,tools:a,model:d,apiKey:p,temperature:f=0,hooks:m,signal:b}=e,T={sessionId:s,turnId:r},h=e.maxTurns??0,k=e.querySource,_=e.runtimePorts.resolveToolEligibility(a,e.toolEligibilityContext),R=_.eligibleTools;for(let g of _.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:g.toolName,reason:"blocked-by-policy"};let P=Lo(e.maxRounds,i),oe=Oo(e.maxToolCalls,i),Fe=Ee(i),q={contextWindowTokens:e.contextWindowTokens??ro,responseBufferTokens:so,maxOutputTokens:e.maxOutputTokens??io,abortSignal:b,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},L=new Set,E=0,X=R,gn=ps(R,i),ye,Ne=!1,Et=0,c={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:dt(q),reactiveCompactState:yt(),toolLoopState:Me({maxRounds:P,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:Ye(),currentModel:d,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,finalMarkerEmptyRecoveryCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,fileReadCounts:new Map,recoveryTrace:new Map},De=Math.max(h*5,200),wt=0,O=(g,F)=>(c.recoveryTrace.set(g,(c.recoveryTrace.get(g)??0)+1),{type:"recovery",turnId:r,action:g,detail:F}),I=g=>({type:"end",turnId:r,content:g,usage:c.totalUsage,model:c.currentModel,...c.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(c.recoveryTrace)}:{}}),ae=(g,F)=>{if(c.finalText.trim()===""){let z=Oe({inputMessages:i,reason:F});if(z)return z}return c.finalText||Ct(g,n)},yn=(g,F,z)=>{let H=te({inputMessages:i,messages:F,reason:z});if(H)return H;if(g.trim()===""){let A=Oe({inputMessages:i,reason:z});if(A)return A}return g||Ct(F,n)};for(;;){if(wt++,wt>De){n.info(`hard iteration cap reached (${De}), forcing completion`);let l=ae(c.messages,`hard iteration cap reached (${De}) before producing the requested final marker`);yield I(l);return}let{messages:g,maxOutputTokensRecoveryCount:F,maxOutputTokensOverride:z,turnCount:H,guardState:A,reactiveCompactState:U,collapseStore:Be}=c,{toolLoopState:N}=c;if(ye){try{let l=await ye;l&&(yield{type:"tool_use_summary",turnId:r,summary:l})}catch{}ye=void 0}if(e.refreshTools&&H>1){let l=e.refreshTools();l!==X&&(X=l,n.debug(`tools refreshed: ${l.length} tools`))}if(gt(A,q)){n.info(`turn aborted by guard at turn ${H}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:c.totalUsage};return}let Y=pt(A,q);if(Y.level==="blocking"){Y.reason==="prompt_too_long"&&se(U)&&(U.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${Y.reason}), reactive compact needed`),yield O("reactive_compact","token budget pre-check")),n.info(`token budget blocking (${Y.reason}), ending tool loop`);break}Y.level==="warning"&&n.info(`token budget warning: ${Y.usagePercent}% used, ${Y.remainingTokens} remaining`);let he=yield*Uo({messages:g,contentReplacementState:c.contentReplacementState,snipRemovedIds:c.snipRemovedIds,collapseStore:Be,guardState:A,guardConfig:q,runtimePorts:e.runtimePorts,hooks:m,hookCtx:T,sessionId:s,currentModel:c.currentModel,log:n,recovery:O,onAutocompact:()=>{c.hasAttemptedReactiveCompact=!1}}),hn=e.toolChoice==="required"&&Ne?"auto":e.toolChoice??"auto",le=nt({tools:X,toolChoice:hn}),ce=Me({maxRounds:P,replayMessages:he,lastStopReason:N.lastStopReason,options:{stopReason:N.lastStopReason}}),It=le.extraSystemPrompt?[{role:"system",content:le.extraSystemPrompt},...ce.state.replayMessages]:ce.state.replayMessages;N=ce.state,ce.recoveryActions.length>0&&n.debug(`tool loop recovery: ${ce.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),n.debug(`turn ${H}, messages: ${It.length}`),S(m,"turn.before_inference",{...T,model:c.currentModel},n);let $e=!1,Ue=[],Pt=new Map,Lt="stop",D,x=null,Te=!1,Ot=!1,ue=[],j=[];try{for await(let l of t.stream({model:c.currentModel,messages:It,...le.tools.length>0?{tools:le.tools,toolChoice:le.normalizedToolChoice??"auto"}:{},temperature:f,maxTokens:(z??A.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:c.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},p,b))switch(l.type){case"delta":Ue.push(l.text);break;case"tool_call_delta":$e=!0,ht(Pt,l);break;case"reasoning_delta":ue.push(l.text);break;case"reasoning_block_complete":l.signature&&j.push({thinking:ue.join(""),signature:l.signature}),ue.length=0;break;case"usage":D={inputTokens:l.promptTokens,outputTokens:l.completionTokens,reasoningTokens:l.reasoningTokens,cacheRead:l.cacheReadTokens,cacheWrite:l.cacheCreationTokens};break;case"response_id":c.lastResponseId=l.id;break;case"annotations":yield{type:"annotations",turnId:r,annotations:l.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${l.toolType}: ${l.event}`};break;case"done":Ot=!0,Lt=l.finishReason;break}if($e||S(m,"turn.after_inference",{...T,model:c.currentModel},n),e.postSamplingHooks&&e.postSamplingHooks.length>0){let l=c.currentModel;for(let u of e.postSamplingHooks)try{u({messages:[...he],model:l,sessionId:s})}catch{}}}catch(l){let u=yield*jo(l,{state:c,guardState:A,fallbackModel:e.fallbackModel,signal:b,querySource:k,turnId:r,log:n,emitRecovery:O});if(u.kind==="return")return;if(u.kind==="continue"){c={...c,...u.patch};continue}x=u.streamError}if(!x&&!Ot){let l="LLM stream closed before a terminal event; the response was likely truncated upstream.";S(m,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:l},n),yield{type:"error",turnId:r,error:l,code:"RETRYABLE_TRANSIENT",usage:c.totalUsage};return}if(x&&S(m,"turn.after_inference",{...T,model:c.currentModel,response:{error:x.message}},n),x)if(kt(x))Te=!0,n.info(`withheld prompt_too_long error (status=${x.status})`);else if(Rt(x))Te=!0,n.info(`withheld media_size error (status=${x.status})`);else{let l=mt({status:x.status??500,message:x.message},A,q);if(l.action==="reactive_compact"&&se(U)&&(U.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,yield O("reactive_compact",`API ${x.status??500}: ${x.message}`)),l.action==="retry"){let y=(c.consecutiveApiRetries??0)+1;if(y>re){n.info(`API retry limit reached (${re}), aborting`);let C=ne(x.status,x.message);yield{type:"error",turnId:r,error:x.message,code:C,usage:c.totalUsage};return}yield O("retry",l.reason),c={...c,consecutiveApiRetries:y,transition:void 0};continue}let u=ne(x.status,x.message);S(m,"stop.failure",{sessionId:s,reason:u,error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:u,usage:c.totalUsage};return}D&&(c.totalUsage.inputTokens+=D.inputTokens,c.totalUsage.outputTokens+=D.outputTokens,D.reasoningTokens&&(c.totalUsage.reasoningTokens=(c.totalUsage.reasoningTokens??0)+D.reasoningTokens),D.cacheRead&&(c.totalUsage.cacheRead=(c.totalUsage.cacheRead??0)+D.cacheRead),D.cacheWrite&&(c.totalUsage.cacheWrite=(c.totalUsage.cacheWrite??0)+D.cacheWrite)),D?.inputTokens&&(A.promptTokens=D.inputTokens);let Ft=Ue.join(""),$=[...Pt.values()].map(l=>({id:l.id||`tc_${r}_${H}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if($.length===0&&!$e){if(Ft&&(c.finalText=Ft),e.toolChoice==="required"&&!Ne&&X.length>0&&Et<2){Et++;let M=X.map(w=>w.function.name).filter(Boolean).slice(0,8).join(", ");c={...c,messages:[...g,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${M}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(Te&&x&&kt(x)){if(c.transition?.reason!=="collapse_drain_retry"){let M=Ze(he,Be);if(M.committed>0){n.info(`collapse drain: committed ${M.committed} stages`),yield O("collapse_drain",`${M.committed} stages committed`),c={...c,messages:M.messages,transition:{reason:"collapse_drain_retry",committed:M.committed}};continue}}if(se(U)){U.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,n.info("withheld 413: reactive compact attempt"),yield O("reactive_compact","withheld prompt_too_long"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld 413: recovery exhausted, surfacing error"),S(m,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:"PROMPT_TOO_LONG",usage:c.totalUsage};return}if(Te&&x&&Rt(x)){if(se(U)){U.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,n.info("withheld media error: reactive compact strip-retry"),yield O("reactive_compact","media error strip-retry"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld media error: recovery exhausted"),S(m,"stop.failure",{sessionId:s,reason:"media_error",error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:"IMAGE_ERROR",usage:c.totalUsage};return}if(Do(Lt)){A.consecutiveTruncations+=1;let M=e.modelMaxOutputTokens??ao,w=ft(A,q,M);if(w.shouldEscalate&&z===void 0){A.currentMaxOutputTokens=w.newMax,n.info(`max_output_tokens escalate: ${w.newMax} tokens`),yield O("output_escalation",`${w.newMax} tokens`),c={...c,maxOutputTokensOverride:co,transition:{reason:"max_output_tokens_escalate"}};continue}if(F<lo){let K={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."};n.info(`max_output_tokens recovery #${F+1}`),yield O("max_output_tokens_recovery",`attempt ${F+1}`),c={...c,messages:[...he,K],maxOutputTokensRecoveryCount:F+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:F+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else A.consecutiveTruncations=0;N=_e(N,{replayMessages:g,lastStopReason:"completed"});let l=await on({hooks:m,sessionId:s,messages:g,finalText:c.finalText,thinkingBlocks:j,log:n});if(l?.action==="end"){let M=yn(l.content,g,"stop hook prevented continuation before producing the requested final marker");yield I(M);return}if(l?.action==="continue"){c={...c,messages:l.messages,stopHookActive:l.stopHookActive,transition:l.transition};continue}let u=nn({tokenBudget:e.tokenBudget,totalUsage:c.totalUsage,budgetContinuationCount:c.budgetContinuationCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,messages:g,finalText:c.finalText,thinkingBlocks:j,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:n});if(u){yield O("budget_continuation",u.recoveryDetail),c={...c,messages:u.messages,budgetContinuationCount:u.budgetContinuationCount,lastBudgetDeltaTokens:u.lastBudgetDeltaTokens,lastBudgetGlobalTokens:u.lastBudgetGlobalTokens,transition:u.transition};continue}let y=At({inputMessages:i,messages:g,finalText:c.finalText,thinkingBlocks:j,stopHookActive:c.stopHookActive,totalToolCallCount:E,distinctToolNames:L,log:n});if(y){if(c.stopHookActive&&(y.reason==="final_marker_verification"||c.finalText.trim()==="")){let M=te({inputMessages:i,messages:y.messages,reason:"final marker verification produced an empty response after tool use"});if(M){yield I(M);return}if(y.reason==="final_marker_verification"&&c.finalText.trim()===""&&c.finalMarkerEmptyRecoveryCount<1){yield O("final_marker_empty_retry","one extra retry after empty marker nudge"),c={...c,messages:y.messages,stopHookActive:y.stopHookActive,transition:y.transition,finalMarkerEmptyRecoveryCount:c.finalMarkerEmptyRecoveryCount+1};continue}let w=Jo({inputMessages:i,messages:y.messages});if(w){yield I(w);return}let K=Oe({inputMessages:i,reason:"final marker verification produced an empty response after tool use"});if(K){yield I(K);return}}c={...c,messages:y.messages,stopHookActive:y.stopHookActive,transition:y.transition};continue}let C=vt({totalToolCallCount:E,distinctToolNames:L,projectRoot:e.projectRoot});C&&(yield{type:"skill_instruction",turnId:r,instruction:C});let v=ae(g,"the model ended with an empty response after tool use before producing the requested final marker");for(let M of Ue)yield{type:"delta",turnId:r,text:M};yield I(v);return}let Tn=j.length===0&&ue.length>0?ue.join(""):void 0;g.push(Ge($,void 0,j.length>0?j:void 0,Tn)),N=lt(N,{replayMessages:g,pendingToolCallIds:$.map(l=>l.id),completedToolCallIds:N.completedToolCallIds,lastStopReason:"tool_calls"});let Ce=c.identicalCallCounts,Nt=[],ke=[],Dt=[],Bt=!1;for(let l of $){let u=`${l.function.name}::${l.function.arguments}`,y=Ce.get(u)??0;if(Ce.set(u,y+1),y+1>no){let C=St.has(l.function.name)?c.identicalSuccessfulToolResults.get(u):void 0;if(C){Dt.push({call:l,result:C,repeatCount:y+1});continue}ke.push(l),Bt||(Bt=!0,n.info(`AP4 blocked: ${l.function.name} repeated ${y+1}x`))}else Nt.push(l)}let G=[];for(let l of Dt){let u=l.call,y=`Reused previous successful ${u.function.name} result for identical arguments (attempt ${l.repeatCount}); no additional tool execution was performed.
9
+
10
+ ${l.result.content}`,C=W(u.id,{ok:!0,payload:y,imageUrls:l.result.imageUrls,toolReferences:l.result.toolReferences});g.push(C),G.push(u.id),L.add(u.function.name),E++,yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!0,outputPreview:y.slice(0,2e3),durationMs:0,details:{type:u.function.name,reusedIdenticalCall:!0,repeatCount:l.repeatCount}}}for(let l of ke){let u=Ce.get(`${l.function.name}::${l.function.arguments}`),y=Tt(g,l.function.name),C=y?`This exact tool call has been attempted ${u} times. Last error: ${y}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${u} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,v=W(l.id,{ok:!1,error:C});g.push(v),G.push(l.id),L.add(l.function.name),E++,yield{type:"tool_result",turnId:r,callId:l.id,name:l.function.name,ok:!1,error:C}}if(ke.length>0){let l=Tt(g,ke[0].function.name),u={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(l?`The error was: "${l}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};g.push(u)}let $t=[],je=[];for(let l of Nt){let u=tn({inputMessages:i,messages:g,toolCall:l});u?je.push({call:l,error:u}):$t.push(l)}for(let l of je){let u=l.call;g.push(W(u.id,{ok:!1,error:l.error})),G.push(u.id),L.add(u.function.name),E++,yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!1,error:l.error},n.info(`premature completion artifact blocked: ${u.function.name}`)}je.length>0&&g.push({role:"user",content:"A tool attempted to write a completion artifact before all explicitly requested output files had evidence. Do not write final DONE markers or success reports into artifacts until the missing files are created or verified. If you cannot complete them, respond with the requested FAIL marker and the real reason."});let Cn=new Set(X.map(l=>l.function.name)),Ut=[],jt=[];for(let l of $t)Cn.has(l.function.name)?Ut.push(l):jt.push(l);for(let l of jt){let u=`Tool "${l.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;g.push(W(l.id,{ok:!1,error:u})),G.push(l.id),n.warn(`unoffered tool call suppressed: ${l.function.name}`)}let qe=rn(Ut,c.toolFailureCounts),qt=qe.allowed,zt=Math.max(0,oe-E),de=zt>0?qt.slice(0,zt):[],ze=qt.slice(de.length),kn=ze.length>0;if(qe.blocked.length>0){for(let l of qe.blocked){let u=l.call,y=W(u.id,{ok:!1,error:l.error});g.push(y),G.push(u.id),L.add(u.function.name),E++,yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!1,error:l.error},n.info(`variant tool blocked: ${u.function.name} failed ${l.failCount}x with different args`)}g.push(sn())}if(ze.length>0){let l=`Tool call budget exhausted (${oe}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let u of ze){let y=W(u.id,{ok:!1,error:l});g.push(y),G.push(u.id),L.add(u.function.name),E++,yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!1,error:l}}g.push({role:"user",content:`${l} If explicitly requested output files are still missing, respond with the requested FAIL marker and the real reason.`})}for(let l of de){let u=l.function.arguments,y=X.find(C=>C.function.name===l.function.name);if(y?.backfillObservableInput)try{let C=JSON.parse(l.function.arguments),v={...C};y.backfillObservableInput(v),Object.keys(v).some(w=>!(w in C))&&(u=JSON.stringify(v))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:u,inputSummary:No(u)}}let Rn=new Map(c.toolFailureCounts),Re=null;try{let l=e.runtimePorts.createStreamingToolExecutor({toolInvoker:o,hooks:m,sessionId:s,turnId:r,log:n,signal:b,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:to});for(let u of de)l.addTool(u);for await(let u of l.getRemainingResults()){u.blocked&&(yield{type:"tool_blocked",turnId:r,callId:u.callId,name:u.toolName,reason:u.blockReason??"blocked"}),g.push(u.message),G.push(u.callId),L.add(u.toolName),E++;let y=u.ok&&Po(u);if(an({toolFailureCounts:c.toolFailureCounts,toolName:u.toolName,ok:u.ok,softEmpty:y}),u.ok&&ys.has(u.toolName)&&hs(c),u.ok&&!y&&St.has(u.toolName)){let C=de.find(M=>M.id===u.callId),v=typeof u.message?.content=="string"?u.message.content:"";if(C&&v){let M=Array.isArray(u.message.imageUrls)?u.message.imageUrls.filter(K=>typeof K=="string"):void 0,w=Array.isArray(u.message.toolReferences)?u.message.toolReferences.filter(K=>typeof K=="string"):void 0;c.identicalSuccessfulToolResults.set(`${C.function.name}::${C.function.arguments}`,{content:v,imageUrls:M,toolReferences:w})}}if(u.ok&&u.toolName==="read"){let C=de.find(v=>v.id===u.callId);if(C)try{let v=JSON.parse(C.function.arguments),M=v.file_path??v.path??v.filePath??"";if(M){let w=c.fileReadCounts.get(M)??0;c.fileReadCounts.set(M,w+1)}}catch{}}yield So(r,u);for(let C of Eo(r,u))yield C;for(let C of wo({turnId:r,result:u,toolCalls:$}))yield C;!Re&&gn&&u.toolName==="stt"&&u.ok&&(Re=ms(i,u))}}catch(l){let u=l instanceof Error?l.message:String(l);yield{type:"error",turnId:r,error:u,code:"TOOL_EXECUTION_ERROR",usage:c.totalUsage};return}if(Re){yield I(Re);return}if(g.push(...ln({toolFailureCounts:c.toolFailureCounts,snapshot:Rn})),kn){let l=te({inputMessages:i,messages:g,reason:`tool call budget exhausted (${oe}) before completing all required files`});if(l){yield I(l);return}}if(N=_e(N,{replayMessages:g,completedToolCallIds:[...N.completedToolCallIds,...G],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&$.length>0&&(Ne=!0),e.generateToolUseSummary&&$.length>0){let l=$.map(u=>({name:u.function.name,arguments:u.function.arguments}));ye=e.generateToolUseSummary(l).catch(()=>null)}let bn=$.length>0&&$.every(l=>{let u=g.find(C=>C?.role==="tool"&&C?.tool_call_id===l.id);if(!u)return!0;let y=u.content;return typeof y=="string"&&y.startsWith("Error: ")}),pe=c.consecutiveFailedRounds;if(bn){if(pe+=1,pe>=oo){if(Fe>=3&&c.repeatedToolFailureRecoveryCount<1){let y=At({inputMessages:i,messages:g,finalText:c.finalText,thinkingBlocks:[],stopHookActive:c.stopHookActive,totalToolCallCount:E,distinctToolNames:L,log:n});if(y?.reason==="explicit_required_file_verification"||y?.reason==="explicit_extra_file_verification"){yield O("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),c={...c,messages:y.messages,stopHookActive:y.stopHookActive,transition:y.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}let l=te({inputMessages:i,messages:g,reason:"repeated tool failures stopped the turn before completing all required files"});if(l){yield I(l);return}let u=ae(g,"repeated tool failures stopped the turn before producing the requested final marker");n.info(`early exit: ${pe} consecutive failed rounds, returning ${c.finalText?"partial":"fallback"} response`),yield I(u);return}}else pe=0;let xn=3,Ht=[...c.fileReadCounts.entries()].filter(([,l])=>l>=xn);if(Ht.length>0){let l=Ht.map(([y])=>y).join(", ");n.info(`AP5: file read cycle detected on ${l}, injecting nudge`);let u={role:"user",content:`You are reading the same files repeatedly (${l}). This indicates a circular dependency or cycle. Stop reading files, summarize your findings so far, and explain the circular structure to the user.`};g.push(u),c.fileReadCounts.clear()}let He=H+1;if(h>0&&He>h){if(n.info(`max turns reached (${h}), completing`),m){let y=await m.invoke("stop",{sessionId:s,reason:"max_turns"});if(y.action==="abort"){let C=y.reason??"Stop hook requested continuation after max_turns",v={role:"assistant",content:c.finalText,...j.length>0&&{thinkingBlocks:[...j]}};c={...c,messages:[...g,v,{role:"user",content:C}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let l=te({inputMessages:i,messages:g,reason:`tool loop max turns reached (${h}) before completing all required files`});if(l){yield I(l);return}let u=ae(g,`tool loop max turns reached (${h}) before producing the requested final marker`);yield I(u);return}if(He>P){n.info(`tool loop budget exhausted (${P} rounds), returning`);let l=vt({totalToolCallCount:E,distinctToolNames:L,projectRoot:e.projectRoot});l&&(yield{type:"skill_instruction",turnId:r,instruction:l});let u=te({inputMessages:i,messages:g,reason:`tool budget exhausted (${P} rounds) before completing all required files`});if(u){yield I(u);return}let y=ae(g,`tool budget exhausted (${P} rounds) before producing the requested final marker`);yield I(y);return}c={messages:g,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:He,transition:{reason:"next_turn"},guardState:A,reactiveCompactState:U,toolLoopState:N,consecutiveFailedRounds:pe,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:Be,currentModel:c.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:c.stopHookActive,lastResponseId:c.lastResponseId,snipRemovedIds:c.snipRemovedIds,contentReplacementState:c.contentReplacementState,budgetContinuationCount:c.budgetContinuationCount,finalMarkerEmptyRecoveryCount:c.finalMarkerEmptyRecoveryCount,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,identicalCallCounts:Ce,identicalSuccessfulToolResults:c.identicalSuccessfulToolResults,toolFailureCounts:c.toolFailureCounts,fileReadCounts:c.fileReadCounts,recoveryTrace:c.recoveryTrace}}}var Ts=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function pn(e){let t=Cs(e),o=["[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){o.push("[Memory conflict detected]");for(let n of t)o.push(`- entity: ${n.entity}; fact: ${n.predicate}; L1 project MD says: ${dn(n.l1Amount)}; L2 long-term says: ${dn(n.l2Amount)}; action: ask the user which value is current before using it.`)}for(let n of e){let r=bs(n);o.push(`- [${r}] ${n.text}`)}return o.join(`
11
+ `)}function Cs(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>un(r.text)),o=e.filter(r=>r.source==="l2-long-term").flatMap(r=>un(r.text)),n=[];for(let r of t)for(let s of o)r.entity===s.entity&&r.predicate===s.predicate&&r.amount!==s.amount&&n.push({entity:r.entity,predicate:r.predicate,l1Amount:r.amount,l2Amount:s.amount,l1Text:r.text,l2Text:s.text});return xs(n)}function un(e){let t=[];for(let o of e.split(/\r?\n/)){let n=o.trim();if(n)for(let r of Ts){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(n))continue;let s=new RegExp(`${_s(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let i of n.matchAll(s)){let a=Rs(i[1]);a!==null&&t.push({entity:ks(n,r),predicate:r,amount:a,text:n})}}}return t}function ks(e,t){if(/Galaxy\s+Tech/i.test(e))return"Galaxy Tech";if(e.includes("\u7528\u6237"))return"\u7528\u6237";let o=e.toLowerCase().indexOf(t.toLowerCase()),r=(o>=0?e.slice(0,o):"").replace(/[#*`:\-,。;;,.]/g," ").trim().split(/\s+/).filter(Boolean);return r[r.length-1]??"unknown"}function Rs(e){let t=e.replace(/,/g,"").replace(/\s+/g,"").trim(),o=t.endsWith("\u4E07")?1e4:/k$/i.test(t)?1e3:1,n=Number(t.replace(/[万kK]$/u,""));return Number.isFinite(n)?n*o:null}function bs(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 dn(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function xs(e){let t=new Set;return e.filter(o=>{let n=`${o.entity}\0${o.predicate}\0${o.l1Amount}\0${o.l2Amount}`;return t.has(n)?!1:(t.add(n),!0)})}function _s(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ms=8192;async function mn(e){let{hooks:t,detectRecallCategories:o,log:n,sessionId:r,turnId:s,query:i}=e;try{let a=o(i),p=(await t.invoke("memory.before_recall",{sessionId:r,turnId:s,query:i,preferredCategories:a.preferred.length>0?a.preferred:void 0,deprioritizedCategories:a.deprioritized.length>0?a.deprioritized:void 0}))?.context?.recalledMemories,f=null;if(p&&p.length>0){let m=0,b=[];for(let T of p){let h=(T.text?.length??0)*2;if(m+h>Ms)break;b.push(T),m+=h}b.length>0&&(f=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
12
+ ${pn(b)}`)}return S(t,"memory.after_recall",{sessionId:r,turnId:s,blockCount:p?.length??0},n),f}catch{return null}}var fn=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;configuredMaxRounds;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.configuredMaxRounds=typeof t.maxRounds=="number"&&Number.isFinite(t.maxRounds)?Math.min(t.maxRounds,100):void 0,this.maxRounds=Math.min(this.configuredMaxRounds??25,100)}async*run(t,o){let{turnId:n,messages:r,tools:s,systemPrompt:i,config:a}=t,d={sessionId:t.sessionId,turnId:n};yield{type:"start",turnId:n},S(this.hooks,"turn.submitted",{...d,prompt:r[r.length-1]?.content??void 0},this.log);let p=at(r),f=[];if(i&&f.push({role:"system",content:i}),f.push(...p),this.hooks){let h=p.filter(_=>_.role==="user").pop(),k=typeof h?.content=="string"?h.content.slice(0,500):void 0;if(k){let _=await mn({hooks:this.hooks,detectRecallCategories:R=>this.runtimePorts.detectRecallCategories(R),log:this.log,sessionId:t.sessionId,turnId:n,query:k});_&&f.splice(i?1:0,0,{role:"system",content:_})}}let m=a?.model??"",b=typeof a?.maxRounds=="number"&&Number.isFinite(a.maxRounds)?a.maxRounds:this.configuredMaxRounds,T=b===void 0?void 0:Math.min(b,100);try{let h=async P=>{let oe=this.runtimePorts.resolveModelForPurpose("smallModel");if(!oe)return null;try{let Fe=P.map(E=>`${E.name}(${E.arguments.slice(0,200)})`).join(", "),q=this.transport.stream({model:oe,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:Fe}],tools:[],maxTokens:60},a?.apiKey??this.apiKey),L="";for await(let E of q)E.type==="delta"&&(L+=E.text);return L.trim()||null}catch{return null}},k=a?.reasoning;a?.reasoning?.effort==="auto"&&(k={...a?.reasoning,effort:"medium"});let _={turnId:n,sessionId:t.sessionId,messages:f,tools:s,model:m,apiKey:a?.apiKey??this.apiKey,temperature:a?.temperature,maxRounds:T,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:k,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:h,runtimePorts:this.runtimePorts.toolLoop,signal:o},R;for await(let P of cn(_,this.transport,this.toolInvoker,this.log))R=P,yield P;R?.type==="end"?S(this.hooks,"turn.completed",{...d},this.log):R?.type==="error"&&S(this.hooks,"turn.failed",{...d,code:R.code,error:R.error},this.log)}catch(h){if(o?.aborted)S(this.hooks,"turn.failed",{...d,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED"};else{let k=h instanceof Error?h.message:String(h),_=typeof h?.status=="number"?h.status:void 0,R=ne(_,k);this.log.error(`turn ${n} error [${R}, retryable=${We(R)}]: ${k}`),S(this.hooks,"turn.failed",{...d,code:R,error:k},this.log),yield{type:"error",turnId:n,error:k,code:R}}}}};export{fn as Agent};