qlogicagent 2.12.8 → 2.12.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +91 -157
- package/dist/agent.js +6 -6
- package/dist/cli.js +411 -426
- package/dist/index.js +410 -425
- package/dist/orchestration.js +6 -6
- package/dist/protocol.js +1 -1
- package/dist/types/agent/memory-recall-injection.d.ts +34 -0
- package/dist/types/agent/tool-loop/budget-continuation-policy.d.ts +22 -0
- package/dist/types/agent/tool-loop/completion-action-policy.d.ts +19 -0
- package/dist/types/agent/tool-loop/completion-stop-policy.d.ts +19 -0
- package/dist/types/agent/tool-loop/compression-pipeline.d.ts +44 -0
- package/dist/types/agent/tool-loop/skill-instruction-policy.d.ts +7 -0
- package/dist/types/agent/tool-loop/stream-error-recovery.d.ts +59 -0
- package/dist/types/agent/tool-loop/tool-failure-policy.d.ts +22 -0
- package/dist/types/agent/types.d.ts +2 -2
- package/dist/types/cli/acp-message-router.d.ts +8 -0
- package/dist/types/cli/acp-session-host.d.ts +3 -0
- package/dist/types/cli/cli-agent-builder.d.ts +1 -1
- package/dist/types/cli/core-tools/config-tool-bootstrap.d.ts +1 -5
- package/dist/types/cli/core-tools/config-tool-service.d.ts +9 -5
- package/dist/types/cli/core-tools/registry.d.ts +1 -2
- package/dist/types/cli/core-tools/session-tool-manifest.d.ts +11 -0
- package/dist/types/cli/core-tools/team-registry.d.ts +8 -8
- package/dist/types/cli/dev-tools/dev-tool-registry.d.ts +1 -2
- package/dist/types/cli/gateway-rpc-connection.d.ts +50 -0
- package/dist/types/cli/handlers/session-handler.d.ts +2 -1
- package/dist/types/cli/handlers/workflow-handler.d.ts +10 -0
- package/dist/types/cli/model-client-resolver.d.ts +12 -3
- package/dist/types/cli/resolved-agent-cache.d.ts +47 -0
- package/dist/types/cli/rpc-registry.d.ts +59 -5
- package/dist/types/cli/session-context.d.ts +32 -0
- package/dist/types/cli/skill-meta-tool-bootstrap.d.ts +7 -0
- package/dist/types/cli/stdio-acp-protocol-coordinator.d.ts +18 -0
- package/dist/types/cli/stdio-acp-request-host.d.ts +3 -0
- package/dist/types/cli/stdio-rpc-handler-hosts.d.ts +50 -0
- package/dist/types/cli/stdio-server.d.ts +103 -180
- package/dist/types/cli/stdio-session-runtime-coordinator.d.ts +19 -0
- package/dist/types/cli/tool-bootstrap-core-registration.d.ts +30 -0
- package/dist/types/cli/tool-bootstrap-media-registration.d.ts +8 -0
- package/dist/types/cli/tool-bootstrap-paths.d.ts +7 -0
- package/dist/types/cli/tool-bootstrap-web-registration.d.ts +13 -0
- package/dist/types/cli/tool-bootstrap-workflow-registration.d.ts +7 -0
- package/dist/types/cli/tool-bootstrap.d.ts +5 -22
- package/dist/types/cli/tunable-store.d.ts +26 -0
- package/dist/types/cli/workflow-host-adapter.d.ts +29 -0
- package/dist/types/contracts/hooks.d.ts +6 -0
- package/dist/types/orchestration/workflow/run-history-store.d.ts +58 -0
- package/dist/types/orchestration/workflow/workflow-controller.d.ts +23 -1
- package/dist/types/orchestration/workflow/workflow-store.d.ts +24 -0
- package/dist/types/protocol/wire/acp-protocol.d.ts +1 -2
- package/dist/types/protocol/wire/gateway-rpc.d.ts +0 -112
- package/dist/types/runtime/config/tunable-defaults.d.ts +6 -0
- package/dist/types/runtime/infra/agent-paths.d.ts +0 -2
- package/dist/types/runtime/infra/agent-process.d.ts +1 -1
- package/dist/types/runtime/infra/default-path-service.d.ts +0 -1
- package/dist/types/runtime/infra/index.d.ts +1 -1
- package/dist/types/runtime/infra/key-pool.d.ts +1 -0
- package/dist/types/runtime/infra/llmrouter-catalog.d.ts +8 -0
- package/dist/types/runtime/ports/path-service.d.ts +0 -1
- package/dist/types/runtime/ports/tool-contracts.d.ts +1 -1
- package/dist/types/runtime/prompt/environment-context.d.ts +13 -0
- package/dist/types/runtime/prompt/index.d.ts +1 -0
- package/dist/types/runtime/prompt/prompt-policy.d.ts +2 -0
- package/dist/types/runtime/prompt/system-prompt-sections.d.ts +2 -0
- package/dist/types/runtime/session/session-catalog.d.ts +4 -0
- package/dist/types/runtime/session/session-metadata-store.d.ts +8 -0
- package/dist/types/runtime/session/session-paths.d.ts +9 -0
- package/dist/types/runtime/session/session-persistence.d.ts +14 -159
- package/dist/types/runtime/session/session-resume.d.ts +4 -0
- package/dist/types/runtime/session/session-schema.d.ts +10 -0
- package/dist/types/runtime/session/session-summary.d.ts +5 -0
- package/dist/types/runtime/session/session-transcript-store.d.ts +13 -0
- package/dist/types/runtime/session/session-types.d.ts +77 -0
- package/dist/types/runtime/session/session-write-queue.d.ts +2 -0
- package/dist/types/runtime/tasks/task-types.d.ts +1 -1
- package/dist/types/skills/mcp/index.d.ts +1 -3
- package/dist/types/skills/mcp/mcp-manager.d.ts +14 -38
- package/dist/types/skills/permissions/rule-engine.d.ts +1 -0
- package/dist/types/skills/plugins/plugin-api.d.ts +0 -1
- package/dist/types/skills/plugins/plugin-loader.d.ts +0 -4
- package/dist/types/skills/portable-tool.d.ts +2 -2
- package/dist/types/skills/tools/config-tool.d.ts +1 -3
- package/dist/types/skills/tools/skill-tool.d.ts +2 -2
- package/dist/types/skills/tools/team-tool.d.ts +44 -4
- package/dist/types/skills/tools/tool-search-tool.d.ts +11 -0
- package/package.json +2 -1
- package/dist/types/assistants/assistant-registry.d.ts +0 -4
- package/dist/types/assistants/assistant-store.d.ts +0 -23
- package/dist/types/assistants/assistant-turn-context.d.ts +0 -20
- package/dist/types/assistants/assistant-types.d.ts +0 -38
- package/dist/types/assistants/plugin-assistant-registry.d.ts +0 -16
- package/dist/types/cli/core-tools/utility-tool-bootstrap.d.ts +0 -12
- package/dist/types/cli/dev-tools/repl-tool-service.d.ts +0 -5
- package/dist/types/cli/handlers/assistants-handler.d.ts +0 -13
- package/dist/types/skills/mcp/mcp-http-client.d.ts +0 -68
- package/dist/types/skills/mcp/mcp-stdio-client.d.ts +0 -86
- package/dist/types/skills/think-tool.d.ts +0 -16
- package/dist/types/skills/tools/apply-patch-tool.d.ts +0 -29
- package/dist/types/skills/tools/mcp-client-types.d.ts +0 -269
- package/dist/types/skills/tools/mcp-resource-tools.d.ts +0 -14
- package/dist/types/skills/tools/mcp-tool.d.ts +0 -249
- package/dist/types/skills/tools/project-switch-tool.d.ts +0 -24
- package/dist/types/skills/tools/repl-tool.d.ts +0 -70
- package/dist/types/skills/tools/send-message-tool.d.ts +0 -57
package/dist/agent.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
function Me(e,t,r,o){return{role:"assistant",content:t||null,tool_calls:e,...r&&r.length>0?{thinkingBlocks:r}:{},...o?{reasoning_content:o}:{}}}function de(e,t){let r=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:r,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var yo=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,z={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},ho=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,To=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Co=512,ko=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Ro=new Set([500,502,503,504,521,522,523,524,529]),bo=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],_o=["upgrade your plan","upgrade plan","current plan","subscription"],xo=["daily","weekly","monthly"],So=["try again","retry","temporary","cooldown"],Mo=["usage limit","rate limit","organization usage"],Ao=["organization","workspace"],vo=["billing period","exceeded","reached","exhausted"],Eo=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,Io=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function K(e,t){if(!e)return!1;let r=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(r):r.includes(o))}function wo(e){return K(e,z.format)}function dt(e){return K(e,z.rateLimit)}function Lo(e){return K(e,z.timeout)}function Po(e){return yo.test(e)}function Ae(e){let t=e.toLowerCase();return t?e.length>Co?To.test(t):K(t,z.billing)?!0:ho.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function pt(e){return K(e,z.authPermanent)}function Oo(e){return K(e,z.auth)}function mt(e){return K(e,z.overloaded)}function q(e,t){return t.some(r=>e.includes(r))}function No(e){return q(e,bo)||q(e,_o)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Do(e){let t=q(e,xo),r=e.includes("spend limit")||e.includes("spending limit"),o=q(e,Ao);return q(e,So)&&q(e,Mo)||t&&(e.includes("usage limit")||r)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(r||q(e,vo))}function Fo(e){return e.trim().toLowerCase().replace(Io,"").trim()}function gt(e){let t=Fo(e);return!t||No(t)?"billing":dt(t)||Do(t)?"rate_limit":"billing"}function Bo(e){return Eo.test(e)?gt(e):null}function ft(e){let t=e.match(ko);if(!t)return null;let r=Number(t[1]);return Number.isFinite(r)?{code:r,rest:(t[2]??"").trim()}:null}function Uo(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function $o(e){let t=e.trim();if(!t)return!1;let r=ft(t);return r?Ro.has(r.code):!1}function yt(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?gt(t):"billing":e===429?"rate_limit":e===401||e===403?t&&pt(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&mt(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&Ae(t)?"billing":"format":null}function jo(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function Ho(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function ht(e){if(Ho(e))return"session_expired";if(jo(e))return"model_not_found";let t=Bo(e);return t||(Po(e)?Ae(e)?"billing":"rate_limit":dt(e)?"rate_limit":mt(e)?"overloaded":$o(e)?ft(e.trim())?.code===529?"overloaded":"timeout":Uo(e)?"timeout":wo(e)?"format":Ae(e)?"billing":Lo(e)?"timeout":pt(e)?"auth_permanent":Oo(e)?"auth":null)}var Go={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"},qo=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function W(e,t){let r=yt(e,t)??(t?ht(t):null);return r?Go[r]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function ve(e){return qo.has(e)}function Tt(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var zo=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),te=class{constructor(t=20,r=Tt){this.preserveRecentCount=t;this.estimateTokens=r}preserveRecentCount;estimateTokens;compress(t,r){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=t.length-this.preserveRecentCount,n=0,l=0;return{messages:t.map((a,m)=>{if(m>=o||a.role!=="tool"||typeof a.content!="string"||!a.name||!zo.has(a.name)||a.content.length<=200)return a;let h=this.estimateTokens(a);return l+=h,n++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:n,strategy:"micro-compact",metrics:n>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function Ee(e,t,r=Tt){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,n=0,l=[];for(let a of e){let m=a.tool_call_id??"";if(m&&t.has(m)){o+=r(a),n++,t.delete(m);continue}l.push(a)}let d=n>0?{role:"system",content:`[${n} messages removed by snip]`}:void 0;return{messages:l,tokensFreed:o,removedCount:n,boundaryMessage:d}}function Ie(){return{stages:[]}}function we(e,t,r){let o=r?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let l=Ct(e,t),d=Ko(l,t,o);if(d.length===0)return{messages:l,stagedCount:0};for(let a of d)t.stages.push(a);return l=Ct(e,t),{messages:l,stagedCount:d.length}}function Le(e,t){let r=0;for(let o of t.stages)o.committed||(o.committed=!0,r++);return r===0?{messages:e,committed:0}:{messages:kt(e,t),committed:r}}function Ct(e,t){return t.stages.filter(o=>o.committed).length===0?e:kt(e,t)}function kt(e,t){let r=t.stages.filter(n=>n.committed).sort((n,l)=>l.range[0]-n.range[0]),o=[...e];for(let n of r){let[l,d]=n.range;if(l>=o.length)continue;let a=Math.min(d,o.length),m={role:"system",content:n.summary};o.splice(l,a-l,m)}return o}function Ko(e,t,r){let o=Math.max(0,e.length-Math.floor(r/2)),n=[],l=new Set(t.stages.map(m=>`${m.range[0]}-${m.range[1]}`)),d=-1,a=0;for(let m=0;m<o;m++){let h=e[m];if(h.role==="tool"||h.role==="assistant"&&typeof h.content=="string"&&h.content==="")d<0&&(d=m),a++;else{if(a>=3){let k=`${d}-${d+a}`;l.has(k)||n.push({id:`collapse_${d}_${d+a}`,range:[d,d+a],summary:`[${a} tool results collapsed]`,committed:!1})}d=-1,a=0}}if(a>=3){let m=`${d}-${d+a}`;l.has(m)||n.push({id:`collapse_${d}_${d+a}`,range:[d,d+a],summary:`[${a} tool results collapsed]`,committed:!1})}return n}import{existsSync as Oe,readFileSync as $t,writeFileSync as Wo,readdirSync as jt,mkdirSync as Xo}from"node:fs";import{join as Ne,dirname as Yo}from"node:path";var Rt=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),bt=3,_t=2,pe=2,xt=128e3,St=13e3,Mt=16384,At=65536,vt=3,Et=65536,Pe=500,It=3;var wt=3e4,Lt=3,oe=2;var Pt=20;var Ot=3,Nt=2,Dt=300*1e3,Ft=3,Bt=720*60*60*1e3;var zn=300*1e3;var Kn=3600*1e3;var Wn=50*1024,Xn=500*1024,Yn=500*1024*1024,Vn=50*1024*1024;var Jn=60*1024;var Ht=0;var Vo="skill-patterns.json";function Gt(e){return Ne(e,".qlogicagent",Vo)}function Jo(e){let t=Gt(e);try{return JSON.parse($t(t,"utf8"))}catch{return{version:1,patterns:{}}}}function Ut(e,t){let r=Gt(e);Xo(Yo(r),{recursive:!0}),Wo(r,JSON.stringify(t,null,2),"utf8")}function Zo(e){let t=Date.now()-Bt;for(let[r,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[r]}function qt(e,t){if(t.length===0)return!1;let r=me(t),o=Jo(e);Zo(o);let n=new Date().toISOString(),l=o.patterns[r];if(l||(l={signature:r,count:0,firstSeen:n,lastSeen:n,promoted:!1},o.patterns[r]=l),l.promoted)return Ut(e,o),!1;l.count++,l.lastSeen=n;let d=l.count>=Ft;return d&&(l.promoted=!0),Ut(e,o),d}function me(e){return[...e].sort().join("+")}function Qo(e,t){if(!Oe(t))return null;let r=me(e);try{let o=jt(t,{withFileTypes:!0});for(let n of o){if(!n.isDirectory())continue;let l=Ne(t,n.name,"SKILL.md");try{let a=$t(l,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let m=a[1].split(`
|
|
2
|
-
`).map(h=>h.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(me(m)===r)return n.name}}catch{}}}catch{}return null}function en(e){if(!Oe(e))return 0;try{return jt(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&Oe(Ne(e,t.name,"SKILL.md"))).length}catch{return 0}}function tn(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<Ot||e.distinctToolCount<Nt||Date.now()-Ht<Dt||t?.projectSkillsDir&&(en(t.projectSkillsDir)>=Pt||t.tools.length>0&&Qo(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!qt(t.projectRoot,t.tools))}function on(e){return e.existingSkillName?e.feedback==="negative":!1}function ge(e,t){return on(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:tn(e,t)?(Ht=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function zt(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function nn(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function rn(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function sn(e){if(!e.eligibility?.length)return[...e.tools];let t=rn(e.eligibility);return e.tools.filter(r=>{let o=zt(r);if(!o)return!1;let n=t.get(o);return!n||nn(n.status)})}function an(e){let t=[],r=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&r.requireAutoWhenThinking){let n=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;n&&n!=="auto"&&n!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&r.allowRequiredToolChoice===!1){let n=r.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${n}.`),o=n}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&r.allowNamedToolChoice===!1){let n=r.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${n}.`),o=n}return{normalizedToolChoice:o,warnings:t}}function De(e){let t=an({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),r=t.normalizedToolChoice,o=[...t.warnings],n=sn({tools:e.tools,eligibility:e.eligibility});if(!r||r==="auto")return{tools:n,normalizedToolChoice:r,warnings:o};if(r==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(r==="required"){if(n.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:n,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof r=="object"&&!Array.isArray(r)&&r.type==="function"){let l=r.function??void 0,d=typeof l?.name=="string"?l.name.trim():"";if(!d)throw new Error("tool_choice.function.name is required");let a=n.filter(m=>zt(m)===d);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${d}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:d}},extraSystemPrompt:`You must call the ${d} tool before responding.`,warnings:o}}return{tools:n,normalizedToolChoice:r,warnings:o}}var ln=["stop","aborted","timeout","cancelled","interrupted","error"],cn=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Kt(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function un(e,t){return{...e,content:[...Kt(e.content),...Kt(t.content)]}}function dn(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function pn(e){return new Set((e??ln).map(t=>t.trim().toLowerCase()))}function mn(e,t){return e?pn(t).has(e.trim().toLowerCase()):!1}function Fe(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let m=a.tool_calls.filter(h=>dn(h));return{...a,...m.length>0?{tool_calls:m}:{tool_calls:void 0}}}return{...a}}),r=new Set;for(let a of t)if(!(a.role!=="assistant"||!Array.isArray(a.tool_calls)))for(let m of a.tool_calls)typeof m.id=="string"&&m.id&&r.add(m.id);let o=t.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&r.has(a.tool_call_id))),n=new Set;for(let a of o)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&n.add(a.tool_call_id);let l=[];for(let a of o){if(a.role==="assistant"&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0){let m=a.tool_calls.filter(h=>typeof h.id=="string"&&n.has(h.id));if(m.length===0){let{tool_calls:h,...T}=a;T.content!=null&&T.content!==""&&l.push(T);continue}if(m.length<a.tool_calls.length){l.push({...a,tool_calls:m});continue}}l.push(a)}let d=[];for(let a of l){let m=d.length>0?d[d.length-1]:void 0;if(a.role==="user"&&m?.role==="user"){d[d.length-1]=un(m,a);continue}d.push(a)}return d}function Be(e,t){return mn(t?.stopReason,t?.forcedStopReasons)?e.map(r=>{if(r.role!=="assistant")return{...r};let o={...r};for(let n of cn)delete o[n];return o}):[...e]}function Ue(e,t){let r=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let l of e)l.role==="tool"&&typeof l.tool_call_id=="string"&&l.tool_call_id&&o.add(l.tool_call_id);let n=[];for(let l of e)if(n.push({...l}),!(l.role!=="assistant"||!Array.isArray(l.tool_calls)||l.tool_calls.length===0))for(let d of l.tool_calls)typeof d.id!="string"||!d.id||o.has(d.id)||(o.add(d.id),n.push({role:"tool",tool_call_id:d.id,content:r}));return n}function $e(e,t){let r=Fe(e),o=Be(r,t);return Ue(o,t)}function gn(e){let t=new Set,r=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let n of o.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&r.add(o.tool_call_id)}return[...t].filter(o=>!r.has(o))}function fn(e){let t=new Set;for(let r of e)r.role==="tool"&&typeof r.tool_call_id=="string"&&r.tool_call_id&&t.add(r.tool_call_id);return[...t]}function yn(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function je(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function fe(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function ye(e){let t=[],r=Fe(e.replayMessages);r.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=Be(r,e.options);o.some((l,d)=>l!==r[d])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let n=Ue(o,e.options);return n.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:yn({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:n,pendingToolCallIds:gn(n),completedToolCallIds:fn(n)}),recoveryActions:t}}var hn=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function He(e){return e?hn.has(e):!0}function Ge(e){return e===429||e===529}function he(e,t=500,r=32e3){let o=Math.min(t*Math.pow(2,e-1),r);return o+Math.floor(Math.random()*o*.25)}var cr={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Te(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var ne=class extends Error{constructor(r,o){super(`Model fallback triggered: ${r} -> ${o}`);this.originalModel=r;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function qe(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function ze(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let r=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=r>0?e.promptTokens/r*100:100;return e.promptTokens>=r?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:r-e.promptTokens}:{level:"ok"}}function Ke(e,t,r){let o=e.message?.toLowerCase()??"",n=e.status??0;return n===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&r.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:n>=500&&n<600?{action:"retry",reason:`server_error_${n}`}:n===429?{action:"retry",reason:"rate_limited"}:n===401||n===403?{action:"abort",reason:"auth_error"}:n===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function We(e,t,r){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,r);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function Xe(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Cn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Ye(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function X(e,t=Cn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function Ve(e,t){let r=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(r.id=t.id),t.name&&(r.name=t.name),r.arguments+=t.arguments??"",e.set(t.index,r)}function I(e,t,r,o){e?.invoke(t,r).catch(n=>{let l=n instanceof Error?n.message:String(n);o.warn(`[hook:${t}] handler failed: ${l}`)})}function Wt(e,t){let r=typeof t.message?.content=="string"?t.message.content:"",o=r?r.slice(0,2e3):void 0,n=t.details,l=typeof n?.stdout=="string"?n.stdout.slice(0,8e3):void 0,d=typeof n?.stderr=="string"?n.stderr.slice(0,4e3):void 0,a=typeof n?.exitCode=="number"?n.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:o,durationMs:t.durationMs,exitCode:a,stdout:l,stderr:d,details:n}}function Xt(e,t){if(!t.ok)return[];let r=t.details;if(!r)return[];let o=kn(r);return o?(Array.isArray(r.mediaUrls)?r.mediaUrls.filter(l=>typeof l=="string"&&l.trim().length>0):[]).map(l=>({type:"media_result",turnId:e,mediaType:o,url:l,model:typeof r.model=="string"?r.model:void 0,provider:typeof r.provider=="string"?r.provider:void 0,durationSeconds:typeof r.durationMs=="number"?r.durationMs/1e3:void 0,taskId:typeof r.taskId=="string"?r.taskId:void 0})):[]}function kn(e){let t=typeof e.type=="string"?e.type:"";if(!t)return null;if(t==="three_d_generate")return"3d";let r=t.split("_")[0];return r==="image"||r==="tts"||r==="video"||r==="music"?r:null}var Rn=new Set(["write","edit","patch","apply_patch"]);function Yt(e){let{turnId:t,result:r,toolCalls:o}=e;if(!r.ok)return[];let n=o.find(a=>a.id===r.callId);if(!n)return[];let l=[],d=bn(n.function.arguments);if(!d)return l;if(r.toolName==="plan_mode"&&d.action==="exit"&&typeof d.plan=="string"&&d.plan.length>0&&l.push({type:"plan_update",turnId:t,slug:"approved-plan",content:d.plan}),Rn.has(r.toolName)){let a=_n(d);a&&l.push({type:"artifact",turnId:t,artifactId:`artifact-${r.callId}`,artifactType:xn(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:Sn(a)})}return l}function bn(e){try{return JSON.parse(e)}catch{return null}}function _n(e){return typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:void 0}function xn(e){let t=e.split(".").pop()?.toLowerCase()??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(t)?"image":["md","txt","pdf","doc","docx","rtf","html"].includes(t)?"document":["mermaid","mmd","dot","puml","plantuml"].includes(t)?"diagram":["csv","tsv","xlsx","xls"].includes(t)?"table":["ts","tsx","js","jsx","py","rs","go","java","c","cpp","h","cs","rb","sh","sql","json","yaml","yml","toml","xml","css","scss","vue","svelte"].includes(t)?"code":"file"}function Sn(e){let t=e.split(".").pop()?.toLowerCase()??"";return{ts:"typescript",tsx:"typescriptreact",js:"javascript",jsx:"javascriptreact",py:"python",rs:"rust",go:"go",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",rb:"ruby",sh:"shellscript",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",vue:"vue",svelte:"svelte",md:"markdown"}[t]}var An=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,vn=new Set(["search","web_search","grep","glob","find","list","read","exec"]);function Vt(e){if(!vn.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&An.test(t)}function Je(e,t){for(let r=e.length-1;r>=0;r--){let o=e[r];if(!o||o.role!=="tool")continue;let n=typeof o.content=="string"?o.content:"";if(n.startsWith("Error: "))return n.slice(7).trim()}}function Jt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.round(e),100):Rt}function Zt(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function Y(e,t){let r=[];for(let o=e.length-1;o>=0;o--){let n=e[o];if(n.role==="tool"&&typeof n.content=="string")r.unshift(n.content.slice(0,500));else if(n.role==="assistant"){if(typeof n.content=="string"&&n.content.trim())return t.info("synthesizeFallbackContent: found assistant text, using it"),n.content;break}else break}return r.length>0?(t.info(`synthesizeFallbackContent: synthesized from ${r.length} tool result(s)`),r.join(`
|
|
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 Eo=/\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]},Io=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,wo=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Po=512,Lo=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Oo=new Set([500,502,503,504,521,522,523,524,529]),No=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Do=["upgrade your plan","upgrade plan","current plan","subscription"],Bo=["daily","weekly","monthly"],Fo=["try again","retry","temporary","cooldown"],Uo=["usage limit","rate limit","organization usage"],jo=["organization","workspace"],$o=["billing period","exceeded","reached","exhausted"],Ho=/["']?(?: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,Go=/^(?: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 qo(e){return K(e,q.format)}function dt(e){return K(e,q.rateLimit)}function Ko(e){return K(e,q.timeout)}function zo(e){return Eo.test(e)}function Se(e){let t=e.toLowerCase();return t?e.length>Po?wo.test(t):K(t,q.billing)?!0:Io.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function pt(e){return K(e,q.authPermanent)}function Wo(e){return K(e,q.auth)}function mt(e){return K(e,q.overloaded)}function G(e,t){return t.some(n=>e.includes(n))}function Xo(e){return G(e,No)||G(e,Do)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Yo(e){let t=G(e,Bo),n=e.includes("spend limit")||e.includes("spending limit"),o=G(e,jo);return G(e,Fo)&&G(e,Uo)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||G(e,$o))}function Vo(e){return e.trim().toLowerCase().replace(Go,"").trim()}function gt(e){let t=Vo(e);return!t||Xo(t)?"billing":dt(t)||Yo(t)?"rate_limit":"billing"}function Jo(e){return Ho.test(e)?gt(e):null}function ft(e){let t=e.match(Lo);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Qo(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Zo(e){let t=e.trim();if(!t)return!1;let n=ft(t);return n?Oo.has(n.code):!1}function yt(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?gt(t):"billing":e===429?"rate_limit":e===401||e===403?t&&pt(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&mt(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&Se(t)?"billing":"format":null}function en(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 tn(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function Tt(e){if(tn(e))return"session_expired";if(en(e))return"model_not_found";let t=Jo(e);return t||(zo(e)?Se(e)?"billing":"rate_limit":dt(e)?"rate_limit":mt(e)?"overloaded":Zo(e)?ft(e.trim())?.code===529?"overloaded":"timeout":Qo(e)?"timeout":qo(e)?"format":Se(e)?"billing":Ko(e)?"timeout":pt(e)?"auth_permanent":Wo(e)?"auth":null)}var on={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"},nn=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function W(e,t){let n=yt(e,t)??(t?Tt(t):null);return n?on[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Me(e){return nn.has(e)}function ht(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var rn=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=ht){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||!rn.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=ht){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=Ct(e,t),c=sn(i,t,o);if(c.length===0)return{messages:i,stagedCount:0};for(let s of c)t.stages.push(s);return i=Ct(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:kt(e,t),committed:n}}function Ct(e,t){return t.stages.filter(o=>o.committed).length===0?e:kt(e,t)}function kt(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 sn(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 f=`${c}-${c+s}`;i.has(f)||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 Pe,readFileSync as jt,writeFileSync as an,readdirSync as $t,mkdirSync as ln}from"node:fs";import{join as Le,dirname as cn}from"node:path";var Rt=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),bt=3,xt=2,de=2,_t=128e3,St=13e3,Mt=16384,At=65536,vt=3,Et=65536,we=500,It=3;var wt=3e4,Pt=3,X=2;var Lt=20;var Ot=3,Nt=2,Dt=300*1e3,Bt=3,Ft=720*60*60*1e3;var dr=300*1e3;var pr=3600*1e3;var mr=50*1024,gr=500*1024,fr=500*1024*1024,yr=50*1024*1024;var Tr=60*1024;var Ht=0;var un="skill-patterns.json";function Gt(e){return Le(e,".qlogicagent",un)}function dn(e){let t=Gt(e);try{return JSON.parse(jt(t,"utf8"))}catch{return{version:1,patterns:{}}}}function Ut(e,t){let n=Gt(e);ln(cn(n),{recursive:!0}),an(n,JSON.stringify(t,null,2),"utf8")}function pn(e){let t=Date.now()-Ft;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function qt(e,t){if(t.length===0)return!1;let n=pe(t),o=dn(e);pn(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 Ut(e,o),!1;i.count++,i.lastSeen=r;let c=i.count>=Bt;return c&&(i.promoted=!0),Ut(e,o),c}function pe(e){return[...e].sort().join("+")}function mn(e,t){if(!Pe(t))return null;let n=pe(e);try{let o=$t(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let i=Le(t,r.name,"SKILL.md");try{let s=jt(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 gn(e){if(!Pe(e))return 0;try{return $t(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&Pe(Le(e,t.name,"SKILL.md"))).length}catch{return 0}}function fn(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<Ot||e.distinctToolCount<Nt||Date.now()-Ht<Dt||t?.projectSkillsDir&&(gn(t.projectSkillsDir)>=Lt||t.tools.length>0&&mn(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!qt(t.projectRoot,t.tools))}function yn(e){return e.existingSkillName?e.feedback==="negative":!1}function Oe(e,t){return yn(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:fn(e,t)?(Ht=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function Kt(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function Tn(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function hn(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Cn(e){if(!e.eligibility?.length)return[...e.tools];let t=hn(e.eligibility);return e.tools.filter(n=>{let o=Kt(n);if(!o)return!1;let r=t.get(o);return!r||Tn(r.status)})}function kn(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=kn({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Cn({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=>Kt(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 Rn=["stop","aborted","timeout","cancelled","interrupted","error"],bn=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function zt(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function xn(e,t){return{...e,content:[...zt(e.content),...zt(t.content)]}}function _n(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 Sn(e){return new Set((e??Rn).map(t=>t.trim().toLowerCase()))}function Mn(e,t){return e?Sn(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=>_n(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,...m}=s;m.content!=null&&m.content!==""&&i.push(m);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]=xn(d,s);continue}c.push(s)}return c}function Be(e,t){return Mn(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of bn)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 An(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 vn(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 En(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:En({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:An(r),completedToolCallIds:vn(r)}),recoveryActions:t}}var In=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function $e(e){return e?In.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 Er={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 Wt(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 Xt(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=Ln(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 Ln(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 On=new Set(["write","edit","patch"]);function Yt(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=Nn(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}),On.has(n.toolName)){let s=Dn(c);s&&i.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:Bn(s),title:s.split(/[\\/]/).pop()||s,filePath:s,language:Fn(s)})}return i}function Nn(e){try{return JSON.parse(e)}catch{return null}}function Dn(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 Bn(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 Fn(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 jn=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,$n=new Set(["search","web_search","grep","glob","find","list","read","exec"]);function Vt(e){if(!$n.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&jn.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 Jt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.round(e),100):Rt}function Qt(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(`
|
|
3
3
|
|
|
4
|
-
`)):""}function Qt(e){try{let t=JSON.parse(e),o=[t.description,t.command,t.query,t.url,t.path,t.file_path,t.filePath,t.pattern,t.model].find(l=>typeof l=="string"&&l.trim().length>0);if(typeof o=="string")return o.trim().slice(0,240);let n=Object.keys(t);return n.length>0?n.slice(0,5).join(" / "):void 0}catch{return}}function Ze(e){let t=e.message.toLowerCase();return e.status===413||t.includes("prompt_too_long")||t.includes("context_length_exceeded")||t.includes("maximum context length")}function eo(e){return e==="length"||e==="max_tokens"}function Qe(e){let t=e.message.toLowerCase();return(t.includes("image")||t.includes("media")||t.includes("file too large")||t.includes("payload too large"))&&(e.status===413||t.includes("too large")||t.includes("size"))}function to(e){let t=e.headers;if(!t)return null;let r=t["retry-after"]??t["Retry-After"];if(!r)return null;let o=parseInt(r,10);return!isNaN(o)&&o>0?o*1e3:null}function oo(e){if(e.status!==400)return null;let t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!t?.[1]||!t?.[3])return null;let r=parseInt(t[1],10),o=parseInt(t[3],10);if(isNaN(r)||isNaN(o))return null;let n=o-r-1e3;return n>=3e3?n:null}async function*no(e,t,r,o,n,l,d,a){let m=[],h;a.debug(`single LLM round, messages: ${r.length}`);for await(let T of d.stream({model:t,messages:r,temperature:n},o,l))switch(T.type){case"delta":m.push(T.text),yield{type:"delta",turnId:e,text:T.text};break;case"usage":h={inputTokens:T.promptTokens,outputTokens:T.completionTokens,reasoningTokens:T.reasoningTokens,cacheRead:T.cacheReadTokens,cacheWrite:T.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:e,content:m.join(""),usage:h??{inputTokens:0,outputTokens:0},model:t}}async function*ro(e,t,r,o){let{turnId:n,sessionId:l,messages:d,tools:a,model:m,apiKey:h,temperature:T=0,hooks:k,signal:H}=e,M={sessionId:l,turnId:n},R=e.maxTurns??0,L=e.querySource,b=e.runtimePorts.resolveToolEligibility(a,e.toolEligibilityContext),D=b.eligibleTools;for(let f of b.blockedTools)yield{type:"tool_blocked",turnId:n,callId:"",name:f.toolName,reason:"blocked-by-policy"};if(!D.length){yield*no(n,m,d,h,T,H,t,o);return}let j=Jt(e.maxRounds),F={contextWindowTokens:e.contextWindowTokens??xt,responseBufferTokens:St,maxOutputTokens:e.maxOutputTokens??Mt,abortSignal:H,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},_=new Set,C=0,A=D,re,Ce=!1,et=0,s={messages:[...d],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:qe(F),reactiveCompactState:Ye(),toolLoopState:ye({maxRounds:j,replayMessages:[...d]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:Ie(),currentModel:m,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,toolFailureCounts:new Map,fileReadCounts:new Map},tt=Math.max(R*5,200),ot=0;for(;;){if(ot++,ot>tt){o.info(`hard iteration cap reached (${tt}), forcing completion`);let i=s.finalText||Y(s.messages,o);yield{type:"end",turnId:n,content:i,usage:s.totalUsage,model:s.currentModel};return}let{messages:f,maxOutputTokensRecoveryCount:V,hasAttemptedReactiveCompact:Bn,maxOutputTokensOverride:nt,turnCount:J,guardState:x,reactiveCompactState:$,collapseStore:ke}=s,{toolLoopState:P}=s;if(re){try{let i=await re;i&&(yield{type:"tool_use_summary",turnId:n,summary:i})}catch{}re=void 0}if(e.refreshTools&&J>1){let i=e.refreshTools();i!==A&&(A=i,o.debug(`tools refreshed: ${i.length} tools`))}if(Xe(x,F)){o.info(`turn aborted by guard at turn ${J}`),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED",usage:s.totalUsage};return}let G=ze(x,F);if(G.level==="blocking"){G.reason==="prompt_too_long"&&X($)&&($.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${G.reason}), reactive compact needed`),yield{type:"recovery",turnId:n,action:"reactive_compact",detail:"token budget pre-check"}),o.info(`token budget blocking (${G.reason}), ending tool loop`);break}G.level==="warning"&&o.info(`token budget warning: ${G.usagePercent}% used, ${G.remainingTokens} remaining`);let S;{let i=await e.runtimePorts.enforceToolResultBudget(f,s.contentReplacementState,l);S=i.messages,i.newlyReplacedCount>0&&(o.info(`tool-result-budget: persisted ${i.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:n,action:"tool_result_budget",detail:`${i.newlyReplacedCount} persisted`})}{let i=Ee(S,s.snipRemovedIds);S=i.messages,i.removedCount>0&&(o.info(`snip: removed ${i.removedCount} messages, freed ~${i.tokensFreed} tokens`),yield{type:"recovery",turnId:n,action:"snip",detail:`${i.removedCount} messages`})}{let c=new te().compress(S,0);c.droppedCount>0&&(S=c.messages,o.info(`microcompact: cleared ${c.droppedCount} old tool results`))}if(S=we(S,ke).messages,x.promptTokens>0){let i=F.contextWindowTokens*.75,c=e.runtimePorts.getActiveContextCompressionEngine(),u;c?u=await c.compressAsync(S,i,{model:s.currentModel,sessionId:l}):u=e.runtimePorts.compressMessages(S,{budget:i,model:s.currentModel}),u.droppedCount>0&&(S=u.messages,o.info(`autocompact: ${u.strategy}, dropped ${u.droppedCount}`),yield{type:"recovery",turnId:n,action:"autocompact",detail:`${u.strategy}: ${u.droppedCount} dropped`},s.hasAttemptedReactiveCompact=!1,I(k,"context.after_compact",{...M,removedCount:u.droppedCount},o))}S=Zt(S);let uo=e.toolChoice==="required"&&Ce?"auto":e.toolChoice??"auto",se=De({tools:A,toolChoice:uo}),Z=ye({maxRounds:j,replayMessages:S,lastStopReason:P.lastStopReason,options:{stopReason:P.lastStopReason}}),rt=se.extraSystemPrompt?[{role:"system",content:se.extraSystemPrompt},...Z.state.replayMessages]:Z.state.replayMessages;P=Z.state,Z.recoveryActions.length>0&&o.debug(`tool loop recovery: ${Z.recoveryActions.map(i=>i.detail??i.kind).join("; ")}`),o.debug(`turn ${J}, messages: ${rt.length}`),I(k,"turn.before_inference",{...M,model:s.currentModel},o);let Re=!1,be=[],st=new Map,it="stop",O,y=null,ie=!1,Q=[],w=[];try{for await(let i of t.stream({model:s.currentModel,messages:rt,tools:se.tools,toolChoice:se.normalizedToolChoice??"auto",temperature:T,maxTokens:(nt??x.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:s.lastResponseId,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},h,H))switch(i.type){case"delta":be.push(i.text);break;case"tool_call_delta":Re=!0,Ve(st,i);break;case"reasoning_delta":Q.push(i.text);break;case"reasoning_block_complete":i.signature&&w.push({thinking:Q.join(""),signature:i.signature}),Q.length=0;break;case"usage":O={inputTokens:i.promptTokens,outputTokens:i.completionTokens,reasoningTokens:i.reasoningTokens,cacheRead:i.cacheReadTokens,cacheWrite:i.cacheCreationTokens};break;case"response_id":s.lastResponseId=i.id;break;case"annotations":yield{type:"annotations",turnId:n,annotations:i.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:n,message:`${i.toolType}: ${i.event}`};break;case"done":it=i.finishReason;break}if(Re||I(k,"turn.after_inference",{...M,model:s.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let i=s.currentModel;for(let c of e.postSamplingHooks)try{c({messages:[...S],model:i,sessionId:l})}catch{}}}catch(i){if(i instanceof ne&&e.fallbackModel){o.info(`model fallback triggered: ${i.originalModel} -> ${i.fallbackModel}`),yield{type:"recovery",turnId:n,action:"model_fallback",detail:`${i.originalModel} -> ${i.fallbackModel}`},s={...s,currentModel:i.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let c=i instanceof Error?i.message:String(i),u=typeof i?.status=="number"?i.status:void 0;if(!u&&c&&(c.includes("ECONNRESET")||c.includes("EPIPE"))){let g=(s.consecutiveApiRetries??0)+1;if(g>oe){o.info(`stale connection retry limit reached (${oe}), aborting`),yield{type:"error",turnId:n,error:c,code:"RETRIES_EXHAUSTED",usage:s.totalUsage};return}o.info(`stale connection (${c.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:n,action:"stale_connection_retry",detail:c.slice(0,80)},s={...s,consecutiveApiRetries:g,transition:void 0};continue}let p=oo({status:u,message:c});if(p!==null){o.info(`max_tokens overflow: adjusting to ${p}`),x.currentMaxOutputTokens=p,s={...s,maxOutputTokensOverride:p,transition:void 0};continue}if(Ge(u)){s.consecutive529Errors++;let g=2,v=e.fallbackModel&&s.currentModel!==e.fallbackModel;if(s.consecutive529Errors>g&&!v&&!Te()){o.info(`transient ${u} \u8133 ${s.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:n,error:`API unavailable after ${s.consecutive529Errors} consecutive ${u} errors`,code:"API_ERROR",usage:s.totalUsage};return}if(s.consecutive529Errors>=Lt&&e.fallbackModel&&s.currentModel!==e.fallbackModel){o.info(`529 \u8133 ${s.consecutive529Errors}: triggering fallback to ${e.fallbackModel}`),yield{type:"recovery",turnId:n,action:"model_fallback",detail:`529 \u8133 ${s.consecutive529Errors}`},s={...s,currentModel:e.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(Te()){let E=he(s.consecutive529Errors);o.info(`persistent retry: waiting ${E}ms (attempt ${s.consecutive529Errors})`);let N=E;for(;N>0;){if(H?.aborted){yield{type:"error",turnId:n,error:"Aborted during retry wait",code:"ABORTED",usage:s.totalUsage};return}yield{type:"heartbeat",turnId:n,message:`Retrying in ${Math.ceil(N/1e3)}s (${u})`};let U=Math.min(N,wt);await new Promise(Se=>setTimeout(Se,U)),N-=U}s={...s,transition:void 0};continue}if(He(L)){let N=to({status:u,message:c})??he(s.consecutive529Errors);o.info(`transient ${u}: retry in ${N}ms`),yield{type:"recovery",turnId:n,action:"retry",detail:`${u} retry in ${N}ms`},await new Promise(U=>setTimeout(U,N)),s={...s,transition:void 0};continue}o.info(`background source ${L}: not retrying ${u}`)}y={status:u,message:c}}if(y&&I(k,"turn.after_inference",{...M,model:s.currentModel,response:{error:y.message}},o),y)if(Ze(y))ie=!0,o.info(`withheld prompt_too_long error (status=${y.status})`);else if(Qe(y))ie=!0,o.info(`withheld media_size error (status=${y.status})`);else{let i=Ke({status:y.status??500,message:y.message},x,F);if(i.action==="reactive_compact"&&X($)&&($.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:n,action:"reactive_compact",detail:`API ${y.status??500}: ${y.message}`}),i.action==="retry"){let u=(s.consecutiveApiRetries??0)+1;if(u>oe){o.info(`API retry limit reached (${oe}), aborting`);let p=W(y.status,y.message);yield{type:"error",turnId:n,error:y.message,code:p,usage:s.totalUsage};return}yield{type:"recovery",turnId:n,action:"retry",detail:i.reason},s={...s,consecutiveApiRetries:u,transition:void 0};continue}let c=W(y.status,y.message);I(k,"stop.failure",{sessionId:l,reason:c,error:y.message},o),yield{type:"error",turnId:n,error:y.message,code:c,usage:s.totalUsage};return}O&&(s.totalUsage.inputTokens+=O.inputTokens,s.totalUsage.outputTokens+=O.outputTokens,O.reasoningTokens&&(s.totalUsage.reasoningTokens=(s.totalUsage.reasoningTokens??0)+O.reasoningTokens),O.cacheRead&&(s.totalUsage.cacheRead=(s.totalUsage.cacheRead??0)+O.cacheRead),O.cacheWrite&&(s.totalUsage.cacheWrite=(s.totalUsage.cacheWrite??0)+O.cacheWrite)),O?.inputTokens&&(x.promptTokens=O.inputTokens);let at=be.join(""),B=[...st.values()].map(i=>({id:i.id||`tc_${n}_${J}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:i.name,arguments:i.arguments}}));if(B.length===0&&!Re){if(at&&(s.finalText=at),e.toolChoice==="required"&&!Ce&&A.length>0&&et<2){et++;let u=A.map(p=>p.function.name).filter(Boolean).slice(0,8).join(", ");s={...s,messages:[...f,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${u}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(ie&&y&&Ze(y)){if(s.transition?.reason!=="collapse_drain_retry"){let u=Le(S,ke);if(u.committed>0){o.info(`collapse drain: committed ${u.committed} stages`),yield{type:"recovery",turnId:n,action:"collapse_drain",detail:`${u.committed} stages committed`},s={...s,messages:u.messages,transition:{reason:"collapse_drain_retry",committed:u.committed}};continue}}if(X($)){$.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:n,action:"reactive_compact",detail:"withheld prompt_too_long"},s={...s,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),I(k,"stop.failure",{sessionId:l,reason:"prompt_too_long",error:y.message},o),yield{type:"error",turnId:n,error:y.message,code:"PROMPT_TOO_LONG",usage:s.totalUsage};return}if(ie&&y&&Qe(y)){if(X($)){$.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:n,action:"reactive_compact",detail:"media error strip-retry"},s={...s,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),I(k,"stop.failure",{sessionId:l,reason:"media_error",error:y.message},o),yield{type:"error",turnId:n,error:y.message,code:"IMAGE_ERROR",usage:s.totalUsage};return}if(eo(it)){x.consecutiveTruncations+=1;let u=e.modelMaxOutputTokens??At,p=We(x,F,u);if(p.shouldEscalate&&nt===void 0){x.currentMaxOutputTokens=p.newMax,o.info(`max_output_tokens escalate: ${p.newMax} tokens`),yield{type:"recovery",turnId:n,action:"output_escalation",detail:`${p.newMax} tokens`},s={...s,maxOutputTokensOverride:Et,transition:{reason:"max_output_tokens_escalate"}};continue}if(V<vt){let g={role:"user",content:"Output token limit hit. Resume directly - no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};o.info(`max_output_tokens recovery #${V+1}`),yield{type:"recovery",turnId:n,action:"max_output_tokens_recovery",detail:`attempt ${V+1}`},s={...s,messages:[...S,g],maxOutputTokensRecoveryCount:V+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:V+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else x.consecutiveTruncations=0;if(P=fe(P,{replayMessages:f,lastStopReason:"completed"}),k){let u=await k.invoke("stop",{sessionId:l,reason:"completed"});if(u.action==="prevent"){o.info(`stop hook prevented continuation: ${u.reason??"no reason"}`),yield{type:"end",turnId:n,content:s.finalText,usage:s.totalUsage,model:s.currentModel};return}if(u.action==="abort"){let p=u.reason??"Stop hook requested continuation";o.info(`stop hook blocking: ${p}`);let g={role:"user",content:p},v={role:"assistant",content:s.finalText,...w.length>0&&{thinkingBlocks:[...w]}};s={...s,messages:[...f,v,g],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(e.tokenBudget&&e.tokenBudget>0&&s.budgetContinuationCount<5){let u=s.totalUsage.inputTokens+s.totalUsage.outputTokens+(s.totalUsage.reasoningTokens??0),p=u/e.tokenBudget*100,g=u-s.lastBudgetGlobalTokens,v=s.budgetContinuationCount>=It&&g<Pe&&s.lastBudgetDeltaTokens<Pe;if(v&&o.info(`token budget early stop: diminishing returns at ${Math.round(p)}% (delta=${g})`),!v&&p<90){let E=s.budgetContinuationCount+1,N={role:"user",content:e.runtimePorts.getBudgetContinuationMessage(p,u,e.tokenBudget)};o.info(`token budget continuation #${E}: ${Math.round(p)}% used`),yield{type:"recovery",turnId:n,action:"budget_continuation",detail:`${Math.round(p)}% used (#${E})`};let U={role:"assistant",content:s.finalText,...w.length>0&&{thinkingBlocks:[...w]}};s={...s,messages:[...f,U,N],budgetContinuationCount:E,lastBudgetDeltaTokens:g,lastBudgetGlobalTokens:u,transition:{reason:"token_budget_continuation"}};continue}}if(!s.stopHookActive){let u=d.find(E=>E.role==="user"),p=typeof u?.content=="string"?u.content:"",g=/create\s+(?:a\s+)?file|write\s+(?:a\s+)?file|make\s+(?:a\s+)?file|fix|implement|modify|update|repair|generate\s+(?:a\s+)?file|new\s+file/i.test(p),v=_.has("write")||_.has("edit");if(g&&!v){if(o.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),C>0){let U=[...f].reverse().find(Se=>Se.role==="tool");U&&typeof U.content=="string"&&(U.content+=`
|
|
4
|
+
`)):""}function Zt(e){try{let t=JSON.parse(e),o=[t.description,t.command,t.query,t.url,t.path,t.file_path,t.filePath,t.pattern,t.model].find(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 eo(e){return e==="length"||e==="max_tokens"}function Qe(e){let t=e.message.toLowerCase();return(t.includes("image")||t.includes("media")||t.includes("file too large")||t.includes("payload too large"))&&(e.status===413||t.includes("too large")||t.includes("size"))}function to(e){let t=e.headers;if(!t)return null;let 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 oo(e){if(e.status!==400)return null;let t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!t?.[1]||!t?.[3])return null;let 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*no(e,t,n,o,r,i,c,s){let d=[],g;s.debug(`single LLM round, messages: ${n.length}`);for await(let m of c.stream({model:t,messages:n,temperature:r},o,i))switch(m.type){case"delta":d.push(m.text),yield{type:"delta",turnId:e,text:m.text};break;case"usage":g={inputTokens:m.promptTokens,outputTokens:m.completionTokens,reasoningTokens:m.reasoningTokens,cacheRead:m.cacheReadTokens,cacheWrite:m.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:e,content:d.join(""),usage:g??{inputTokens:0,outputTokens:0},model:t}}async function*ro(e){let{messages:t,contentReplacementState:n,snipRemovedIds:o,collapseStore:r,guardState:i,guardConfig:c,runtimePorts:s,hooks:d,hookCtx:g,sessionId:m,currentModel:f,log:b,recovery:h,onAutocompact:x}=e,C;{let p=await s.enforceToolResultBudget(t,n,m);C=p.messages,p.newlyReplacedCount>0&&(b.info(`tool-result-budget: persisted ${p.newlyReplacedCount} oversized tool results`),yield h("tool_result_budget",`${p.newlyReplacedCount} persisted`))}{let p=Ae(C,o);C=p.messages,p.removedCount>0&&(b.info(`snip: removed ${p.removedCount} messages, freed ~${p.tokensFreed} tokens`),yield h("snip",`${p.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 p=c.contextWindowTokens*.75,_=s.getActiveContextCompressionEngine(),S;_?S=await _.compressAsync(C,p,{model:f,sessionId:m}):S=s.compressMessages(C,{budget:p,model:f}),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=Qt(C),C}async function*so(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 m=e instanceof Error?e.message:String(e),f=typeof e?.status=="number"?e.status:void 0;if(!f&&m&&(m.includes("ECONNRESET")||m.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:m,code:"RETRIES_EXHAUSTED",usage:n.totalUsage},{kind:"return"}):(d.info(`stale connection (${m.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield g("stale_connection_retry",m.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:h,transition:void 0}})}let b=oo({status:f,message:m});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(f)){n.consecutive529Errors++;let h=2,x=r&&n.currentModel!==r;if(n.consecutive529Errors>h&&!x&&!ye())return d.info(`transient ${f} \u8133 ${n.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:s,error:`API unavailable after ${n.consecutive529Errors} consecutive ${f} 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 p=C;for(;p>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(p/1e3)}s (${f})`};let _=Math.min(p,wt);await new Promise(S=>setTimeout(S,_)),p-=_}return{kind:"continue",patch:{transition:void 0}}}if($e(c)){let p=to({status:f,message:m})??fe(n.consecutive529Errors);return d.info(`transient ${f}: retry in ${p}ms`),yield g("retry",`${f} retry in ${p}ms`),await new Promise(_=>setTimeout(_,p)),{kind:"continue",patch:{transition:void 0}}}d.info(`background source ${c}: not retrying ${f}`)}return{kind:"streamError",streamError:{status:f,message:m}}}var Hn=/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 io(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Gn(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 qn(e){let t=[...e].reverse().find(n=>n.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
|
|
5
5
|
|
|
6
|
-
\u923F\u72C5\u7B0D NOTE: You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail silently or produce incorrect results on this platform. Please use the 'write' tool directly to create the requested file with the correct content.`)}let E={role:"user",content:C===0?"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes - actually make them.":"You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail on this platform. Please use the write tool directly to create the requested file with the correct content."},N={role:"assistant",content:s.finalText,...w.length>0&&{thinkingBlocks:[...w]}};s={...s,messages:[...f,N,E],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(!s.stopHookActive&&C>=3&&_.has("write")){let u=0;for(let p of f){let g=p,v=g.is_error===!0||typeof g.content=="string"&&g.content.startsWith("Error:");g.role==="tool"&&typeof g.content=="string"&&!v&&u++}if(u>=3){o.info("AP3 verification nudge: 3+ files created, injecting completeness check");let p={role:"user",content:"You created multiple files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. If everything is correct, confirm completion. If not, fix the issues now."},g={role:"assistant",content:s.finalText,...w.length>0&&{thinkingBlocks:[...w]}};s={...s,messages:[...f,g,p],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(C>0){let u={ok:!0,toolCallCount:C,distinctToolCount:_.size,multiStep:C>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},p=ge(u,{tools:[..._],projectRoot:e.projectRoot});p&&(yield{type:"skill_instruction",turnId:n,instruction:p})}let c=s.finalText||Y(f,o);for(let u of be)yield{type:"delta",turnId:n,text:u};yield{type:"end",turnId:n,content:c,usage:s.totalUsage,model:s.currentModel};return}let po=w.length===0&&Q.length>0?Q.join(""):void 0;f.push(Me(B,void 0,w.length>0?w:void 0,po)),P=je(P,{replayMessages:f,pendingToolCallIds:B.map(i=>i.id),completedToolCallIds:P.completedToolCallIds,lastStopReason:"tool_calls"});let ae=s.identicalCallCounts,lt=[],le=[],ct=!1;for(let i of B){let c=`${i.function.name}::${i.function.arguments}`,u=ae.get(c)??0;ae.set(c,u+1),u+1>_t?(le.push(i),ct||(ct=!0,o.info(`AP4 blocked: ${i.function.name} repeated ${u+1}x`))):lt.push(i)}let ce=[];for(let i of le){let c=ae.get(`${i.function.name}::${i.function.arguments}`),u=Je(f,i.function.name),p=u?`This exact tool call has been attempted ${c} times. Last error: ${u}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${c} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,g=de(i.id,{ok:!1,error:p});f.push(g),ce.push(i.id),_.add(i.function.name),C++,yield{type:"tool_result",turnId:n,callId:i.id,name:i.function.name,ok:!1,error:p}}if(le.length>0){let i=Je(f,le[0].function.name),c={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(i?`The error was: "${i}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};f.push(c)}let ue=[],_e=[];for(let i of lt)(s.toolFailureCounts.get(i.function.name)??0)>=pe?_e.push(i):ue.push(i);if(_e.length>0){for(let c of _e){let u=s.toolFailureCounts.get(c.function.name),p=`Tool "${c.function.name}" has failed ${u} times this turn with different arguments. The target likely does not exist. Stop trying variations and report the issue to the user.`,g=de(c.id,{ok:!1,error:p});f.push(g),ce.push(c.id),_.add(c.function.name),C++,yield{type:"tool_result",turnId:n,callId:c.id,name:c.function.name,ok:!1,error:p},o.info(`AP4-variant blocked: ${c.function.name} failed ${u}x with different args`)}let i={role:"user",content:"Tool calls were blocked because the tool has failed too many times with different arguments. The resource you are looking for does not exist. Stop trying variations and tell the user what happened."};f.push(i)}for(let i of ue){let c=i.function.arguments,u=A.find(p=>p.function.name===i.function.name);if(u?.backfillObservableInput)try{let p=JSON.parse(i.function.arguments),g={...p};u.backfillObservableInput(g),Object.keys(g).some(E=>!(E in p))&&(c=JSON.stringify(g))}catch{}yield{type:"tool_call",turnId:n,callId:i.id,name:i.function.name,arguments:c,inputSummary:Qt(c)}}let mo=new Map(s.toolFailureCounts);try{let i=e.runtimePorts.createStreamingToolExecutor({toolInvoker:r,hooks:k,sessionId:l,turnId:n,log:o,signal:H,maxConcurrentTools:e?.maxConcurrentTools});for(let c of ue)i.addTool(c);for await(let c of i.getRemainingResults()){c.blocked&&(yield{type:"tool_blocked",turnId:n,callId:c.callId,name:c.toolName,reason:c.blockReason??"blocked"}),f.push(c.message),ce.push(c.callId),_.add(c.toolName),C++;let u=c.ok&&Vt(c);if(!c.ok||u){let g=(s.toolFailureCounts.get(c.toolName)??0)+1;s.toolFailureCounts.set(c.toolName,g)}if(c.ok&&c.toolName==="read"){let p=ue.find(g=>g.id===c.callId);if(p)try{let g=JSON.parse(p.function.arguments),v=g.file_path??g.path??g.filePath??"";if(v){let E=s.fileReadCounts.get(v)??0;s.fileReadCounts.set(v,E+1)}}catch{}}yield Wt(n,c);for(let p of Xt(n,c))yield p;for(let p of Yt({turnId:n,result:c,toolCalls:B}))yield p}}catch(i){let c=i instanceof Error?i.message:String(i);yield{type:"error",turnId:n,error:c,code:"TOOL_EXECUTION_ERROR",usage:s.totalUsage};return}for(let[i,c]of s.toolFailureCounts)c>=pe&&(mo.get(i)??0)<pe&&f.push({role:"user",content:`Tool "${i}" has now failed/returned empty results ${c} times with different arguments. The target clearly does not exist. Do NOT call "${i}" again. Report the result to the user immediately.`});if(P=fe(P,{replayMessages:f,completedToolCallIds:[...P.completedToolCallIds,...ce],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&B.length>0&&(Ce=!0),e.generateToolUseSummary&&B.length>0){let i=B.map(c=>({name:c.function.name,arguments:c.function.arguments}));re=e.generateToolUseSummary(i).catch(()=>null)}let go=B.length>0&&B.every(i=>{let c=f.find(p=>p?.role==="tool"&&p?.tool_call_id===i.id);if(!c)return!0;let u=c.content;return typeof u=="string"&&u.startsWith("Error: ")}),ee=s.consecutiveFailedRounds;if(go){if(ee+=1,ee>=bt){let i=s.finalText||Y(f,o);o.info(`early exit: ${ee} consecutive failed rounds, returning ${s.finalText?"partial":"fallback"} response`),yield{type:"end",turnId:n,content:i,usage:s.totalUsage,model:s.currentModel};return}}else ee=0;let fo=3,ut=[...s.fileReadCounts.entries()].filter(([,i])=>i>=fo);if(ut.length>0){let i=ut.map(([u])=>u).join(", ");o.info(`AP5: file read cycle detected on ${i}, injecting nudge`);let c={role:"user",content:`You are reading the same files repeatedly (${i}). This indicates a circular dependency or cycle. Stop reading files, summarize your findings so far, and explain the circular structure to the user.`};f.push(c),s.fileReadCounts.clear()}let xe=J+1;if(R>0&&xe>R){if(o.info(`max turns reached (${R}), completing`),k){let c=await k.invoke("stop",{sessionId:l,reason:"max_turns"});if(c.action==="abort"){let u=c.reason??"Stop hook requested continuation after max_turns",p={role:"assistant",content:s.finalText,...w.length>0&&{thinkingBlocks:[...w]}};s={...s,messages:[...f,p,{role:"user",content:u}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let i=s.finalText||Y(f,o);yield{type:"end",turnId:n,content:i,usage:s.totalUsage,model:s.currentModel};return}if(xe>j){if(o.info(`tool loop budget exhausted (${j} rounds), returning`),C>0){let c={ok:!0,toolCallCount:C,distinctToolCount:_.size,multiStep:C>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},u=ge(c,{tools:[..._],projectRoot:e.projectRoot});u&&(yield{type:"skill_instruction",turnId:n,instruction:u})}let i=s.finalText||Y(f,o);yield{type:"end",turnId:n,content:i,usage:s.totalUsage,model:s.currentModel};return}s={messages:f,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:xe,transition:{reason:"next_turn"},guardState:x,reactiveCompactState:$,toolLoopState:P,consecutiveFailedRounds:ee,finalText:s.finalText,totalUsage:s.totalUsage,collapseStore:ke,currentModel:s.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:s.stopHookActive,lastResponseId:s.lastResponseId,snipRemovedIds:s.snipRemovedIds,contentReplacementState:s.contentReplacementState,budgetContinuationCount:s.budgetContinuationCount,lastBudgetDeltaTokens:s.lastBudgetDeltaTokens,lastBudgetGlobalTokens:s.lastBudgetGlobalTokens,identicalCallCounts:ae,toolFailureCounts:s.toolFailureCounts,fileReadCounts:s.fileReadCounts}}}var In=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function ao(e){let t=wn(e),r=["[Recalled memories]","- L1 project MD is project-scoped working memory.","- L2 long-term memory is cross-project canonical memory.","- If L1 and L2 conflict on the same entity/fact, do not silently merge or choose. Surface the conflict and ask the user to confirm. For current-project operational tasks, use L1 only as a project-scoped clue until confirmed into L2."];if(t.length>0){r.push("[Memory conflict detected]");for(let o of t)r.push(`- entity: ${o.entity}; fact: ${o.predicate}; L1 project MD says: ${io(o.l1Amount)}; L2 long-term says: ${io(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let n=On(o);r.push(`- [${n}] ${o.text}`)}return r.join(`
|
|
7
|
-
`)}function
|
|
8
|
-
${
|
|
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 ao(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function lo(e){if(e.stopHookActive)return null;let t=e.inputMessages.find(i=>i.role==="user"),n=typeof t?.content=="string"?t.content:"",o=Hn.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&&qn(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 ao("file_action_verification",e.messages,io(e.finalText,e.thinkingBlocks),i)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(Gn).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 ao("multi_file_skeleton_verification",e.messages,io(e.finalText,e.thinkingBlocks),c)}return null}function Kn(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function co(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,Kn(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var zn=5;function Wn(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function Xn(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function uo(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=zn)return null;let t=Wn(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=It&&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,Xn(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 po(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 mo(){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 go(e){if(e.ok&&!e.softEmpty)return;let t=e.toolFailureCounts.get(e.toolName)??0;e.toolFailureCounts.set(e.toolName,t+1)}function fo(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*yo(e,t,n,o){let{turnId:r,sessionId:i,messages:c,tools:s,model:d,apiKey:g,temperature:m=0,hooks:f,signal:b}=e,h={sessionId:i,turnId:r},x=e.maxTurns??0,C=e.querySource,p=e.runtimePorts.resolveToolEligibility(s,e.toolEligibilityContext),_=p.eligibleTools;for(let y of p.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:y.toolName,reason:"blocked-by-policy"};if(!_.length){yield*no(r,d,c,g,m,b,t,o);return}let S=Jt(e.maxRounds),F={contextWindowTokens:e.contextWindowTokens??_t,responseBufferTokens:St,maxOutputTokens:e.maxOutputTokens??Mt,abortSignal:b,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},U=new Set,N=0,E=_,ne,Te=!1,et=0,a={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,P=(y,$)=>(a.recoveryTrace.set(y,(a.recoveryTrace.get(y)??0)+1),{type:"recovery",turnId:r,action:y,detail:$}),z=y=>({type:"end",turnId:r,content:y,usage:a.totalUsage,model:a.currentModel,...a.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(a.recoveryTrace)}:{}});for(;;){if(ot++,ot>tt){o.info(`hard iteration cap reached (${tt}), forcing completion`);let l=a.finalText||V(a.messages,o);yield z(l);return}let{messages:y,maxOutputTokensRecoveryCount:$,maxOutputTokensOverride:nt,turnCount:J,guardState:A,reactiveCompactState:D,collapseStore:he}=a,{toolLoopState:I}=a;if(ne){try{let l=await ne;l&&(yield{type:"tool_use_summary",turnId:r,summary:l})}catch{}ne=void 0}if(e.refreshTools&&J>1){let l=e.refreshTools();l!==E&&(E=l,o.debug(`tools refreshed: ${l.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:a.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 P("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*ro({messages:y,contentReplacementState:a.contentReplacementState,snipRemovedIds:a.snipRemovedIds,collapseStore:he,guardState:A,guardConfig:F,runtimePorts:e.runtimePorts,hooks:f,hookCtx:h,sessionId:i,currentModel:a.currentModel,log:o,recovery:P,onAutocompact:()=>{a.hasAttemptedReactiveCompact=!1}}),xo=e.toolChoice==="required"&&Te?"auto":e.toolChoice??"auto",se=Ne({tools:E,toolChoice:xo}),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(l=>l.detail??l.kind).join("; ")}`),o.debug(`turn ${J}, messages: ${rt.length}`),M(f,"turn.before_inference",{...h,model:a.currentModel},o);let Ce=!1,ke=[],st=new Map,it="stop",w,k=null,ie=!1,Z=[],B=[];try{for await(let l of t.stream({model:a.currentModel,messages:rt,tools:se.tools,toolChoice:se.normalizedToolChoice??"auto",temperature:m,maxTokens:(nt??A.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:a.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(l.type){case"delta":ke.push(l.text);break;case"tool_call_delta":Ce=!0,Ye(st,l);break;case"reasoning_delta":Z.push(l.text);break;case"reasoning_block_complete":l.signature&&B.push({thinking:Z.join(""),signature:l.signature}),Z.length=0;break;case"usage":w={inputTokens:l.promptTokens,outputTokens:l.completionTokens,reasoningTokens:l.reasoningTokens,cacheRead:l.cacheReadTokens,cacheWrite:l.cacheCreationTokens};break;case"response_id":a.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":it=l.finishReason;break}if(Ce||M(f,"turn.after_inference",{...h,model:a.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let l=a.currentModel;for(let u of e.postSamplingHooks)try{u({messages:[...re],model:l,sessionId:i})}catch{}}}catch(l){let u=yield*so(l,{state:a,guardState:A,fallbackModel:e.fallbackModel,signal:b,querySource:C,turnId:r,log:o,emitRecovery:P});if(u.kind==="return")return;if(u.kind==="continue"){a={...a,...u.patch};continue}k=u.streamError}if(k&&M(f,"turn.after_inference",{...h,model:a.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 l=Ke({status:k.status??500,message:k.message},A,F);if(l.action==="reactive_compact"&&Y(D)&&(D.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,yield P("reactive_compact",`API ${k.status??500}: ${k.message}`)),l.action==="retry"){let T=(a.consecutiveApiRetries??0)+1;if(T>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:a.totalUsage};return}yield P("retry",l.reason),a={...a,consecutiveApiRetries:T,transition:void 0};continue}let u=W(k.status,k.message);M(f,"stop.failure",{sessionId:i,reason:u,error:k.message},o),yield{type:"error",turnId:r,error:k.message,code:u,usage:a.totalUsage};return}w&&(a.totalUsage.inputTokens+=w.inputTokens,a.totalUsage.outputTokens+=w.outputTokens,w.reasoningTokens&&(a.totalUsage.reasoningTokens=(a.totalUsage.reasoningTokens??0)+w.reasoningTokens),w.cacheRead&&(a.totalUsage.cacheRead=(a.totalUsage.cacheRead??0)+w.cacheRead),w.cacheWrite&&(a.totalUsage.cacheWrite=(a.totalUsage.cacheWrite??0)+w.cacheWrite)),w?.inputTokens&&(A.promptTokens=w.inputTokens);let at=ke.join(""),O=[...st.values()].map(l=>({id:l.id||`tc_${r}_${J}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(O.length===0&&!Ce){if(at&&(a.finalText=at),e.toolChoice==="required"&&!Te&&E.length>0&&et<2){et++;let v=E.map(j=>j.function.name).filter(Boolean).slice(0,8).join(", ");a={...a,messages:[...y,{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(a.transition?.reason!=="collapse_drain_retry"){let v=Ie(re,he);if(v.committed>0){o.info(`collapse drain: committed ${v.committed} stages`),yield P("collapse_drain",`${v.committed} stages committed`),a={...a,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 P("reactive_compact","withheld prompt_too_long"),a={...a,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),M(f,"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:a.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 P("reactive_compact","media error strip-retry"),a={...a,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),M(f,"stop.failure",{sessionId:i,reason:"media_error",error:k.message},o),yield{type:"error",turnId:r,error:k.message,code:"IMAGE_ERROR",usage:a.totalUsage};return}if(eo(it)){A.consecutiveTruncations+=1;let v=e.modelMaxOutputTokens??At,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 P("output_escalation",`${j.newMax} tokens`),a={...a,maxOutputTokensOverride:Et,transition:{reason:"max_output_tokens_escalate"}};continue}if($<vt){let vo={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 P("max_output_tokens_recovery",`attempt ${$+1}`),a={...a,messages:[...re,vo],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:y,lastStopReason:"completed"});let l=await co({hooks:f,sessionId:i,messages:y,finalText:a.finalText,thinkingBlocks:B,log:o});if(l?.action==="end"){yield z(l.content);return}if(l?.action==="continue"){a={...a,messages:l.messages,stopHookActive:l.stopHookActive,transition:l.transition};continue}let u=uo({tokenBudget:e.tokenBudget,totalUsage:a.totalUsage,budgetContinuationCount:a.budgetContinuationCount,lastBudgetDeltaTokens:a.lastBudgetDeltaTokens,lastBudgetGlobalTokens:a.lastBudgetGlobalTokens,messages:y,finalText:a.finalText,thinkingBlocks:B,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o});if(u){yield P("budget_continuation",u.recoveryDetail),a={...a,messages:u.messages,budgetContinuationCount:u.budgetContinuationCount,lastBudgetDeltaTokens:u.lastBudgetDeltaTokens,lastBudgetGlobalTokens:u.lastBudgetGlobalTokens,transition:u.transition};continue}let T=lo({inputMessages:c,messages:y,finalText:a.finalText,thinkingBlocks:B,stopHookActive:a.stopHookActive,totalToolCallCount:N,distinctToolNames:U,log:o});if(T){a={...a,messages:T.messages,stopHookActive:T.stopHookActive,transition:T.transition};continue}let R=Ze({totalToolCallCount:N,distinctToolNames:U,projectRoot:e.projectRoot});R&&(yield{type:"skill_instruction",turnId:r,instruction:R});let L=a.finalText||V(y,o);for(let v of ke)yield{type:"delta",turnId:r,text:v};yield z(L);return}let _o=B.length===0&&Z.length>0?Z.join(""):void 0;y.push(_e(O,void 0,B.length>0?B:void 0,_o)),I=je(I,{replayMessages:y,pendingToolCallIds:O.map(l=>l.id),completedToolCallIds:I.completedToolCallIds,lastStopReason:"tool_calls"});let ae=a.identicalCallCounts,lt=[],le=[],ct=!1;for(let l of O){let u=`${l.function.name}::${l.function.arguments}`,T=ae.get(u)??0;ae.set(u,T+1),T+1>xt?(le.push(l),ct||(ct=!0,o.info(`AP4 blocked: ${l.function.name} repeated ${T+1}x`))):lt.push(l)}let ce=[];for(let l of le){let u=ae.get(`${l.function.name}::${l.function.arguments}`),T=Ve(y,l.function.name),R=T?`This exact tool call has been attempted ${u} times. Last error: ${T}. 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.`,L=ue(l.id,{ok:!1,error:R});y.push(L),ce.push(l.id),U.add(l.function.name),N++,yield{type:"tool_result",turnId:r,callId:l.id,name:l.function.name,ok:!1,error:R}}if(le.length>0){let l=Ve(y,le[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."};y.push(u)}let Re=po(lt,a.toolFailureCounts),be=Re.allowed;if(Re.blocked.length>0){for(let l of Re.blocked){let u=l.call,T=ue(u.id,{ok:!1,error:l.error});y.push(T),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:l.error},o.info(`variant tool blocked: ${u.function.name} failed ${l.failCount}x with different args`)}y.push(mo())}for(let l of be){let u=l.function.arguments,T=E.find(R=>R.function.name===l.function.name);if(T?.backfillObservableInput)try{let R=JSON.parse(l.function.arguments),L={...R};T.backfillObservableInput(L),Object.keys(L).some(j=>!(j in R))&&(u=JSON.stringify(L))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:u,inputSummary:Zt(u)}}let So=new Map(a.toolFailureCounts);try{let l=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:f,sessionId:i,turnId:r,log:o,signal:b,maxConcurrentTools:e?.maxConcurrentTools});for(let u of be)l.addTool(u);for await(let u of l.getRemainingResults()){if(u.blocked&&(yield{type:"tool_blocked",turnId:r,callId:u.callId,name:u.toolName,reason:u.blockReason??"blocked"}),y.push(u.message),ce.push(u.callId),U.add(u.toolName),N++,go({toolFailureCounts:a.toolFailureCounts,toolName:u.toolName,ok:u.ok,softEmpty:u.ok&&Vt(u)}),u.ok&&u.toolName==="read"){let T=be.find(R=>R.id===u.callId);if(T)try{let R=JSON.parse(T.function.arguments),L=R.file_path??R.path??R.filePath??"";if(L){let v=a.fileReadCounts.get(L)??0;a.fileReadCounts.set(L,v+1)}}catch{}}yield Wt(r,u);for(let T of Xt(r,u))yield T;for(let T of Yt({turnId:r,result:u,toolCalls:O}))yield T}}catch(l){let u=l instanceof Error?l.message:String(l);yield{type:"error",turnId:r,error:u,code:"TOOL_EXECUTION_ERROR",usage:a.totalUsage};return}if(y.push(...fo({toolFailureCounts:a.toolFailureCounts,snapshot:So})),I=me(I,{replayMessages:y,completedToolCallIds:[...I.completedToolCallIds,...ce],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&O.length>0&&(Te=!0),e.generateToolUseSummary&&O.length>0){let l=O.map(u=>({name:u.function.name,arguments:u.function.arguments}));ne=e.generateToolUseSummary(l).catch(()=>null)}let Mo=O.length>0&&O.every(l=>{let u=y.find(R=>R?.role==="tool"&&R?.tool_call_id===l.id);if(!u)return!0;let T=u.content;return typeof T=="string"&&T.startsWith("Error: ")}),ee=a.consecutiveFailedRounds;if(Mo){if(ee+=1,ee>=bt){let l=a.finalText||V(y,o);o.info(`early exit: ${ee} consecutive failed rounds, returning ${a.finalText?"partial":"fallback"} response`),yield z(l);return}}else ee=0;let Ao=3,ut=[...a.fileReadCounts.entries()].filter(([,l])=>l>=Ao);if(ut.length>0){let l=ut.map(([T])=>T).join(", ");o.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.`};y.push(u),a.fileReadCounts.clear()}let xe=J+1;if(x>0&&xe>x){if(o.info(`max turns reached (${x}), completing`),f){let u=await f.invoke("stop",{sessionId:i,reason:"max_turns"});if(u.action==="abort"){let T=u.reason??"Stop hook requested continuation after max_turns",R={role:"assistant",content:a.finalText,...B.length>0&&{thinkingBlocks:[...B]}};a={...a,messages:[...y,R,{role:"user",content:T}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let l=a.finalText||V(y,o);yield z(l);return}if(xe>S){o.info(`tool loop budget exhausted (${S} rounds), returning`);let l=Ze({totalToolCallCount:N,distinctToolNames:U,projectRoot:e.projectRoot});l&&(yield{type:"skill_instruction",turnId:r,instruction:l});let u=a.finalText||V(y,o);yield z(u);return}a={messages:y,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:xe,transition:{reason:"next_turn"},guardState:A,reactiveCompactState:D,toolLoopState:I,consecutiveFailedRounds:ee,finalText:a.finalText,totalUsage:a.totalUsage,collapseStore:he,currentModel:a.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:a.stopHookActive,lastResponseId:a.lastResponseId,snipRemovedIds:a.snipRemovedIds,contentReplacementState:a.contentReplacementState,budgetContinuationCount:a.budgetContinuationCount,lastBudgetDeltaTokens:a.lastBudgetDeltaTokens,lastBudgetGlobalTokens:a.lastBudgetGlobalTokens,identicalCallCounts:ae,toolFailureCounts:a.toolFailureCounts,fileReadCounts:a.fileReadCounts,recoveryTrace:a.recoveryTrace}}}var Vn=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function Co(e){let t=Jn(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: ${ho(o.l1Amount)}; L2 long-term says: ${ho(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=er(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
|
|
7
|
+
`)}function Jn(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>To(r.text)),n=e.filter(r=>r.source==="l2-long-term").flatMap(r=>To(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 tr(o)}function To(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim();if(o)for(let r of Vn){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let i=new RegExp(`${or(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let c of o.matchAll(i)){let s=Zn(c[1]);s!==null&&t.push({entity:Qn(o,r),predicate:r,amount:s,text:o})}}}return t}function Qn(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 Zn(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 er(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 ho(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function tr(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 or(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var nr=8192;async function ko(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,m=null;if(g&&g.length>0){let f=0,b=[];for(let h of g){let x=(h.text?.length??0)*2;if(f+x>nr)break;b.push(h),f+=x}b.length>0&&(m=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
|
|
8
|
+
${Co(b)}`)}return M(t,"memory.after_recall",{sessionId:r,turnId:i,blockCount:g?.length??0},o),m}catch{return null}}var bo=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),m=[];if(c&&m.push({role:"system",content:c}),m.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 ko({hooks:this.hooks,detectRecallCategories:p=>this.runtimePorts.detectRecallCategories(p),log:this.log,sessionId:t.sessionId,turnId:o,query:x});C&&m.splice(c?1:0,0,{role:"system",content:C})}}let f=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:m,tools:i,model:f,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},p;for await(let _ of yo(C,this.transport,this.toolInvoker,this.log))p=_,yield _;p?.type==="end"?M(this.hooks,"turn.completed",{...d},this.log):p?.type==="error"&&M(this.hooks,"turn.failed",{...d,code:p.code,error:p.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,p=W(C,x);this.log.error(`turn ${o} error [${p}, retryable=${Me(p)}]: ${x}`),M(this.hooks,"turn.failed",{...d,code:p,error:x},this.log),yield{type:"error",turnId:o,error:x,code:p}}}}};export{bo as Agent};
|