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