qlogicagent 2.15.1 → 2.15.3
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 +22 -9
- package/dist/cli.js +328 -315
- package/dist/index.js +327 -314
- package/dist/protocol.js +1 -1
- package/dist/types/agent/tool-loop/loop-helpers.d.ts +16 -0
- package/dist/types/cli/handlers/project-handler.d.ts +1 -2
- package/dist/types/cli/handlers/turn-handler.d.ts +13 -0
- package/dist/types/cli/tool-registry-adapter.d.ts +0 -1
- package/dist/types/protocol/methods.d.ts +0 -6
- package/dist/types/protocol/wire/gateway-rpc.d.ts +0 -10
- package/dist/types/runtime/infra/project-store.d.ts +0 -5
- package/package.json +1 -1
- package/dist/types/skills/tools/brief-tool.d.ts +0 -74
- package/dist/types/skills/tools/browser-tool.d.ts +0 -114
- package/dist/types/skills/tools/plan-mode-tool.d.ts +0 -98
- package/dist/types/skills/tools/structured-output-tool.d.ts +0 -116
package/dist/agent.js
CHANGED
|
@@ -1,12 +1,25 @@
|
|
|
1
|
-
function nt(e,t,o,n){return{role:"assistant",content:t||null,tool_calls:e,...o&&o.length>0?{thinkingBlocks:o}:{},...n?{reasoning_content:n}:{}}}function V(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 Uo=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,ne={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]},jo=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,qo=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Ho=512,zo=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Go=new Set([500,502,503,504,521,522,523,524,529]),Wo=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ko=["upgrade your plan","upgrade plan","current plan","subscription"],Xo=["daily","weekly","monthly"],Yo=["try again","retry","temporary","cooldown"],Vo=["usage limit","rate limit","organization usage"],Zo=["organization","workspace"],Jo=["billing period","exceeded","reached","exhausted"],Qo=/["']?(?: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,er=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function oe(e,t){if(!e)return!1;let o=e.toLowerCase();return t.some(n=>n instanceof RegExp?n.test(o):o.includes(n))}function tr(e){return oe(e,ne.format)}function an(e){return oe(e,ne.rateLimit)}function nr(e){return oe(e,ne.timeout)}function or(e){return Uo.test(e)}function ot(e){let t=e.toLowerCase();return t?e.length>Ho?qo.test(t):oe(t,ne.billing)?!0:jo.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function ln(e){return oe(e,ne.authPermanent)}function rr(e){return oe(e,ne.auth)}function cn(e){return oe(e,ne.overloaded)}function te(e,t){return t.some(o=>e.includes(o))}function sr(e){return te(e,Wo)||te(e,Ko)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function ir(e){let t=te(e,Xo),o=e.includes("spend limit")||e.includes("spending limit"),n=te(e,Zo);return te(e,Yo)&&te(e,Vo)||t&&(e.includes("usage limit")||o)||t&&e.includes("limit")&&e.includes("reset")||n&&e.includes("limit")&&(o||te(e,Jo))}function ar(e){return e.trim().toLowerCase().replace(er,"").trim()}function un(e){let t=ar(e);return!t||sr(t)?"billing":an(t)||ir(t)?"rate_limit":"billing"}function lr(e){return Qo.test(e)?un(e):null}function dn(e){let t=e.match(zo);if(!t)return null;let o=Number(t[1]);return Number.isFinite(o)?{code:o,rest:(t[2]??"").trim()}:null}function cr(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function ur(e){let t=e.trim();if(!t)return!1;let o=dn(t);return o?Go.has(o.code):!1}function pn(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?un(t):"billing":e===429?"rate_limit":e===401||e===403?t&&ln(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&cn(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&ot(t)?"billing":"format":null}function dr(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 pr(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 mn(e){if(pr(e))return"session_expired";if(dr(e))return"model_not_found";let t=lr(e);return t||(or(e)?ot(e)?"billing":"rate_limit":an(e)?"rate_limit":cn(e)?"overloaded":ur(e)?dn(e.trim())?.code===529?"overloaded":"timeout":cr(e)?"timeout":tr(e)?"format":ot(e)?"billing":nr(e)?"timeout":ln(e)?"auth_permanent":rr(e)?"auth":null)}var mr={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"},fr=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ae(e,t){let o=pn(e,t)??(t?mn(t):null);return o?mr[o]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function rt(e){return fr.has(e)}function fn(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var gr=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"]),Ce=class{constructor(t=20,o=fn){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,u)=>{if(u>=n||a.role!=="tool"||typeof a.content!="string"||!a.name||!gr.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 st(e,t,o=fn){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let n=0,r=0,s=[];for(let a of e){let u=a.tool_call_id??"";if(u&&t.has(u)){n+=o(a),r++,t.delete(u);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:n,removedCount:r,boundaryMessage:i}}function it(){return{stages:[]}}function at(e,t,o){let n=o?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=n)return{messages:e,stagedCount:0};let s=gn(e,t),i=yr(s,t,n);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=gn(e,t),{messages:s,stagedCount:i.length}}function lt(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:yn(e,t),committed:o}}function gn(e,t){return t.stages.filter(n=>n.committed).length===0?e:yn(e,t)}function yn(e,t){let o=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),n=[...e];for(let r of o){let[s,i]=r.range;if(s>=n.length)continue;let a=Math.min(i,n.length),u={role:"system",content:r.summary};n.splice(s,a-s,u)}return n}function yr(e,t,o){let n=Math.max(0,e.length-Math.floor(o/2)),r=[],s=new Set(t.stages.map(u=>`${u.range[0]}-${u.range[1]}`)),i=-1,a=0;for(let u=0;u<n;u++){let p=e[u];if(p.role==="tool"||p.role==="assistant"&&typeof p.content=="string"&&p.content==="")i<0&&(i=u),a++;else{if(a>=3){let m=`${i}-${i+a}`;s.has(m)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let u=`${i}-${i+a}`;s.has(u)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{existsSync as ut,readFileSync as Nn,writeFileSync as hr,readdirSync as Bn,mkdirSync as Tr}from"node:fs";import{join as dt,dirname as Cr}from"node:path";var re=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),hn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),Tn=3,Cn=2,Oe=2,kn=128e3,Rn=13e3,bn=16384,xn=65536,_n=3,Mn=65536,ct=500,An=3;var vn=3e4,Sn=3,se=2;var En=20;var wn=3,In=2,Pn=300*1e3,Ln=3,On=720*60*60*1e3;var Js=300*1e3;var Qs=3600*1e3;var ei=50*1024,ti=500*1024,ni=500*1024*1024,oi=50*1024*1024;var ri=60*1024;var Dn=0;var kr="skill-patterns.json";function $n(e){return dt(e,".qlogicagent",kr)}function Rr(e){let t=$n(e);try{return JSON.parse(Nn(t,"utf8"))}catch{return{version:1,patterns:{}}}}function Fn(e,t){let o=$n(e);Tr(Cr(o),{recursive:!0}),hr(o,JSON.stringify(t,null,2),"utf8")}function br(e){let t=Date.now()-On;for(let[o,n]of Object.entries(e.patterns))new Date(n.lastSeen).getTime()<t&&delete e.patterns[o]}function Un(e,t){if(t.length===0)return!1;let o=Fe(t),n=Rr(e);br(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 Fn(e,n),!1;s.count++,s.lastSeen=r;let i=s.count>=Ln;return i&&(s.promoted=!0),Fn(e,n),i}function Fe(e){return[...e].sort().join("+")}function xr(e,t){if(!ut(t))return null;let o=Fe(e);try{let n=Bn(t,{withFileTypes:!0});for(let r of n){if(!r.isDirectory())continue;let s=dt(t,r.name,"SKILL.md");try{let a=Nn(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let u=a[1].split(`
|
|
2
|
-
`).map(p=>p.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(Fe(u)===o)return r.name}}catch{}}}catch{}return null}function _r(e){if(!ut(e))return 0;try{return Bn(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&ut(dt(e,t.name,"SKILL.md"))).length}catch{return 0}}function Mr(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<wn||e.distinctToolCount<In||Date.now()-Dn<Pn||t?.projectSkillsDir&&(_r(t.projectSkillsDir)>=En||t.tools.length>0&&xr(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Un(t.projectRoot,t.tools))}function Ar(e){return e.existingSkillName?e.feedback==="negative":!1}function pt(e,t){return Ar(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Mr(e,t)?(Dn=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 jn(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 vr(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Sr(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Er(e){if(!e.eligibility?.length)return[...e.tools];let t=Sr(e.eligibility);return e.tools.filter(o=>{let n=jn(o);if(!n)return!1;let r=t.get(n);return!r||vr(r.status)})}function wr(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 mt(e){let t=wr({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),o=t.normalizedToolChoice,n=[...t.warnings],r=Er({tools:e.tools,eligibility:e.eligibility});if(!o||o==="auto")return{tools:r,normalizedToolChoice:o,warnings:n};if(o==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(o==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:n}}if(typeof o=="object"&&!Array.isArray(o)&&o.type==="function"){let s=o.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(u=>jn(u)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:n}}return{tools:r,normalizedToolChoice:o,warnings:n}}var Ir=["stop","aborted","timeout","cancelled","interrupted","error"],Pr=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function qn(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Lr(e,t){return{...e,content:[...qn(e.content),...qn(t.content)]}}function Or(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 Fr(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=Or(r);if(s.size!==0)for(let i=n+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(o.push(a),t.add(i))}}return o}function 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 Br(e){return new Set((e??Ir).map(t=>t.trim().toLowerCase()))}function Dr(e,t){return e?Br(t).has(e.trim().toLowerCase()):!1}function ft(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(u=>{if(u.role==="assistant"&&Array.isArray(u.tool_calls)){let p=u.tool_calls.filter(f=>Nr(f));return{...u,...p.length>0?{tool_calls:p}:{tool_calls:void 0}}}return{...u}}),o=new Set;for(let u of t)if(!(u.role!=="assistant"||!Array.isArray(u.tool_calls)))for(let p of u.tool_calls)typeof p.id=="string"&&p.id&&o.add(p.id);let n=t.filter(u=>u.role!=="tool"?!0:!!(u.tool_call_id&&o.has(u.tool_call_id))),r=new Set;for(let u of n)u.role==="tool"&&typeof u.tool_call_id=="string"&&u.tool_call_id&&r.add(u.tool_call_id);let s=[];for(let u of n){if(u.role==="assistant"&&Array.isArray(u.tool_calls)&&u.tool_calls.length>0){let p=u.tool_calls.filter(f=>typeof f.id=="string"&&r.has(f.id));if(p.length===0){let{tool_calls:f,...m}=u;m.content!=null&&m.content!==""&&s.push(m);continue}if(p.length<u.tool_calls.length){s.push({...u,tool_calls:p});continue}}s.push(u)}let i=Fr(s),a=[];for(let u of i){let p=a.length>0?a[a.length-1]:void 0;if(u.role==="user"&&p?.role==="user"){a[a.length-1]=Lr(p,u);continue}a.push(u)}return a}function gt(e,t){return Dr(t?.stopReason,t?.forcedStopReasons)?e.map(o=>{if(o.role!=="assistant")return{...o};let n={...o};for(let r of Pr)delete n[r];return n}):[...e]}function yt(e,t){let o=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",n=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&n.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||n.has(i.id)||(n.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:o}));return r}function ht(e,t){let o=ft(e),n=gt(o,t);return yt(n,t)}function $r(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 Ur(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 jr(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 Ne(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 Be(e){let t=[],o=ft(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=gt(o,e.options);n.some((s,i)=>s!==o[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=yt(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:jr({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:$r(r),completedToolCallIds:Ur(r)}),recoveryActions:t}}var qr=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Ct(e){return e?qr.has(e):!0}function kt(e){return e===429||e===529}function De(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 yi={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function $e(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var ke=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 bt(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 xt(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 _t(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 Mt(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var zr={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function At(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function le(e,t=zr){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function vt(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 E(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 Hn(e,t){let o=typeof t.message?.content=="string"?t.message.content:"",n=o?o.slice(0,2e3):void 0,r=t.details,s=typeof r?.stdout=="string"?r.stdout.slice(0,8e3):void 0,i=typeof r?.stderr=="string"?r.stderr.slice(0,4e3):void 0,a=typeof r?.exitCode=="number"?r.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:n,durationMs:t.durationMs,exitCode:a,stdout:s,stderr:i,details:r}}function zn(e,t){if(!t.ok)return[];let o=t.details;if(!o)return[];let n=Gr(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 Gr(e){let t=typeof e.type=="string"?e.type:"";if(!t)return null;if(t==="three_d_generate")return"3d";let o=t.split("_")[0];return o==="image"||o==="tts"||o==="video"||o==="music"?o:null}var Wr=new Set(["write","edit","patch"]);function Gn(e){let{turnId:t,result:o,toolCalls:n}=e;if(!o.ok)return[];let r=n.find(a=>a.id===o.callId);if(!r)return[];let s=[],i=Kr(r.function.arguments);if(!i)return s;if(o.toolName==="plan_mode"&&i.action==="exit"&&typeof i.plan=="string"&&i.plan.length>0&&s.push({type:"plan_update",turnId:t,slug:"approved-plan",content:i.plan}),Wr.has(o.toolName)){let a=Xr(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${o.callId}`,artifactType:Yr(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:Vr(a)})}return s}function Kr(e){try{return JSON.parse(e)}catch{return null}}function Xr(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 Vr(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 Zr=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,Jr=new Set(["search","web_search","grep","glob","find","list","read","exec"]),Qr=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,es=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])((?:[A-Za-z0-9._-]+[\\/])+[A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,ts=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,ns=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i;function Wn(e){if(!Jr.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&Zr.test(t)}function St(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()}}var os=/\b(?:build|create|make|develop|implement|scaffold|generate)\b[\s\S]{0,40}\b(?:app|application|game|website|web ?app|site|system|tool|project|dashboard|platform|service|server)\b|(?:做|搭|写|开发|实现|构建|生成|搭建)[\s\S]{0,12}(?:游戏|应用|网站|系统|程序|项目|工具|平台|服务|网页|app)/i,Kn=50;function Xn(e){if(!e)return!1;for(let t of e)if(t.role==="user"&&typeof t.content=="string"&&os.test(t.content))return!0;return!1}var rs=/(?:我来|我先|我现在就?|让我先?|接下来我?|我帮你|我这就|我会|我将|我去|我看)[^。.!?!?\n]{0,12}(?:做|搭建?|写|开发|实现|构建|生成|创建|新建|建立|改|修复?|检查|读取?|运行|跑|执行|看一?下?|查看|配置|安装|部署|分析|整理|定位|排查|找)/,ss=/\b(?:let me|i['’]?ll|i will|i['’]?m going to|let['’]?s)\b[^.!?\n]{0,24}\b(?:build|create|make|write|implement|generate|check|read|run|look|set up|scaffold|add|fix|inspect|search|find|list|analyze|review|start|debug|investigate)\b/i;function Yn(e){let t=e.trim();return t.length===0||t.length>200||t.includes("```")?!1:rs.test(t)||ss.test(t)}function Vn(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let o=Ue(t);return o>=3?Math.min(Math.max(25,20+o*15),100):Xn(t)?Math.min(Math.max(25,Kn),100):25}function Ue(e){if(!e)return 0;let t=new Set,o=new Set,n=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase();t.add(`path:${s}`);let i=s.split("/").pop();i&&o.add(i)};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content;for(let i of r.content.matchAll(Qr))n(i[0]);if(ns.test(s)){for(let i of s.matchAll(es)){let a=i[1]?.toLowerCase();if(!a)continue;t.add(`relative:${a.replace(/\\/g,"/")}`);let u=a.replace(/\\/g,"/").split("/").pop();u&&o.add(u)}for(let i of s.matchAll(ts)){let a=i[1]?.toLowerCase();!a||o.has(a)||t.add(`name:${a}`)}}}return t.size}function Zn(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let o=Ue(t);return o>=3?Math.min(Math.max(re,20+o*15),100):Xn(t)?Math.min(Math.max(re,Kn),100):re}function Jn(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function Et(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(`
|
|
1
|
+
function ot(e,t,o,n){return{role:"assistant",content:t||null,tool_calls:e,...o&&o.length>0?{thinkingBlocks:o}:{},...n?{reasoning_content:n}:{}}}function V(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 qo=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,oe={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Ho=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,zo=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Go=512,Wo=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Ko=new Set([500,502,503,504,521,522,523,524,529]),Xo=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Yo=["upgrade your plan","upgrade plan","current plan","subscription"],Vo=["daily","weekly","monthly"],Zo=["try again","retry","temporary","cooldown"],Jo=["usage limit","rate limit","organization usage"],Qo=["organization","workspace"],er=["billing period","exceeded","reached","exhausted"],tr=/["']?(?: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,nr=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function re(e,t){if(!e)return!1;let o=e.toLowerCase();return t.some(n=>n instanceof RegExp?n.test(o):o.includes(n))}function or(e){return re(e,oe.format)}function ln(e){return re(e,oe.rateLimit)}function rr(e){return re(e,oe.timeout)}function sr(e){return qo.test(e)}function rt(e){let t=e.toLowerCase();return t?e.length>Go?zo.test(t):re(t,oe.billing)?!0:Ho.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function cn(e){return re(e,oe.authPermanent)}function ir(e){return re(e,oe.auth)}function un(e){return re(e,oe.overloaded)}function ne(e,t){return t.some(o=>e.includes(o))}function ar(e){return ne(e,Xo)||ne(e,Yo)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function lr(e){let t=ne(e,Vo),o=e.includes("spend limit")||e.includes("spending limit"),n=ne(e,Qo);return ne(e,Zo)&&ne(e,Jo)||t&&(e.includes("usage limit")||o)||t&&e.includes("limit")&&e.includes("reset")||n&&e.includes("limit")&&(o||ne(e,er))}function cr(e){return e.trim().toLowerCase().replace(nr,"").trim()}function dn(e){let t=cr(e);return!t||ar(t)?"billing":ln(t)||lr(t)?"rate_limit":"billing"}function ur(e){return tr.test(e)?dn(e):null}function pn(e){let t=e.match(Wo);if(!t)return null;let o=Number(t[1]);return Number.isFinite(o)?{code:o,rest:(t[2]??"").trim()}:null}function dr(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function pr(e){let t=e.trim();if(!t)return!1;let o=pn(t);return o?Ko.has(o.code):!1}function mn(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?dn(t):"billing":e===429?"rate_limit":e===401||e===403?t&&cn(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&un(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&rt(t)?"billing":"format":null}function mr(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 fr(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 fn(e){if(fr(e))return"session_expired";if(mr(e))return"model_not_found";let t=ur(e);return t||(sr(e)?rt(e)?"billing":"rate_limit":ln(e)?"rate_limit":un(e)?"overloaded":pr(e)?pn(e.trim())?.code===529?"overloaded":"timeout":dr(e)?"timeout":or(e)?"format":rt(e)?"billing":rr(e)?"timeout":cn(e)?"auth_permanent":ir(e)?"auth":null)}var gr={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"},yr=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function le(e,t){let o=mn(e,t)??(t?fn(t):null);return o?gr[o]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function st(e){return yr.has(e)}function gn(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var hr=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,o=gn){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,u)=>{if(u>=n||a.role!=="tool"||typeof a.content!="string"||!a.name||!hr.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 it(e,t,o=gn){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let n=0,r=0,s=[];for(let a of e){let u=a.tool_call_id??"";if(u&&t.has(u)){n+=o(a),r++,t.delete(u);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:n,removedCount:r,boundaryMessage:i}}function at(){return{stages:[]}}function lt(e,t,o){let n=o?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=n)return{messages:e,stagedCount:0};let s=yn(e,t),i=Tr(s,t,n);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=yn(e,t),{messages:s,stagedCount:i.length}}function ct(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:hn(e,t),committed:o}}function yn(e,t){return t.stages.filter(n=>n.committed).length===0?e:hn(e,t)}function hn(e,t){let o=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),n=[...e];for(let r of o){let[s,i]=r.range;if(s>=n.length)continue;let a=Math.min(i,n.length),u={role:"system",content:r.summary};n.splice(s,a-s,u)}return n}function Tr(e,t,o){let n=Math.max(0,e.length-Math.floor(o/2)),r=[],s=new Set(t.stages.map(u=>`${u.range[0]}-${u.range[1]}`)),i=-1,a=0;for(let u=0;u<n;u++){let p=e[u];if(p.role==="tool"||p.role==="assistant"&&typeof p.content=="string"&&p.content==="")i<0&&(i=u),a++;else{if(a>=3){let m=`${i}-${i+a}`;s.has(m)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let u=`${i}-${i+a}`;s.has(u)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{existsSync as dt,readFileSync as Bn,writeFileSync as Cr,readdirSync as Dn,mkdirSync as kr}from"node:fs";import{join as pt,dirname as Rr}from"node:path";var se=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Tn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),Cn=3,kn=2,Fe=2,Rn=128e3,bn=13e3,xn=16384,_n=65536,Mn=3,An=65536,ut=500,vn=3;var Sn=3e4,En=3,ie=2;var wn=20;var In=3,Pn=2,Ln=300*1e3,On=3,Fn=720*60*60*1e3;var ei=300*1e3;var ti=3600*1e3;var ni=50*1024,oi=500*1024,ri=500*1024*1024,si=50*1024*1024;var ii=60*1024;var $n=0;var br="skill-patterns.json";function Un(e){return pt(e,".qlogicagent",br)}function xr(e){let t=Un(e);try{return JSON.parse(Bn(t,"utf8"))}catch{return{version:1,patterns:{}}}}function Nn(e,t){let o=Un(e);kr(Rr(o),{recursive:!0}),Cr(o,JSON.stringify(t,null,2),"utf8")}function _r(e){let t=Date.now()-Fn;for(let[o,n]of Object.entries(e.patterns))new Date(n.lastSeen).getTime()<t&&delete e.patterns[o]}function jn(e,t){if(t.length===0)return!1;let o=Ne(t),n=xr(e);_r(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 Nn(e,n),!1;s.count++,s.lastSeen=r;let i=s.count>=On;return i&&(s.promoted=!0),Nn(e,n),i}function Ne(e){return[...e].sort().join("+")}function Mr(e,t){if(!dt(t))return null;let o=Ne(e);try{let n=Dn(t,{withFileTypes:!0});for(let r of n){if(!r.isDirectory())continue;let s=pt(t,r.name,"SKILL.md");try{let a=Bn(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let u=a[1].split(`
|
|
2
|
+
`).map(p=>p.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(Ne(u)===o)return r.name}}catch{}}}catch{}return null}function Ar(e){if(!dt(e))return 0;try{return Dn(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&dt(pt(e,t.name,"SKILL.md"))).length}catch{return 0}}function vr(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<In||e.distinctToolCount<Pn||Date.now()-$n<Ln||t?.projectSkillsDir&&(Ar(t.projectSkillsDir)>=wn||t.tools.length>0&&Mr(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!jn(t.projectRoot,t.tools))}function Sr(e){return e.existingSkillName?e.feedback==="negative":!1}function mt(e,t){return Sr(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:vr(e,t)?($n=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 qn(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 Er(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function wr(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Ir(e){if(!e.eligibility?.length)return[...e.tools];let t=wr(e.eligibility);return e.tools.filter(o=>{let n=qn(o);if(!n)return!1;let r=t.get(n);return!r||Er(r.status)})}function Pr(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 ft(e){let t=Pr({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),o=t.normalizedToolChoice,n=[...t.warnings],r=Ir({tools:e.tools,eligibility:e.eligibility});if(!o||o==="auto")return{tools:r,normalizedToolChoice:o,warnings:n};if(o==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(o==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:n}}if(typeof o=="object"&&!Array.isArray(o)&&o.type==="function"){let s=o.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(u=>qn(u)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:n}}return{tools:r,normalizedToolChoice:o,warnings:n}}var Lr=["stop","aborted","timeout","cancelled","interrupted","error"],Or=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Hn(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Fr(e,t){return{...e,content:[...Hn(e.content),...Hn(t.content)]}}function Nr(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 Br(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=Nr(r);if(s.size!==0)for(let i=n+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(o.push(a),t.add(i))}}return o}function Dr(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 $r(e){return new Set((e??Lr).map(t=>t.trim().toLowerCase()))}function Ur(e,t){return e?$r(t).has(e.trim().toLowerCase()):!1}function gt(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(u=>{if(u.role==="assistant"&&Array.isArray(u.tool_calls)){let p=u.tool_calls.filter(f=>Dr(f));return{...u,...p.length>0?{tool_calls:p}:{tool_calls:void 0}}}return{...u}}),o=new Set;for(let u of t)if(!(u.role!=="assistant"||!Array.isArray(u.tool_calls)))for(let p of u.tool_calls)typeof p.id=="string"&&p.id&&o.add(p.id);let n=t.filter(u=>u.role!=="tool"?!0:!!(u.tool_call_id&&o.has(u.tool_call_id))),r=new Set;for(let u of n)u.role==="tool"&&typeof u.tool_call_id=="string"&&u.tool_call_id&&r.add(u.tool_call_id);let s=[];for(let u of n){if(u.role==="assistant"&&Array.isArray(u.tool_calls)&&u.tool_calls.length>0){let p=u.tool_calls.filter(f=>typeof f.id=="string"&&r.has(f.id));if(p.length===0){let{tool_calls:f,...m}=u;m.content!=null&&m.content!==""&&s.push(m);continue}if(p.length<u.tool_calls.length){s.push({...u,tool_calls:p});continue}}s.push(u)}let i=Br(s),a=[];for(let u of i){let p=a.length>0?a[a.length-1]:void 0;if(u.role==="user"&&p?.role==="user"){a[a.length-1]=Fr(p,u);continue}a.push(u)}return a}function yt(e,t){return Ur(t?.stopReason,t?.forcedStopReasons)?e.map(o=>{if(o.role!=="assistant")return{...o};let n={...o};for(let r of Or)delete n[r];return n}):[...e]}function ht(e,t){let o=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",n=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&n.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||n.has(i.id)||(n.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:o}));return r}function Tt(e,t){let o=gt(e),n=yt(o,t);return ht(n,t)}function jr(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 qr(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 Hr(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Ct(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 Be(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 De(e){let t=[],o=gt(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=yt(o,e.options);n.some((s,i)=>s!==o[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=ht(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:Hr({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:jr(r),completedToolCallIds:qr(r)}),recoveryActions:t}}var zr=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function kt(e){return e?zr.has(e):!0}function Rt(e){return e===429||e===529}function $e(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 Ti={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Ue(){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 bt(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function xt(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 _t(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 Mt(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 At(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Wr={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function vt(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function ce(e,t=Wr){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function St(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 E(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 zn(e,t){let o=typeof t.message?.content=="string"?t.message.content:"",n=o?o.slice(0,2e3):void 0,r=t.details,s=typeof r?.stdout=="string"?r.stdout.slice(0,8e3):void 0,i=typeof r?.stderr=="string"?r.stderr.slice(0,4e3):void 0,a=typeof r?.exitCode=="number"?r.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:n,durationMs:t.durationMs,exitCode:a,stdout:s,stderr:i,details:r}}function Gn(e,t){if(!t.ok)return[];let o=t.details;if(!o)return[];let n=Kr(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 Kr(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 Xr=new Set(["write","edit","patch"]);function Wn(e){let{turnId:t,result:o,toolCalls:n}=e;if(!o.ok)return[];let r=n.find(a=>a.id===o.callId);if(!r)return[];let s=[],i=Yr(r.function.arguments);if(!i)return s;if(Xr.has(o.toolName)){let a=Vr(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${o.callId}`,artifactType:Zr(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:Jr(a)})}return s}function Yr(e){try{return JSON.parse(e)}catch{return null}}function Vr(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 Zr(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 Jr(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 Qr=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,es=new Set(["search","web_search","grep","glob","find","list","read","exec"]),ts=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,ns=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])((?:[A-Za-z0-9._-]+[\\/])+[A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,os=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,rs=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i;function Kn(e){if(!es.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&Qr.test(t)}function je(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()}}var ss=/\b(?:build|create|make|develop|implement|scaffold|generate)\b[\s\S]{0,40}\b(?:app|application|game|website|web ?app|site|system|tool|project|dashboard|platform|service|server)\b|(?:做|搭|写|开发|实现|构建|生成|搭建)[\s\S]{0,12}(?:游戏|应用|网站|系统|程序|项目|工具|平台|服务|网页|app)/i,Xn=50;function Yn(e){if(!e)return!1;for(let t of e)if(t.role==="user"&&typeof t.content=="string"&&ss.test(t.content))return!0;return!1}var is=/(?:我来|我先|我现在就?|让我先?|接下来我?|我帮你|我这就|我会|我将|我去|我看)[^。.!?!?\n]{0,12}(?:做|搭建?|写|开发|实现|构建|生成|创建|新建|建立|改|修复?|检查|读取?|运行|跑|执行|看一?下?|查看|配置|安装|部署|分析|整理|定位|排查|找)/,as=/\b(?:let me|i['’]?ll|i will|i['’]?m going to|let['’]?s)\b[^.!?\n]{0,24}\b(?:build|create|make|write|implement|generate|check|read|run|look|set up|scaffold|add|fix|inspect|search|find|list|analyze|review|start|debug|investigate)\b/i;function Vn(e){let t=e.trim();return t.length===0||t.length>200||t.includes("```")?!1:is.test(t)||as.test(t)}function Zn(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let o=qe(t);return o>=3?Math.min(Math.max(25,20+o*15),100):Yn(t)?Math.min(Math.max(25,Xn),100):25}function qe(e){if(!e)return 0;let t=new Set,o=new Set,n=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase();t.add(`path:${s}`);let i=s.split("/").pop();i&&o.add(i)};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content;for(let i of r.content.matchAll(ts))n(i[0]);if(rs.test(s)){for(let i of s.matchAll(ns)){let a=i[1]?.toLowerCase();if(!a)continue;t.add(`relative:${a.replace(/\\/g,"/")}`);let u=a.replace(/\\/g,"/").split("/").pop();u&&o.add(u)}for(let i of s.matchAll(os)){let a=i[1]?.toLowerCase();!a||o.has(a)||t.add(`name:${a}`)}}}return t.size}function Jn(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let o=qe(t);return o>=3?Math.min(Math.max(se,20+o*15),100):Yn(t)?Math.min(Math.max(se,Xn),100):se}function Qn(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function Et(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
|
|
5
|
-
`,t),e.lastIndexOf(";",t),e.lastIndexOf("\u3002",t),e.lastIndexOf("\uFF1B",t))+1,r=e.slice(n,t).toLowerCase();if(/\b(?:do\s+not|don't|never)\s+(?:leave|create|write|include|keep|produce|add|generate)\b/i.test(r)||/\b(?:remove|delete|exclude)\b/i.test(r))return!0;let s=e.slice(Math.max(0,t-16),t+o.length);return new RegExp(`\\bno\\s+${Re(o)}\\b`,"i").test(s)}function lo(e){return e.replace(/https?:\/\/\S+/gu," ")}function He(e){let t=new Set,o=[],n=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B]+$/u,""),i=$(s);t.has(i)||(t.add(i),o.push(s))};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=lo(r.content);for(let i of s.matchAll(as)){let a=i[0];n(a);let u=(i.index??0)+a.length,p=a.replace(/\\/g,"/"),f=p.lastIndexOf("/");if(f>=0){let m=p.slice(0,f+1);so.lastIndex=u;let C;for(;(C=so.exec(s))!==null;)n(`${m}${C[1]}`)}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=lo(r.content);if(!ps.test(s))continue;let i=Array.from(s.matchAll(ls)).map(u=>uo(u[1]??"")).filter(u=>u&&!io(u));if(i.length===0)continue;let a=i[i.length-1];for(let u of s.matchAll(cs)){let p=u[1];p&&(ao(s,u.index??0,p)||n(`${a}/${p}`))}for(let u of s.matchAll(us)){let p=u[1];p&&(ao(s,u.index??0,p)||n(`${a}/${p}`))}for(let u of s.matchAll(ds)){let p=u[1];p&&(io(p)||/(?:assets[\\/]generated|screenshots(?:[\\/]|$)|previews(?:[\\/]|$))/i.test(p)&&/\b(?:generated|bitmap|png|screenshots?|preview|previews|evidence|assets?|containing)\b/i.test(s)&&n(`${a}/${p}/*`))}ms.test(s)&&n(`${a}/previews/*`)}return o}function Ot(e){if(e.role!=="tool")return!1;let t=typeof e.content=="string"?e.content:"";return e.is_error!==!0&&!t.startsWith("Error:")}function po(e){let t=new Set,o=new Map,n=[];for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let u=a,p=u.id,f=u.function;typeof p=="string"&&typeof f?.name=="string"&&o.set(p,f.name)}}for(let r of e){let s=r;if(Ot(s)){let i=s.tool_call_id;typeof i=="string"&&t.add(i),(typeof i=="string"?o.get(i):void 0)==="exec"&&typeof s.content=="string"&&n.push(s.content)}}for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let u=a,p=u.id;if(typeof p=="string"&&t.size>0&&!t.has(p))continue;let f=u.function;if(!(typeof f?.name!="string"||typeof f.arguments!="string"))try{let m=JSON.parse(f.arguments);if(f.name==="write"||f.name==="edit"){for(let C of["path","filePath","file_path"]){let M=m[C];typeof M=="string"&&n.push(M)}continue}if(f.name==="exec"){let C=m.command;typeof C=="string"&&n.push(C)}}catch{f.name==="exec"&&n.push(f.arguments)}}}return n.join(`
|
|
6
|
-
`).replace(/\\/g,"/").toLowerCase()}function Ft(e){try{if(e.endsWith("/*")){let o=e.slice(0,-2);return co(o,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return qe(`${o}/${r.name}`).size>0}catch{return!1}})}let t=qe(e);return t.isFile()&&t.size>0}catch{return!1}}function fs(e,t){let o=$(t);if(!o.endsWith("/*"))return e.includes(o);let n=o.slice(0,-1);return e.includes(n)}function gs(e){let t=ue(e);return/\b(?:exactly|only)\b[^.\n]*(?:artifacts?|files?|outputs?|deliverables?)/i.test(t)||/(?:artifacts?|files?|outputs?|deliverables?)[^.\n]*\b(?:exactly|only)\b/i.test(t)}function ys(e){let t=uo(e),o=t.lastIndexOf("/");return o>=0?t.slice(0,o):""}function hs(e){if(e.length===0)return"";let t=e.map(n=>ys(n).split("/")),o=[];for(let n=0;n<t[0].length;n++){let r=t[0][n];if(t.every(s=>s[n]?.toLowerCase()===r.toLowerCase()))o.push(r);else break}return o.join("/")}function Ts(e,t){let o=$(e);return t.some(n=>{let r=$(n);return r.endsWith("/*")?o.startsWith(r.slice(0,-1)):o===r})}function Cs(e){let t=new Set,o=new Map;for(let n of e){let r=n,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,u=a.id,p=a.function;if(typeof u!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let f=Ut(p.arguments);if(!f)continue;let m=jt(f);m&&o.set(u,m)}}for(let n of e){let r=n;if(!Ot(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...o.entries()].filter(([n])=>t.has(n)).map(([,n])=>n)}function mo(e){return/\bartifact[-_\s]?index\b/i.test(e)&&(/\b(?:evidence|status|failed|partial|passed|verified)\b/i.test(e)||/\bGoal\s+\d+\b/i.test(e))}function ks(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function fo(e){let t=new Set,o=new Map;for(let n of e){let r=n,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,u=a.id,p=a.function;if(typeof u!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let f=Ut(p.arguments);if(!f)continue;let m=jt(f)??"",C=ho(f);(/\bartifact[-_\s]?index\b/i.test(m)||/\bartifact[-_\s]?index\b/i.test(C))&&o.set(u,C)}}for(let n of e){let r=n;if(!Ot(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...o.entries()].filter(([n])=>t.has(n)).map(([,n])=>n).filter(n=>n.trim().length>0)}function go(e){let t=ue(e.inputMessages);if(!mo(t))return[];let o=fo(e.messages).at(-1);if(!o)return[];let n=[],r=ks(t).filter(u=>!new RegExp(`\\b${Re(u)}\\b`,"i").test(o));r.length>0&&n.push({type:"missing_goal_labels",detail:`Missing requested row labels in the generated index: ${r.join(", ")}`});let s=/\b(?:failed|partial|missing|not\s+found|no\s+[^.\n|]*evidence)\b/i.test(o),i=/\b(?:all\s+checks\s+pass|confirmed\s*:\s*all|everything\s+(?:passes|passed)|fully\s+verified)\b/i.test(e.finalText);s&&i&&n.push({type:"overconfident_final",detail:"Final response claimed all checks pass while the generated index contains failed, partial, missing, or no-evidence rows."});let a=o.split(/\r?\n/u).filter(u=>/\bno\s+[^|\n]*(?:found|evidence|files?)\b/i.test(u)&&!/\b(?:not\s+verified|unverified|unknown|not\s+checked|search\s+scope|checked\s+path)\b/i.test(u));return a.length>0&&n.push({type:"unsupported_absence",detail:`Absence claims need scoped evidence or must be marked unverified: ${a.slice(0,3).join(" ; ")}`}),n}function Rs(e){let t=[],o=n=>{let r;try{r=co(n,{withFileTypes:!0})}catch{return}for(let s of r){let i=`${n}/${s.name}`;if(s.isDirectory()){o(i);continue}if(s.isFile())try{qe(i).size>0&&t.push(i)}catch{}}};try{if(!qe(e).isDirectory())return[]}catch{return[]}return o(e),t}function yo(e,t){if(!gs(e))return[];let o=He(e),n=o.filter(i=>!$(i).endsWith("/*"));if(n.length<2)return[];let r=hs(n);if(!r||r.split("/").length<3)return[];let s=$(r);return[...new Set([...Cs(t),...Rs(r)])].filter(i=>$(i).startsWith(`${s}/`)&&!Ts(i,o)&&Ft(i))}function Nt(e,t){let o=He(e);if(o.length===0)return[];let n=po(t);return o.filter(r=>!fs(n,r))}function Lt(e){return be(e).fail}function bs(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function je(e){if(!e)return!1;let t=bs(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function be(e){let t=r=>r.replace(/[.,;:]+$/u,""),o,n;for(let r of e)if(!(r.role!=="user"||typeof r.content!="string")){for(let s of r.content.matchAll(/\b(DONE|PASS)\s+([A-Za-z0-9_.:-]+)/gi))je(s[2])&&(o=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))je(s[1])&&(n=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))je(s[1])&&(o=`${t(s[1])} ${s[2].toUpperCase()}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+FAIL\b/gi))je(s[1])&&(n=`${t(s[1])} FAIL`)}return{done:o,fail:n}}function Bt(e){let t=n=>n.replace(/[.,;:]+$/u,""),o;for(let n of e){if(n.role!=="user"||typeof n.content!="string")continue;let r=n.content;for(let s of r.matchAll(/\bMarker\s*:\s*([A-Za-z0-9_.:-]+)/gi))o=t(s[1]);for(let s of r.matchAll(/\b(?:include|with|contains?)\s+marker\s+([A-Za-z0-9_.:-]+)/gi))o=t(s[1])}return o}function ue(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 Re(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xs(e,t){let o=ue(e);for(let n of[t.done,t.fail]){if(!n)continue;let s=new RegExp(`\\bfinal\\s+(?:answer|response|reply)\\s+exactly\\s*:?\\s*${Re(n)}([^\\n]*)`,"i").exec(o);if(s){let p=(s[1]??"").trimStart();if(p===""||/^[.!?]/u.test(p))return n}let a=new RegExp(`\\b(?:reply|respond)\\s+exactly(?:\\s+with)?\\s*:?\\s*${Re(n)}([^\\n]*)`,"i").exec(o);if(!a)continue;let u=(a[1]??"").trimStart();if(u===""||/^[.!?。!?]/u.test(u))return n}}function Dt(e,t){let o=xs(e,t);if(o)return o;let n=ue(e),r=Bt(e);if(r){let a=/\breply\s+with\s+(?:the\s+)?marker\s+plus\s+suffix\s+([A-Za-z0-9_.:-]+)\s+as\s+one\s+token\b/i.exec(n)?.[1]?.replace(/[.,;:]+$/u,"");if(a)return`${r}${a}`}return/\b(?:reply|respond)\s+exactly(?:\s+with)?\s*:?\s*([A-Za-z0-9_.:-]+)(?:\s*$|[.!?\u3002\uFF01\uFF1F])/i.exec(n)?.[1]?.replace(/[.,;:]+$/u,"")}function _s(e,t,o){let n=ue(e),r=[t.done,t.fail,o].filter(s=>typeof s=="string"&&s.length>0);return[...new Set(r)].filter(s=>new RegExp(`\\bstarts?\\s+with\\s+${Re(s)}\\b`,"i").test(n))}function ie(e){let t=Nt(e.inputMessages,e.messages).filter(n=>!Ft(n));return t.length===0?void 0:`${Lt(e.inputMessages)??"FAIL"} ${e.reason}. Missing required output file evidence: ${t.join(", ")}`}function ze(e){let t=be(e.inputMessages);if(!t.done){let n=Bt(e.inputMessages)??Dt(e.inputMessages,t);return n?`FAIL ${n} ${e.reason}. The model did not produce the requested final marker ${n}.`:void 0}return`${t.fail??"FAIL"} ${e.reason}. The model did not produce the requested final marker ${t.done}.`}function $t(e){let t=be(e.inputMessages),o=Dt(e.inputMessages,t);if(!o)return;if(He(e.inputMessages).length===0){let i=ue(e.inputMessages);return!mo(i)||!fo(e.messages).some(p=>p.includes(o))?void 0:go({inputMessages:e.inputMessages,messages:e.messages,finalText:""}).length===0?o:void 0}if(!(Nt(e.inputMessages,e.messages).filter(i=>!Ft(i)).length>0||yo(e.inputMessages,e.messages).length>0))return o}function Ut(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function jt(e){for(let t of["path","filePath","file_path"]){let o=e[t];if(typeof o=="string"&&o.trim())return o}}function ho(e){for(let t of["content","newContent","replacement","text"]){let o=e[t];if(typeof o=="string")return o}return""}function To(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let o=be(e.inputMessages);if(!o.done)return;let n=Ut(e.toolCall.function.arguments);if(!n)return;let r=jt(n),s=ho(n);if(!r||!s.includes(o.done))return;let i=He(e.inputMessages);if(i.length<2)return;let a=$(r);if(!i.some(m=>$(m)===a))return;let p=po(e.messages),f=i.filter(m=>$(m)!==a).filter(m=>!p.includes($(m)));if(f.length!==0)return`Premature completion artifact blocked: this write/edit attempted to store the requested DONE marker in ${r} before evidence existed for sibling required output files: ${f.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function J(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Ms(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 As(e){let t=[...e].reverse().find(o=>o.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
|
|
4
|
+
`)):""}function eo(e,t){let o=je(e,"")?.slice(0,600).trim(),n=`\u5DF2\u505C\u6B62\u672C\u8F6E\uFF1A\u5DE5\u5177\u8FDE\u7EED ${t} \u8F6E\u8C03\u7528\u5931\u8D25\uFF0C\u7EE7\u7EED\u91CD\u8BD5\u6CA1\u6709\u610F\u4E49\u3002`;return o?`${n}
|
|
7
5
|
|
|
8
|
-
\u923F\u72C5\u7B0D NOTE: You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail silently or produce incorrect results on this platform. Please use the 'write' tool directly to create the requested file with the correct content.`)}function Q(e,t,o,n){return{reason:e,messages:[...t,o,n],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function qt(e){let t=e.inputMessages.find(g=>g.role==="user"),o=typeof t?.content=="string"?t.content:"",n=is.test(o),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=be(e.inputMessages),i=Bt(e.inputMessages),a=_s(e.inputMessages,s,i),u=s.done!==void 0&&e.finalText.includes(s.done)||s.fail!==void 0&&e.finalText.includes(s.fail)||i!==void 0&&e.finalText.includes(i),p=a.length===0||a.some(g=>e.finalText.trimStart().startsWith(g)),f=Dt(e.inputMessages,s),m=Nt(e.inputMessages,e.messages);if(m.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${m.length} file(s) missing`);let g=Lt(e.inputMessages),T={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${m.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${g??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return Q("explicit_required_file_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}let C=yo(e.inputMessages,e.messages);if(C.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${C.length} unexpected file(s)`);let g=Lt(e.inputMessages),T={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${C.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${g??"FAIL"} and the real reason. Do not claim completion while extra deliverables remain.`};return Q("explicit_extra_file_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}let M=go({inputMessages:e.inputMessages,messages:e.messages,finalText:e.finalText});if(M.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`artifact index evidence verification: ${M.length} issue(s)`);let g=f??s.done??i??"the requested marker",T={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+M.map(b=>b.detail).join(" ")+` Use the exact requested Goal row labels, cite concrete evidence names/paths for status claims, and mark a row as not verified/unknown instead of claiming exhaustive absence without scoped evidence. Do not claim all checks pass while any row is failed, partial, missing, or unverified. After correcting and verifying the file, reply exactly with ${g}.`};return Q("artifact_index_evidence_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}if(a.length>0&&e.totalToolCallCount>0&&!p){e.log.info("final marker verification: explicit final marker was not at the start of the response");let g={role:"user",content:`The requested output file evidence is present, but your final response did not start with the explicit completion marker. Your final response must start with one of the requested final markers: ${a.join(" or ")}. No preface, heading, markdown emphasis, or summary may appear before the marker.`};return Q("final_marker_verification",e.messages,J(e.finalText,e.thinkingBlocks),g)}if((s.done!==void 0||i!==void 0)&&e.totalToolCallCount>0&&!u){e.log.info("final marker verification: explicit final DONE/FAIL marker missing");let g=s.done??i,T={role:"user",content:"The requested output file evidence is present, but your final response omitted the explicit completion marker. "+(s.done?`If you have verified the artifacts, Reply exactly with ${s.done}. `:`Your final response must include marker ${g} and clearly say whether the run passed or failed. `)+(s.fail?`If verification failed, reply with ${s.fail} and the real reason. `:`If verification failed, reply with FAIL ${g??""} and the real reason. `)+"Do not end the turn without one of the requested final markers."};return Q("final_marker_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}if(f!==void 0&&e.finalText.trim()!==f){e.log.info("final marker verification: exact-only final marker response had extra text");let g={role:"user",content:`Reply exactly with ${f} and no other text.`};return Q("final_marker_verification",e.messages,J(e.finalText,e.thinkingBlocks),g)}if(u&&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&&As(e.messages);let g={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 Q("file_action_verification",e.messages,J(e.finalText,e.thinkingBlocks),g)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(Ms).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let T={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 Q("multi_file_skeleton_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}return null}function vs(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function Co(e){if(!e.hooks)return null;let t=await e.hooks.invoke("stop",{sessionId:e.sessionId,reason:"completed"});if(t.action==="prevent")return e.log.info(`stop hook prevented continuation: ${t.reason??"no reason"}`),{action:"end",content:e.finalText};if(t.action==="abort"){let 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,vs(e.finalText,e.thinkingBlocks),n],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var Ss=5;function Es(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function ws(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function ko(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=Ss)return null;let t=Es(e.totalUsage),o=t/e.tokenBudget*100,n=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=An&&n<ct&&e.lastBudgetDeltaTokens<ct)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(o)}% (delta=${n})`),null;if(o>=90)return null;let s=e.budgetContinuationCount+1,i={role:"user",content:e.getBudgetContinuationMessage(o,t,e.tokenBudget)};return e.log.info(`token budget continuation #${s}: ${Math.round(o)}% used`),{messages:[...e.messages,ws(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:n,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(o)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function Ht(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 pt(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function Ro(e,t){let o=[],n=[];for(let r of e){let s=t.get(r.function.name)??0;s>=Oe?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 bo(){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 xo(e){if(e.ok&&!e.softEmpty)return;let t=e.toolFailureCounts.get(e.toolName)??0;e.toolFailureCounts.set(e.toolName,t+1)}function _o(e){let t=[];for(let[o,n]of e.toolFailureCounts)n>=Oe&&(e.snapshot.get(o)??0)<Oe&&t.push({role:"user",content:`Tool "${o}" has now failed/returned empty results ${n} times with different arguments. The target clearly does not exist. Do NOT call "${o}" again. Report the result to the user immediately.`});return t}function Ps(e,t){if(e.length!==1||e[0]?.function.name!=="stt")return!1;let o=[...t].reverse().find(i=>i.role==="user");if(!o)return!1;let n=Array.isArray(o.audioUrls)&&o.audioUrls.some(i=>typeof i=="string"&&i.trim()),r=typeof o.content=="string"?o.content:"",s=/\b(?:stt|speech[-\s]?to[-\s]?text|transcribe|transcription|audio[-\s]?to[-\s]?text)\b|转写|转录|语音转文字|音频转文字|听写/i.test(r);return n&&s}function Ls(e,t){let o=Os(t);if(!o)return null;let n=Fs(o);if(!n)return null;let r=[...e].reverse().find(a=>a.role==="user"),s=typeof r?.content=="string"?r.content:"",i=/\bAUDIO_STT_RESULT\s+([^\s<]+)\s+<transcription\b/i.exec(s);return i?.[1]?`AUDIO_STT_RESULT ${i[1]} ${n}`:n}function Os(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 Fs(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}var zt=new Set(["read","search"]),Ns=new Set(["write","edit","patch","image_generate"]);function Bs(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let o=t.slice(0,t.indexOf("::"));zt.has(o)&&e.identicalCallCounts.delete(t)}}async function*Mo(e,t,o,n){let{turnId:r,sessionId:s,messages:i,tools:a,model:u,apiKey:p,temperature:f=0,hooks:m,signal:C}=e,M={sessionId:s,turnId:r},g=e.maxTurns??0,T=e.querySource,b=e.runtimePorts.resolveToolEligibility(a,e.toolEligibilityContext),R=b.eligibleTools;for(let y of b.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:y.toolName,reason:"blocked-by-policy"};let A=Vn(e.maxRounds,i),O=Zn(e.maxToolCalls,i),xe=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),Ge=Ue(i),H={contextWindowTokens:e.contextWindowTokens??kn,responseBufferTokens:Rn,maxOutputTokens:e.maxOutputTokens??bn,abortSignal:C,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},w=new Set,F=0,de=0,pe=0,_e=0,W=R,Io=Ps(R,i),Me,We=!1,Gt=0,Wt=0,Ke=!1,Ae=!1,c={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Rt(H),reactiveCompactState:At(),toolLoopState:Be({maxRounds:A,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:it(),currentModel:u,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,finalMarkerEmptyRecoveryCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,fileReadCounts:new Map,recoveryTrace:new Map},Xe=Math.max(g*5,200),Kt=0,I=(y,N)=>(c.recoveryTrace.set(y,(c.recoveryTrace.get(y)??0)+1),{type:"recovery",turnId:r,action:y,detail:N}),L=y=>({type:"end",turnId:r,content:y,usage:c.totalUsage,model:c.currentModel,...c.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(c.recoveryTrace)}:{}}),me=(y,N)=>{let K=$t({inputMessages:i,messages:y});if(K)return K;if(c.finalText.trim()===""){let U=ze({inputMessages:i,reason:N});if(U)return U}return c.finalText||Et(y,n)},Po=(y,N,K)=>{let U=ie({inputMessages:i,messages:N,reason:K});if(U)return U;if(y.trim()===""){let v=ze({inputMessages:i,reason:K});if(v)return v}return y||Et(N,n)};for(;;){if(Kt++,Kt>Xe){n.info(`hard iteration cap reached (${Xe}), forcing completion`);let l=me(c.messages,`hard iteration cap reached (${Xe}) before producing the requested final marker`);yield L(l);return}let{messages:y,maxOutputTokensRecoveryCount:N,maxOutputTokensOverride:K,turnCount:U,guardState:v,reactiveCompactState:z,collapseStore:Ye}=c,{toolLoopState:B}=c;if(Me){try{let l=await Me;l&&(yield{type:"tool_use_summary",turnId:r,summary:l})}catch{}Me=void 0}if(e.refreshTools&&U>1){let l=e.refreshTools();l!==W&&(W=l,n.debug(`tools refreshed: ${l.length} tools`))}if(Mt(v,H)){n.info(`turn aborted by guard at turn ${U}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:c.totalUsage};return}let ee=bt(v,H);if(ee.level==="blocking"){ee.reason==="prompt_too_long"&&le(z)&&(z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${ee.reason}), reactive compact needed`),yield I("reactive_compact","token budget pre-check")),n.info(`token budget blocking (${ee.reason}), ending tool loop`);break}ee.level==="warning"&&n.info(`token budget warning: ${ee.usagePercent}% used, ${ee.remainingTokens} remaining`);let ve=yield*oo({messages:y,contentReplacementState:c.contentReplacementState,snipRemovedIds:c.snipRemovedIds,collapseStore:Ye,guardState:v,guardConfig:H,runtimePorts:e.runtimePorts,hooks:m,hookCtx:M,sessionId:s,currentModel:c.currentModel,log:n,recovery:I,onAutocompact:()=>{c.hasAttemptedReactiveCompact=!1}}),Lo=Ke?"required":e.toolChoice==="required"&&We?"auto":e.toolChoice??"auto";Ke=!1;let fe=mt({tools:W,toolChoice:Lo}),ge=Be({maxRounds:A,replayMessages:ve,lastStopReason:B.lastStopReason,options:{stopReason:B.lastStopReason}}),Xt=fe.extraSystemPrompt?[{role:"system",content:fe.extraSystemPrompt},...ge.state.replayMessages]:ge.state.replayMessages;B=ge.state,ge.recoveryActions.length>0&&n.debug(`tool loop recovery: ${ge.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),n.debug(`turn ${U}, messages: ${Xt.length}`),E(m,"turn.before_inference",{...M,model:c.currentModel},n);let Ve=!1,Ze=[],Yt=new Map,Vt="stop",D,x=null,Se=!1,Zt=!1,ye=[],G=[];try{for await(let l of t.stream({model:c.currentModel,messages:Xt,...fe.tools.length>0?{tools:fe.tools,toolChoice:fe.normalizedToolChoice??"auto"}:{},temperature:f,maxTokens:(K??v.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:Ae?void 0:c.lastResponseId,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},p,C))switch(l.type){case"delta":Ze.push(l.text);break;case"tool_call_delta":Ve=!0,vt(Yt,l);break;case"reasoning_delta":ye.push(l.text);break;case"reasoning_block_complete":l.signature&&G.push({thinking:ye.join(""),signature:l.signature}),ye.length=0;break;case"usage":D={inputTokens:l.promptTokens,outputTokens:l.completionTokens,reasoningTokens:l.reasoningTokens,cacheRead:l.cacheReadTokens,cacheWrite:l.cacheCreationTokens};break;case"response_id":Ae||(c.lastResponseId=l.id);break;case"annotations":yield{type:"annotations",turnId:r,annotations:l.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${l.toolType}: ${l.event}`};break;case"done":Zt=!0,Vt=l.finishReason;break}if(Ve||E(m,"turn.after_inference",{...M,model:c.currentModel},n),e.postSamplingHooks&&e.postSamplingHooks.length>0){let l=c.currentModel;for(let d of e.postSamplingHooks)try{d({messages:[...ve],model:l,sessionId:s})}catch{}}}catch(l){let d=yield*ro(l,{state:c,guardState:v,fallbackModel:e.fallbackModel,signal:C,querySource:T,turnId:r,log:n,emitRecovery:I});if(d.kind==="return")return;if(d.kind==="continue"){c={...c,...d.patch};continue}x=d.streamError}if(!x&&!Zt){let l="LLM stream closed before a terminal event; the response was likely truncated upstream.";E(m,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:l},n),yield{type:"error",turnId:r,error:l,code:"RETRYABLE_TRANSIENT",usage:c.totalUsage};return}if(x&&E(m,"turn.after_inference",{...M,model:c.currentModel,response:{error:x.message}},n),x){if(!Ae&&c.lastResponseId&&/previous_response_id not found/i.test(x.message)){let l=(c.consecutiveApiRetries??0)+1;if(l<=se){n.info("previous_response_id not found \u2014 disabling response-id chaining, retrying statelessly"),yield I("stateless_retry","previous_response_id not found; replaying full history"),Ae=!0,c={...c,lastResponseId:void 0,consecutiveApiRetries:l,transition:void 0};continue}}if(It(x))Se=!0,n.info(`withheld prompt_too_long error (status=${x.status})`);else if(Pt(x))Se=!0,n.info(`withheld media_size error (status=${x.status})`);else{let l=xt({status:x.status??500,message:x.message},v,H);if(l.action==="reactive_compact"&&le(z)&&(z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,yield I("reactive_compact",`API ${x.status??500}: ${x.message}`)),l.action==="retry"){let h=(c.consecutiveApiRetries??0)+1;if(h>se){n.info(`API retry limit reached (${se}), aborting`);let k=ae(x.status,x.message);yield{type:"error",turnId:r,error:x.message,code:k,usage:c.totalUsage};return}yield I("retry",l.reason),c={...c,consecutiveApiRetries:h,transition:void 0};continue}let d=ae(x.status,x.message);E(m,"stop.failure",{sessionId:s,reason:d,error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:d,usage:c.totalUsage};return}}D&&(c.totalUsage.inputTokens+=D.inputTokens,c.totalUsage.outputTokens+=D.outputTokens,D.reasoningTokens&&(c.totalUsage.reasoningTokens=(c.totalUsage.reasoningTokens??0)+D.reasoningTokens),D.cacheRead&&(c.totalUsage.cacheRead=(c.totalUsage.cacheRead??0)+D.cacheRead),D.cacheWrite&&(c.totalUsage.cacheWrite=(c.totalUsage.cacheWrite??0)+D.cacheWrite)),D?.inputTokens&&(v.promptTokens=D.inputTokens);let Ee=Ze.join(""),j=[...Yt.values()].map((l,d)=>({id:l.id||`tc_${r}_${d}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(j.length===0&&!Ve){if(Ee&&(c.finalText=Ee),e.toolChoice==="required"&&!We&&W.length>0&&Gt<2){Gt++;let _=W.map(P=>P.function.name).filter(Boolean).slice(0,8).join(", ");c={...c,messages:[...y,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${_}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(Se&&x&&It(x)){if(c.transition?.reason!=="collapse_drain_retry"){let _=lt(ve,Ye);if(_.committed>0){n.info(`collapse drain: committed ${_.committed} stages`),yield I("collapse_drain",`${_.committed} stages committed`),c={...c,messages:_.messages,transition:{reason:"collapse_drain_retry",committed:_.committed}};continue}}if(le(z)){z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info("withheld 413: reactive compact attempt"),yield I("reactive_compact","withheld prompt_too_long"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld 413: recovery exhausted, surfacing error"),E(m,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:"PROMPT_TOO_LONG",usage:c.totalUsage};return}if(Se&&x&&Pt(x)){if(le(z)){z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info("withheld media error: reactive compact strip-retry"),yield I("reactive_compact","media error strip-retry"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld media error: recovery exhausted"),E(m,"stop.failure",{sessionId:s,reason:"media_error",error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:"IMAGE_ERROR",usage:c.totalUsage};return}if(eo(Vt)){v.consecutiveTruncations+=1;let _=e.modelMaxOutputTokens??xn,P=_t(v,H,_);if(P.shouldEscalate&&K===void 0){v.currentMaxOutputTokens=P.newMax,n.info(`max_output_tokens escalate: ${P.newMax} tokens`),yield I("output_escalation",`${P.newMax} tokens`),c={...c,maxOutputTokensOverride:Mn,transition:{reason:"max_output_tokens_escalate"}};continue}if(N<_n){let Y={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 #${N+1}`),yield I("max_output_tokens_recovery",`attempt ${N+1}`),c={...c,messages:[...ve,Y],maxOutputTokensRecoveryCount:N+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:N+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else v.consecutiveTruncations=0;B=Ne(B,{replayMessages:y,lastStopReason:"completed"});let l=await Co({hooks:m,sessionId:s,messages:y,finalText:c.finalText,thinkingBlocks:G,log:n});if(l?.action==="end"){let _=Po(l.content,y,"stop hook prevented continuation before producing the requested final marker");yield L(_);return}if(l?.action==="continue"){c={...c,messages:l.messages,stopHookActive:l.stopHookActive,transition:l.transition};continue}let d=ko({tokenBudget:e.tokenBudget,totalUsage:c.totalUsage,budgetContinuationCount:c.budgetContinuationCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,messages:y,finalText:c.finalText,thinkingBlocks:G,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:n});if(d){yield I("budget_continuation",d.recoveryDetail),c={...c,messages:d.messages,budgetContinuationCount:d.budgetContinuationCount,lastBudgetDeltaTokens:d.lastBudgetDeltaTokens,lastBudgetGlobalTokens:d.lastBudgetGlobalTokens,transition:d.transition};continue}let h=qt({inputMessages:i,messages:y,finalText:c.finalText,thinkingBlocks:G,stopHookActive:c.stopHookActive,totalToolCallCount:F,distinctToolNames:w,log:n});if(h){if(c.stopHookActive&&(h.reason==="final_marker_verification"||c.finalText.trim()==="")){let _=ie({inputMessages:i,messages:h.messages,reason:"final marker verification produced an empty response after tool use"});if(_){yield L(_);return}if(h.reason==="final_marker_verification"&&c.finalText.trim()===""&&c.finalMarkerEmptyRecoveryCount<1){yield I("final_marker_empty_retry","one extra retry after empty marker nudge"),c={...c,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition,finalMarkerEmptyRecoveryCount:c.finalMarkerEmptyRecoveryCount+1};continue}let P=$t({inputMessages:i,messages:h.messages});if(P){yield L(P);return}let Y=ze({inputMessages:i,reason:"final marker verification produced an empty response after tool use"});if(Y){yield L(Y);return}}c={...c,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition};continue}if(F===0&&W.length>0&&e.toolChoice!=="none"&&Wt<1&&Yn(Ee)){Wt++,Ke=!0,yield I("intent_without_action","announced but did not act; forcing a tool call"),c={...c,messages:[...y,{role:"assistant",content:Ee},{role:"user",content:"You announced an action but did not take it. Carry it out NOW, in this response: call the appropriate tool to actually do what you just said you would do. Do not restate your intention or describe a plan \u2014 perform it."}],finalText:"",transition:{reason:"next_turn"}};continue}let k=Ht({totalToolCallCount:F,distinctToolNames:w,projectRoot:e.projectRoot});k&&(yield{type:"skill_instruction",turnId:r,instruction:k});let S=me(y,"the model ended with an empty response after tool use before producing the requested final marker");for(let _ of Ze)yield{type:"delta",turnId:r,text:_};yield L(S);return}let Oo=G.length===0&&ye.length>0?ye.join(""):void 0;y.push(nt(j,void 0,G.length>0?G:void 0,Oo)),B=Tt(B,{replayMessages:y,pendingToolCallIds:j.map(l=>l.id),completedToolCallIds:B.completedToolCallIds,lastStopReason:"tool_calls"});let we=c.identicalCallCounts,Jt=[],Ie=[],Qt=[],en=!1;for(let l of j){let d=`${l.function.name}::${l.function.arguments}`,h=we.get(d)??0;if(we.set(d,h+1),h+1>Cn){let k=zt.has(l.function.name)?c.identicalSuccessfulToolResults.get(d):void 0;if(k){Qt.push({call:l,result:k,repeatCount:h+1});continue}Ie.push(l),en||(en=!0,n.info(`AP4 blocked: ${l.function.name} repeated ${h+1}x`))}else Jt.push(l)}let X=[];for(let l of Qt){let d=l.call,h=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${l.repeatCount}); no additional tool execution was performed.
|
|
6
|
+
\u6700\u540E\u4E00\u6B21\u5DE5\u5177\u9519\u8BEF\uFF1A
|
|
7
|
+
${o}
|
|
9
8
|
|
|
10
|
-
${l.result.content}`,k=V(d.id,{ok:!0,payload:h,imageUrls:l.result.imageUrls,toolReferences:l.result.toolReferences});y.push(k),X.push(d.id),w.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!0,outputPreview:h.slice(0,2e3),durationMs:0,details:{type:d.function.name,reusedIdenticalCall:!0,repeatCount:l.repeatCount}}}for(let l of Ie){let d=we.get(`${l.function.name}::${l.function.arguments}`),h=St(y,l.function.name),k=h?`This exact tool call has been attempted ${d} times. Last error: ${h}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${d} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,S=V(l.id,{ok:!1,error:k});y.push(S),X.push(l.id),w.add(l.function.name),F++,yield{type:"tool_result",turnId:r,callId:l.id,name:l.function.name,ok:!1,error:k}}if(Ie.length>0){let l=St(y,Ie[0].function.name),d={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(l?`The error was: "${l}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};y.push(d)}let tn=[],Je=[];for(let l of Jt){let d=To({inputMessages:i,messages:y,toolCall:l});d?Je.push({call:l,error:d}):tn.push(l)}for(let l of Je){let d=l.call;y.push(V(d.id,{ok:!1,error:l.error})),X.push(d.id),w.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},n.info(`premature completion artifact blocked: ${d.function.name}`)}Je.length>0&&y.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 Fo=new Set(W.map(l=>l.function.name)),nn=[],on=[];for(let l of tn)Fo.has(l.function.name)?nn.push(l):on.push(l);for(let l of on){let d=`Tool "${l.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;y.push(V(l.id,{ok:!1,error:d})),X.push(l.id),n.warn(`unoffered tool call suppressed: ${l.function.name}`)}let Qe=Ro(nn,c.toolFailureCounts),et=Qe.allowed;if(xe&&et.length>Math.max(0,O-F)){let l=wt({currentToolBudget:O,currentRoundBudget:A,toolHardCap:100,roundHardCap:100,continuationCount:pe,successfulSinceLastCheck:de-_e,fileReadCounts:c.fileReadCounts,windowTools:re,windowRounds:25});l&&(O=l.nextToolBudget,A=l.nextRoundBudget,pe=l.continuationCount,_e=de,n.info(`tool budget continuation #${l.continuationCount}: tools\u2192${O}, rounds\u2192${A} (progress detected)`))}let rn=Math.max(0,O-F),he=rn>0?et.slice(0,rn):[],tt=et.slice(he.length),No=tt.length>0;if(Qe.blocked.length>0){for(let l of Qe.blocked){let d=l.call,h=V(d.id,{ok:!1,error:l.error});y.push(h),X.push(d.id),w.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},n.info(`variant tool blocked: ${d.function.name} failed ${l.failCount}x with different args`)}y.push(bo())}if(tt.length>0){let l=`Tool call budget exhausted (${O}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of tt){let h=V(d.id,{ok:!1,error:l});y.push(h),X.push(d.id),w.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l}}y.push({role:"user",content:`${l} You reached this turn's tool budget after ${pe} extension(s). Do NOT claim the task is complete or that all files were created if it is not. Be honest in your reply: (1) state plainly the turn stopped before finishing; (2) list concretely what is DONE vs what is still UNFINISHED; (3) tell the user to reply "\u7EE7\u7EED" to finish the rest. If explicitly requested output files are still missing, respond with the requested FAIL marker and the real reason.`})}for(let l of he){let d=l.function.arguments,h=W.find(k=>k.function.name===l.function.name);if(h?.backfillObservableInput)try{let k=JSON.parse(l.function.arguments),S={...k};h.backfillObservableInput(S),Object.keys(S).some(P=>!(P in k))&&(d=JSON.stringify(S))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:d,inputSummary:Qn(d)}}let Bo=new Map(c.toolFailureCounts),Pe=null;try{let l=e.runtimePorts.createStreamingToolExecutor({toolInvoker:o,hooks:m,sessionId:s,turnId:r,log:n,signal:C,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:hn});for(let d of he)l.addTool(d);for await(let d of l.getRemainingResults()){d.blocked&&(yield{type:"tool_blocked",turnId:r,callId:d.callId,name:d.toolName,reason:d.blockReason??"blocked"}),y.push(d.message),X.push(d.callId),w.add(d.toolName),F++;let h=d.ok&&Wn(d);if(d.ok&&!h&&(de+=1),xo({toolFailureCounts:c.toolFailureCounts,toolName:d.toolName,ok:d.ok,softEmpty:h}),d.ok&&Ns.has(d.toolName)&&Bs(c),d.ok&&!h&&zt.has(d.toolName)){let k=he.find(_=>_.id===d.callId),S=typeof d.message?.content=="string"?d.message.content:"";if(k&&S){let _=Array.isArray(d.message.imageUrls)?d.message.imageUrls.filter(Y=>typeof Y=="string"):void 0,P=Array.isArray(d.message.toolReferences)?d.message.toolReferences.filter(Y=>typeof Y=="string"):void 0;c.identicalSuccessfulToolResults.set(`${k.function.name}::${k.function.arguments}`,{content:S,imageUrls:_,toolReferences:P})}}if(d.ok&&d.toolName==="read"){let k=he.find(S=>S.id===d.callId);if(k)try{let S=JSON.parse(k.function.arguments),_=S.file_path??S.path??S.filePath??"";if(_){let P=c.fileReadCounts.get(_)??0;c.fileReadCounts.set(_,P+1)}}catch{}}yield Hn(r,d);for(let k of zn(r,d))yield k;for(let k of Gn({turnId:r,result:d,toolCalls:j}))yield k;!Pe&&Io&&d.toolName==="stt"&&d.ok&&(Pe=Ls(i,d))}}catch(l){let d=l instanceof Error?l.message:String(l);yield{type:"error",turnId:r,error:d,code:"TOOL_EXECUTION_ERROR",usage:c.totalUsage};return}if(Pe){yield L(Pe);return}if(y.push(..._o({toolFailureCounts:c.toolFailureCounts,snapshot:Bo})),No){let l=ie({inputMessages:i,messages:y,reason:`tool call budget exhausted (${O}) before completing all required files`});if(l){yield L(l);return}}if(B=Ne(B,{replayMessages:y,completedToolCallIds:[...B.completedToolCallIds,...X],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&j.length>0&&(We=!0),e.generateToolUseSummary&&j.length>0){let l=j.map(d=>({name:d.function.name,arguments:d.function.arguments}));Me=e.generateToolUseSummary(l).catch(()=>null)}let Do=j.length>0&&j.every(l=>{let d=y.find(k=>k?.role==="tool"&&k?.tool_call_id===l.id);if(!d)return!0;let h=d.content;return typeof h=="string"&&h.startsWith("Error: ")}),Te=c.consecutiveFailedRounds;if(Do){if(Te+=1,Te>=Tn){if(Ge>=3&&c.repeatedToolFailureRecoveryCount<1){let h=qt({inputMessages:i,messages:y,finalText:c.finalText,thinkingBlocks:[],stopHookActive:c.stopHookActive,totalToolCallCount:F,distinctToolNames:w,log:n});if(h?.reason==="explicit_required_file_verification"||h?.reason==="explicit_extra_file_verification"){yield I("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),c={...c,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}let l=ie({inputMessages:i,messages:y,reason:"repeated tool failures stopped the turn before completing all required files"});if(l){yield L(l);return}let d=me(y,"repeated tool failures stopped the turn before producing the requested final marker");n.info(`early exit: ${Te} consecutive failed rounds, returning ${c.finalText?"partial":"fallback"} response`),yield L(d);return}}else Te=0;let $o=3,sn=[...c.fileReadCounts.entries()].filter(([,l])=>l>=$o);if(sn.length>0){let l=sn.map(([h])=>h).join(", ");n.info(`AP5: file read cycle detected on ${l}, injecting nudge`);let d={role:"user",content:`You are reading the same files repeatedly (${l}). This indicates a circular dependency or cycle. Stop reading files, summarize your findings so far, and explain the circular structure to the user.`};y.push(d),c.fileReadCounts.clear()}let Le=U+1;if(g>0&&Le>g){if(n.info(`max turns reached (${g}), completing`),m){let h=await m.invoke("stop",{sessionId:s,reason:"max_turns"});if(h.action==="abort"){let k=h.reason??"Stop hook requested continuation after max_turns",S={role:"assistant",content:c.finalText,...G.length>0&&{thinkingBlocks:[...G]}};c={...c,messages:[...y,S,{role:"user",content:k}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let l=ie({inputMessages:i,messages:y,reason:`tool loop max turns reached (${g}) before completing all required files`});if(l){yield L(l);return}let d=me(y,`tool loop max turns reached (${g}) before producing the requested final marker`);yield L(d);return}if(xe&&Le>A){let l=wt({currentToolBudget:O,currentRoundBudget:A,toolHardCap:100,roundHardCap:100,continuationCount:pe,successfulSinceLastCheck:de-_e,fileReadCounts:c.fileReadCounts,windowTools:re,windowRounds:25});l&&(A=l.nextRoundBudget,O=l.nextToolBudget,pe=l.continuationCount,_e=de,n.info(`round budget continuation #${l.continuationCount}: rounds\u2192${A}, tools\u2192${O} (progress detected)`))}if(Le>A){n.info(`tool loop budget exhausted (${A} rounds), returning`);let l=Ht({totalToolCallCount:F,distinctToolNames:w,projectRoot:e.projectRoot});l&&(yield{type:"skill_instruction",turnId:r,instruction:l});let d=ie({inputMessages:i,messages:y,reason:`tool budget exhausted (${A} rounds) before completing all required files`});if(d){yield L(d);return}let h=me(y,`tool budget exhausted (${A} rounds) before producing the requested final marker`);yield L(h);return}c={messages:y,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Le,transition:{reason:"next_turn"},guardState:v,reactiveCompactState:z,toolLoopState:B,consecutiveFailedRounds:Te,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:Ye,currentModel:c.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:c.stopHookActive,lastResponseId:c.lastResponseId,snipRemovedIds:c.snipRemovedIds,contentReplacementState:c.contentReplacementState,budgetContinuationCount:c.budgetContinuationCount,finalMarkerEmptyRecoveryCount:c.finalMarkerEmptyRecoveryCount,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,identicalCallCounts:we,identicalSuccessfulToolResults:c.identicalSuccessfulToolResults,toolFailureCounts:c.toolFailureCounts,fileReadCounts:c.fileReadCounts,recoveryTrace:c.recoveryTrace}}}var Ds=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function So(e){let t=$s(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: ${vo(n.l1Amount)}; L2 long-term says: ${vo(n.l2Amount)}; action: ask the user which value is current before using it.`)}for(let n of e){let r=qs(n);o.push(`- [${r}] ${n.text}`)}return o.join(`
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
\u8BF7\u6839\u636E\u4E0A\u9762\u7684\u9519\u8BEF\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`:`${n}
|
|
10
|
+
|
|
11
|
+
\u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function to(e){let t,o;for(let r=e.length-1;r>=0;r--){let s=e[r];if(s?.role==="tool"&&typeof s.content=="string"&&s.content.startsWith("Error: ")){t=s.content.slice(7,807).trim(),o=typeof s.tool_call_id=="string"?s.tool_call_id:void 0;break}}if(!t)return null;let n;if(o)for(let r of e){let s=r.tool_calls;if(Array.isArray(s))for(let i of s){let a=i;if(a.id!==o)continue;let u=a.function;typeof u?.arguments=="string"&&(n=wt(u.arguments)??u.arguments.slice(0,200))}}return{role:"user",content:`\u4F60\u6700\u8FD1\u7684\u5DE5\u5177\u8C03\u7528\u8FDE\u7EED\u5931\u8D25\u4E86\u3002\u653E\u5F03\u4E4B\u524D\u5148\u505C\u4E0B\u6765\u7EA0\u6B63\u2014\u2014**\u4E0D\u8981\u518D\u91CD\u590D\u540C\u6837\u7684\u5931\u8D25\u547D\u4EE4**\u3002
|
|
12
|
+
|
|
13
|
+
`+(n?`\u6700\u540E\u4E00\u6B21\u8C03\u7528\uFF1A${n}
|
|
14
|
+
`:"")+`\u6700\u540E\u4E00\u6B21\u9519\u8BEF\uFF1A
|
|
15
|
+
${t}
|
|
16
|
+
|
|
17
|
+
\u8BF7\u6309\u9519\u8BEF\u4FE1\u606F\u7EA0\u6B63\u540E\u518D\u91CD\u8BD5\uFF1A\u5982\u679C\u662F\u547D\u4EE4\u884C\u5DE5\u5177\uFF0C\u5148\u7528\u5B83\u81EA\u5E26\u7684\u5E2E\u52A9\u786E\u8BA4\u6B63\u786E\u7684\u5B50\u547D\u4EE4/\u53C2\u6570/\u8BED\u6CD5\uFF08\u5982 \`<\u5DE5\u5177> --help\` \u6216 \`<\u5DE5\u5177> help <\u5B50\u547D\u4EE4>\`\uFF09\uFF0C\u4E0D\u8981\u51ED\u76F4\u89C9\u62FC\u547D\u4EE4\uFF1B\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}}function wt(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 It(e){if(e.continuationCount>=5||e.currentToolBudget>=e.toolHardCap&&e.currentRoundBudget>=e.roundHardCap||e.successfulSinceLastCheck<=0)return null;for(let t of e.fileReadCounts.values())if(t>=3)return null;return{nextToolBudget:Math.min(e.currentToolBudget+e.windowTools,e.toolHardCap),nextRoundBudget:Math.min(e.currentRoundBudget+e.windowRounds,e.roundHardCap),continuationCount:e.continuationCount+1}}function Pt(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 no(e){return e==="length"||e==="max_tokens"}function Lt(e){let t=e.message.toLowerCase();return(t.includes("image")||t.includes("media")||t.includes("file too large")||t.includes("payload too large"))&&(e.status===413||t.includes("too large")||t.includes("size"))}function oo(e){let t=e.headers;if(!t)return null;let 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 ro(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*so(e){let{messages:t,contentReplacementState:o,snipRemovedIds:n,collapseStore:r,guardConfig:s,runtimePorts:i,hooks:a,hookCtx:u,sessionId:p,currentModel:f,log:m,recovery:C,onAutocompact:M}=e,g;{let T=await i.enforceToolResultBudget(t,o,p);g=T.messages,T.newlyReplacedCount>0&&(m.info(`tool-result-budget: persisted ${T.newlyReplacedCount} oversized tool results`),yield C("tool_result_budget",`${T.newlyReplacedCount} persisted`))}{let T=it(g,n);g=T.messages,T.removedCount>0&&(m.info(`snip: removed ${T.removedCount} messages, freed ~${T.tokensFreed} tokens`),yield C("snip",`${T.removedCount} messages`))}{let b=new Te().compress(g,0);b.droppedCount>0&&(g=b.messages,m.info(`microcompact: cleared ${b.droppedCount} old tool results`))}if(g=lt(g,r).messages,s.contextWindowTokens>0){let T=s.contextWindowTokens*.75,b=i.getActiveContextCompressionEngine(),R;b?R=await b.compressAsync(g,T,{model:f,sessionId:p}):R=i.compressMessages(g,{budget:T,model:f}),R.droppedCount>0&&(g=R.messages,m.info(`autocompact: ${R.strategy}, dropped ${R.droppedCount}`),yield C("autocompact",`${R.strategy}: ${R.droppedCount} dropped`),M(),E(a,"context.after_compact",{...u,removedCount:R.droppedCount},m))}return g=Qn(g),g}async function*io(e,t){let{state:o,guardState:n,fallbackModel:r,signal:s,querySource:i,turnId:a,log:u,emitRecovery:p}=t;if(e instanceof Ce&&r)return u.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield p("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let f=e instanceof Error?e.message:String(e),m=typeof e?.status=="number"?e.status:void 0;if(!m&&f&&(f.includes("ECONNRESET")||f.includes("EPIPE"))){let M=(o.consecutiveApiRetries??0)+1;return M>ie?(u.info(`stale connection retry limit reached (${ie}), aborting`),yield{type:"error",turnId:a,error:f,code:"RETRIES_EXHAUSTED",usage:o.totalUsage},{kind:"return"}):(u.info(`stale connection (${f.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield p("stale_connection_retry",f.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:M,transition:void 0}})}let C=ro({status:m,message:f});if(C!==null)return u.info(`max_tokens overflow: adjusting to ${C}`),n.currentMaxOutputTokens=C,{kind:"continue",patch:{maxOutputTokensOverride:C,transition:void 0}};if(Rt(m)){o.consecutive529Errors++;let M=2,g=r&&o.currentModel!==r;if(o.consecutive529Errors>M&&!g&&!Ue())return u.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>=En&&r&&o.currentModel!==r)return u.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(Ue()){let T=$e(o.consecutive529Errors);u.info(`persistent retry: waiting ${T}ms (attempt ${o.consecutive529Errors})`);let b=T;for(;b>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(b/1e3)}s (${m})`};let R=Math.min(b,Sn);await new Promise(A=>setTimeout(A,R)),b-=R}return{kind:"continue",patch:{transition:void 0}}}if(kt(i)){let b=oo({status:m,message:f})??$e(o.consecutive529Errors);return u.info(`transient ${m}: retry in ${b}ms`),yield p("retry",`${m} retry in ${b}ms`),await new Promise(R=>setTimeout(R,b)),{kind:"continue",patch:{transition:void 0}}}u.info(`background source ${i}: not retrying ${m}`)}return{kind:"streamError",streamError:{status:m,message:f}}}import{readdirSync as po,statSync as ze}from"node:fs";var ls=/create\s+(?:a\s+)?file|write\s+(?:a\s+)?file|make\s+(?:a\s+)?file|\bfix\b|implement|modify|update|repair|generate\s+(?:a\s+)?file|new\s+file/i,cs=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,ao=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,us=/\b(?:in|into|under|to|at|output(?:\s+to)?|save(?:\s+to)?|saved?\s+under)\s+([A-Za-z]:[\\/][^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+)/gi,ds=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,ps=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*(?:[\\/][A-Za-z0-9][A-Za-z0-9._-]*)+\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},.;:\uFF0C\u3001\uFF1B\u3002])/gi,ms=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*(?:[\\/][A-Za-z0-9][A-Za-z0-9._-]*)+)[\\/]?(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,fs=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i,gs=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i;function $(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase()}function mo(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function lo(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function co(e,t,o){let n=Math.max(e.lastIndexOf(".",t),e.lastIndexOf(`
|
|
18
|
+
`,t),e.lastIndexOf(";",t),e.lastIndexOf("\u3002",t),e.lastIndexOf("\uFF1B",t))+1,r=e.slice(n,t).toLowerCase();if(/\b(?:do\s+not|don't|never)\s+(?:leave|create|write|include|keep|produce|add|generate)\b/i.test(r)||/\b(?:remove|delete|exclude)\b/i.test(r))return!0;let s=e.slice(Math.max(0,t-16),t+o.length);return new RegExp(`\\bno\\s+${ke(o)}\\b`,"i").test(s)}function uo(e){return e.replace(/https?:\/\/\S+/gu," ")}function Ge(e){let t=new Set,o=[],n=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B]+$/u,""),i=$(s);t.has(i)||(t.add(i),o.push(s))};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=uo(r.content);for(let i of s.matchAll(cs)){let a=i[0];n(a);let u=(i.index??0)+a.length,p=a.replace(/\\/g,"/"),f=p.lastIndexOf("/");if(f>=0){let m=p.slice(0,f+1);ao.lastIndex=u;let C;for(;(C=ao.exec(s))!==null;)n(`${m}${C[1]}`)}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=uo(r.content);if(!fs.test(s))continue;let i=Array.from(s.matchAll(us)).map(u=>mo(u[1]??"")).filter(u=>u&&!lo(u));if(i.length===0)continue;let a=i[i.length-1];for(let u of s.matchAll(ds)){let p=u[1];p&&(co(s,u.index??0,p)||n(`${a}/${p}`))}for(let u of s.matchAll(ps)){let p=u[1];p&&(co(s,u.index??0,p)||n(`${a}/${p}`))}for(let u of s.matchAll(ms)){let p=u[1];p&&(lo(p)||/(?:assets[\\/]generated|screenshots(?:[\\/]|$)|previews(?:[\\/]|$))/i.test(p)&&/\b(?:generated|bitmap|png|screenshots?|preview|previews|evidence|assets?|containing)\b/i.test(s)&&n(`${a}/${p}/*`))}gs.test(s)&&n(`${a}/previews/*`)}return o}function Ft(e){if(e.role!=="tool")return!1;let t=typeof e.content=="string"?e.content:"";return e.is_error!==!0&&!t.startsWith("Error:")}function fo(e){let t=new Set,o=new Map,n=[];for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let u=a,p=u.id,f=u.function;typeof p=="string"&&typeof f?.name=="string"&&o.set(p,f.name)}}for(let r of e){let s=r;if(Ft(s)){let i=s.tool_call_id;typeof i=="string"&&t.add(i),(typeof i=="string"?o.get(i):void 0)==="exec"&&typeof s.content=="string"&&n.push(s.content)}}for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let u=a,p=u.id;if(typeof p=="string"&&t.size>0&&!t.has(p))continue;let f=u.function;if(!(typeof f?.name!="string"||typeof f.arguments!="string"))try{let m=JSON.parse(f.arguments);if(f.name==="write"||f.name==="edit"){for(let C of["path","filePath","file_path"]){let M=m[C];typeof M=="string"&&n.push(M)}continue}if(f.name==="exec"){let C=m.command;typeof C=="string"&&n.push(C)}}catch{f.name==="exec"&&n.push(f.arguments)}}}return n.join(`
|
|
19
|
+
`).replace(/\\/g,"/").toLowerCase()}function Nt(e){try{if(e.endsWith("/*")){let o=e.slice(0,-2);return po(o,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return ze(`${o}/${r.name}`).size>0}catch{return!1}})}let t=ze(e);return t.isFile()&&t.size>0}catch{return!1}}function ys(e,t){let o=$(t);if(!o.endsWith("/*"))return e.includes(o);let n=o.slice(0,-1);return e.includes(n)}function hs(e){let t=de(e);return/\b(?:exactly|only)\b[^.\n]*(?:artifacts?|files?|outputs?|deliverables?)/i.test(t)||/(?:artifacts?|files?|outputs?|deliverables?)[^.\n]*\b(?:exactly|only)\b/i.test(t)}function Ts(e){let t=mo(e),o=t.lastIndexOf("/");return o>=0?t.slice(0,o):""}function Cs(e){if(e.length===0)return"";let t=e.map(n=>Ts(n).split("/")),o=[];for(let n=0;n<t[0].length;n++){let r=t[0][n];if(t.every(s=>s[n]?.toLowerCase()===r.toLowerCase()))o.push(r);else break}return o.join("/")}function ks(e,t){let o=$(e);return t.some(n=>{let r=$(n);return r.endsWith("/*")?o.startsWith(r.slice(0,-1)):o===r})}function Rs(e){let t=new Set,o=new Map;for(let n of e){let r=n,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,u=a.id,p=a.function;if(typeof u!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let f=jt(p.arguments);if(!f)continue;let m=qt(f);m&&o.set(u,m)}}for(let n of e){let r=n;if(!Ft(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...o.entries()].filter(([n])=>t.has(n)).map(([,n])=>n)}function go(e){return/\bartifact[-_\s]?index\b/i.test(e)&&(/\b(?:evidence|status|failed|partial|passed|verified)\b/i.test(e)||/\bGoal\s+\d+\b/i.test(e))}function bs(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function yo(e){let t=new Set,o=new Map;for(let n of e){let r=n,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,u=a.id,p=a.function;if(typeof u!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let f=jt(p.arguments);if(!f)continue;let m=qt(f)??"",C=Co(f);(/\bartifact[-_\s]?index\b/i.test(m)||/\bartifact[-_\s]?index\b/i.test(C))&&o.set(u,C)}}for(let n of e){let r=n;if(!Ft(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...o.entries()].filter(([n])=>t.has(n)).map(([,n])=>n).filter(n=>n.trim().length>0)}function ho(e){let t=de(e.inputMessages);if(!go(t))return[];let o=yo(e.messages).at(-1);if(!o)return[];let n=[],r=bs(t).filter(u=>!new RegExp(`\\b${ke(u)}\\b`,"i").test(o));r.length>0&&n.push({type:"missing_goal_labels",detail:`Missing requested row labels in the generated index: ${r.join(", ")}`});let s=/\b(?:failed|partial|missing|not\s+found|no\s+[^.\n|]*evidence)\b/i.test(o),i=/\b(?:all\s+checks\s+pass|confirmed\s*:\s*all|everything\s+(?:passes|passed)|fully\s+verified)\b/i.test(e.finalText);s&&i&&n.push({type:"overconfident_final",detail:"Final response claimed all checks pass while the generated index contains failed, partial, missing, or no-evidence rows."});let a=o.split(/\r?\n/u).filter(u=>/\bno\s+[^|\n]*(?:found|evidence|files?)\b/i.test(u)&&!/\b(?:not\s+verified|unverified|unknown|not\s+checked|search\s+scope|checked\s+path)\b/i.test(u));return a.length>0&&n.push({type:"unsupported_absence",detail:`Absence claims need scoped evidence or must be marked unverified: ${a.slice(0,3).join(" ; ")}`}),n}function xs(e){let t=[],o=n=>{let r;try{r=po(n,{withFileTypes:!0})}catch{return}for(let s of r){let i=`${n}/${s.name}`;if(s.isDirectory()){o(i);continue}if(s.isFile())try{ze(i).size>0&&t.push(i)}catch{}}};try{if(!ze(e).isDirectory())return[]}catch{return[]}return o(e),t}function To(e,t){if(!hs(e))return[];let o=Ge(e),n=o.filter(i=>!$(i).endsWith("/*"));if(n.length<2)return[];let r=Cs(n);if(!r||r.split("/").length<3)return[];let s=$(r);return[...new Set([...Rs(t),...xs(r)])].filter(i=>$(i).startsWith(`${s}/`)&&!ks(i,o)&&Nt(i))}function Bt(e,t){let o=Ge(e);if(o.length===0)return[];let n=fo(t);return o.filter(r=>!ys(n,r))}function Ot(e){return Re(e).fail}function _s(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function He(e){if(!e)return!1;let t=_s(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function Re(e){let t=r=>r.replace(/[.,;:]+$/u,""),o,n;for(let r of e)if(!(r.role!=="user"||typeof r.content!="string")){for(let s of r.content.matchAll(/\b(DONE|PASS)\s+([A-Za-z0-9_.:-]+)/gi))He(s[2])&&(o=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))He(s[1])&&(n=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))He(s[1])&&(o=`${t(s[1])} ${s[2].toUpperCase()}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+FAIL\b/gi))He(s[1])&&(n=`${t(s[1])} FAIL`)}return{done:o,fail:n}}function Dt(e){let t=n=>n.replace(/[.,;:]+$/u,""),o;for(let n of e){if(n.role!=="user"||typeof n.content!="string")continue;let r=n.content;for(let s of r.matchAll(/\bMarker\s*:\s*([A-Za-z0-9_.:-]+)/gi))o=t(s[1]);for(let s of r.matchAll(/\b(?:include|with|contains?)\s+marker\s+([A-Za-z0-9_.:-]+)/gi))o=t(s[1])}return o}function de(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 ke(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ms(e,t){let o=de(e);for(let n of[t.done,t.fail]){if(!n)continue;let s=new RegExp(`\\bfinal\\s+(?:answer|response|reply)\\s+exactly\\s*:?\\s*${ke(n)}([^\\n]*)`,"i").exec(o);if(s){let p=(s[1]??"").trimStart();if(p===""||/^[.!?]/u.test(p))return n}let a=new RegExp(`\\b(?:reply|respond)\\s+exactly(?:\\s+with)?\\s*:?\\s*${ke(n)}([^\\n]*)`,"i").exec(o);if(!a)continue;let u=(a[1]??"").trimStart();if(u===""||/^[.!?。!?]/u.test(u))return n}}function $t(e,t){let o=Ms(e,t);if(o)return o;let n=de(e),r=Dt(e);if(r){let a=/\breply\s+with\s+(?:the\s+)?marker\s+plus\s+suffix\s+([A-Za-z0-9_.:-]+)\s+as\s+one\s+token\b/i.exec(n)?.[1]?.replace(/[.,;:]+$/u,"");if(a)return`${r}${a}`}return/\b(?:reply|respond)\s+exactly(?:\s+with)?\s*:?\s*([A-Za-z0-9_.:-]+)(?:\s*$|[.!?\u3002\uFF01\uFF1F])/i.exec(n)?.[1]?.replace(/[.,;:]+$/u,"")}function As(e,t,o){let n=de(e),r=[t.done,t.fail,o].filter(s=>typeof s=="string"&&s.length>0);return[...new Set(r)].filter(s=>new RegExp(`\\bstarts?\\s+with\\s+${ke(s)}\\b`,"i").test(n))}function ae(e){let t=Bt(e.inputMessages,e.messages).filter(n=>!Nt(n));return t.length===0?void 0:`${Ot(e.inputMessages)??"FAIL"} ${e.reason}. Missing required output file evidence: ${t.join(", ")}`}function be(e){let t=Re(e.inputMessages);if(!t.done){let n=Dt(e.inputMessages)??$t(e.inputMessages,t);return n?`FAIL ${n} ${e.reason}. The model did not produce the requested final marker ${n}.`:void 0}return`${t.fail??"FAIL"} ${e.reason}. The model did not produce the requested final marker ${t.done}.`}function Ut(e){let t=Re(e.inputMessages),o=$t(e.inputMessages,t);if(!o)return;if(Ge(e.inputMessages).length===0){let i=de(e.inputMessages);return!go(i)||!yo(e.messages).some(p=>p.includes(o))?void 0:ho({inputMessages:e.inputMessages,messages:e.messages,finalText:""}).length===0?o:void 0}if(!(Bt(e.inputMessages,e.messages).filter(i=>!Nt(i)).length>0||To(e.inputMessages,e.messages).length>0))return o}function jt(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function qt(e){for(let t of["path","filePath","file_path"]){let o=e[t];if(typeof o=="string"&&o.trim())return o}}function Co(e){for(let t of["content","newContent","replacement","text"]){let o=e[t];if(typeof o=="string")return o}return""}function ko(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let o=Re(e.inputMessages);if(!o.done)return;let n=jt(e.toolCall.function.arguments);if(!n)return;let r=qt(n),s=Co(n);if(!r||!s.includes(o.done))return;let i=Ge(e.inputMessages);if(i.length<2)return;let a=$(r);if(!i.some(m=>$(m)===a))return;let p=fo(e.messages),f=i.filter(m=>$(m)!==a).filter(m=>!p.includes($(m)));if(f.length!==0)return`Premature completion artifact blocked: this write/edit attempted to store the requested DONE marker in ${r} before evidence existed for sibling required output files: ${f.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function J(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function vs(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 Ss(e){let t=[...e].reverse().find(o=>o.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
|
|
20
|
+
|
|
21
|
+
\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 Q(e,t,o,n){return{reason:e,messages:[...t,o,n],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function Ht(e){let t=e.inputMessages.find(g=>g.role==="user"),o=typeof t?.content=="string"?t.content:"",n=ls.test(o),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=Re(e.inputMessages),i=Dt(e.inputMessages),a=As(e.inputMessages,s,i),u=s.done!==void 0&&e.finalText.includes(s.done)||s.fail!==void 0&&e.finalText.includes(s.fail)||i!==void 0&&e.finalText.includes(i),p=a.length===0||a.some(g=>e.finalText.trimStart().startsWith(g)),f=$t(e.inputMessages,s),m=Bt(e.inputMessages,e.messages);if(m.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${m.length} file(s) missing`);let g=Ot(e.inputMessages),T={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${m.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${g??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return Q("explicit_required_file_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}let C=To(e.inputMessages,e.messages);if(C.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${C.length} unexpected file(s)`);let g=Ot(e.inputMessages),T={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${C.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${g??"FAIL"} and the real reason. Do not claim completion while extra deliverables remain.`};return Q("explicit_extra_file_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}let M=ho({inputMessages:e.inputMessages,messages:e.messages,finalText:e.finalText});if(M.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`artifact index evidence verification: ${M.length} issue(s)`);let g=f??s.done??i??"the requested marker",T={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+M.map(b=>b.detail).join(" ")+` Use the exact requested Goal row labels, cite concrete evidence names/paths for status claims, and mark a row as not verified/unknown instead of claiming exhaustive absence without scoped evidence. Do not claim all checks pass while any row is failed, partial, missing, or unverified. After correcting and verifying the file, reply exactly with ${g}.`};return Q("artifact_index_evidence_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}if(a.length>0&&e.totalToolCallCount>0&&!p){e.log.info("final marker verification: explicit final marker was not at the start of the response");let g={role:"user",content:`The requested output file evidence is present, but your final response did not start with the explicit completion marker. Your final response must start with one of the requested final markers: ${a.join(" or ")}. No preface, heading, markdown emphasis, or summary may appear before the marker.`};return Q("final_marker_verification",e.messages,J(e.finalText,e.thinkingBlocks),g)}if((s.done!==void 0||i!==void 0)&&e.totalToolCallCount>0&&!u){e.log.info("final marker verification: explicit final DONE/FAIL marker missing");let g=s.done??i,T={role:"user",content:"The requested output file evidence is present, but your final response omitted the explicit completion marker. "+(s.done?`If you have verified the artifacts, Reply exactly with ${s.done}. `:`Your final response must include marker ${g} and clearly say whether the run passed or failed. `)+(s.fail?`If verification failed, reply with ${s.fail} and the real reason. `:`If verification failed, reply with FAIL ${g??""} and the real reason. `)+"Do not end the turn without one of the requested final markers."};return Q("final_marker_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}if(f!==void 0&&e.finalText.trim()!==f){e.log.info("final marker verification: exact-only final marker response had extra text");let g={role:"user",content:`Reply exactly with ${f} and no other text.`};return Q("final_marker_verification",e.messages,J(e.finalText,e.thinkingBlocks),g)}if(u&&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&&Ss(e.messages);let g={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 Q("file_action_verification",e.messages,J(e.finalText,e.thinkingBlocks),g)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(vs).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let T={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 Q("multi_file_skeleton_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}return null}function Es(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function Ro(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,Es(e.finalText,e.thinkingBlocks),n],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var ws=5;function Is(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function Ps(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function bo(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=ws)return null;let t=Is(e.totalUsage),o=t/e.tokenBudget*100,n=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=vn&&n<ut&&e.lastBudgetDeltaTokens<ut)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(o)}% (delta=${n})`),null;if(o>=90)return null;let s=e.budgetContinuationCount+1,i={role:"user",content:e.getBudgetContinuationMessage(o,t,e.tokenBudget)};return e.log.info(`token budget continuation #${s}: ${Math.round(o)}% used`),{messages:[...e.messages,Ps(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:n,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(o)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function zt(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 mt(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function xo(e,t){let o=[],n=[];for(let r of e){let s=t.get(r.function.name)??0;s>=Fe?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 _o(){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 Mo(e){if(e.ok&&!e.softEmpty)return;let t=e.toolFailureCounts.get(e.toolName)??0;e.toolFailureCounts.set(e.toolName,t+1)}function Ao(e){let t=[];for(let[o,n]of e.toolFailureCounts)n>=Fe&&(e.snapshot.get(o)??0)<Fe&&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 Os(e,t){if(e.length!==1||e[0]?.function.name!=="stt")return!1;let o=[...t].reverse().find(i=>i.role==="user");if(!o)return!1;let n=Array.isArray(o.audioUrls)&&o.audioUrls.some(i=>typeof i=="string"&&i.trim()),r=typeof o.content=="string"?o.content:"",s=/\b(?:stt|speech[-\s]?to[-\s]?text|transcribe|transcription|audio[-\s]?to[-\s]?text)\b|转写|转录|语音转文字|音频转文字|听写/i.test(r);return n&&s}function Fs(e,t){let o=Ns(t);if(!o)return null;let n=Bs(o);if(!n)return null;let r=[...e].reverse().find(a=>a.role==="user"),s=typeof r?.content=="string"?r.content:"",i=/\bAUDIO_STT_RESULT\s+([^\s<]+)\s+<transcription\b/i.exec(s);return i?.[1]?`AUDIO_STT_RESULT ${i[1]} ${n}`:n}function Ns(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 Bs(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}var Gt=new Set(["read","search"]),Ds=new Set(["write","edit","patch","image_generate"]);function $s(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let o=t.slice(0,t.indexOf("::"));Gt.has(o)&&e.identicalCallCounts.delete(t)}}async function*vo(e,t,o,n){let{turnId:r,sessionId:s,messages:i,tools:a,model:u,apiKey:p,temperature:f=0,hooks:m,signal:C}=e,M={sessionId:s,turnId:r},g=e.maxTurns??0,T=e.querySource,b=e.runtimePorts.resolveToolEligibility(a,e.toolEligibilityContext),R=b.eligibleTools;for(let y of b.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:y.toolName,reason:"blocked-by-policy"};let A=Zn(e.maxRounds,i),L=Jn(e.maxToolCalls,i),xe=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),We=qe(i),H={contextWindowTokens:e.contextWindowTokens??Rn,responseBufferTokens:bn,maxOutputTokens:e.maxOutputTokens??xn,abortSignal:C,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},w=new Set,O=0,pe=0,me=0,_e=0,W=R,Lo=Os(R,i),Me,Ke=!1,Wt=0,Kt=0,Xe=!1,Ae=!1,c={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:bt(H),reactiveCompactState:vt(),toolLoopState:De({maxRounds:A,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:at(),currentModel:u,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,finalMarkerEmptyRecoveryCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,fileReadCounts:new Map,recoveryTrace:new Map},Ye=Math.max(g*5,200),Xt=0,I=(y,N)=>(c.recoveryTrace.set(y,(c.recoveryTrace.get(y)??0)+1),{type:"recovery",turnId:r,action:y,detail:N}),F=y=>({type:"end",turnId:r,content:y,usage:c.totalUsage,model:c.currentModel,...c.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(c.recoveryTrace)}:{}}),ve=(y,N)=>{let K=Ut({inputMessages:i,messages:y});if(K)return K;if(c.finalText.trim()===""){let U=be({inputMessages:i,reason:N});if(U)return U}return c.finalText||Et(y,n)},Oo=(y,N,K)=>{let U=ae({inputMessages:i,messages:N,reason:K});if(U)return U;if(y.trim()===""){let v=be({inputMessages:i,reason:K});if(v)return v}return y||Et(N,n)};for(;;){if(Xt++,Xt>Ye){n.info(`hard iteration cap reached (${Ye}), forcing completion`);let l=ve(c.messages,`hard iteration cap reached (${Ye}) before producing the requested final marker`);yield F(l);return}let{messages:y,maxOutputTokensRecoveryCount:N,maxOutputTokensOverride:K,turnCount:U,guardState:v,reactiveCompactState:z,collapseStore:Ve}=c,{toolLoopState:B}=c;if(Me){try{let l=await Me;l&&(yield{type:"tool_use_summary",turnId:r,summary:l})}catch{}Me=void 0}if(e.refreshTools&&U>1){let l=e.refreshTools();l!==W&&(W=l,n.debug(`tools refreshed: ${l.length} tools`))}if(At(v,H)){n.info(`turn aborted by guard at turn ${U}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:c.totalUsage};return}let ee=xt(v,H);if(ee.level==="blocking"){ee.reason==="prompt_too_long"&&ce(z)&&(z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${ee.reason}), reactive compact needed`),yield I("reactive_compact","token budget pre-check")),n.info(`token budget blocking (${ee.reason}), ending tool loop`);break}ee.level==="warning"&&n.info(`token budget warning: ${ee.usagePercent}% used, ${ee.remainingTokens} remaining`);let Se=yield*so({messages:y,contentReplacementState:c.contentReplacementState,snipRemovedIds:c.snipRemovedIds,collapseStore:Ve,guardState:v,guardConfig:H,runtimePorts:e.runtimePorts,hooks:m,hookCtx:M,sessionId:s,currentModel:c.currentModel,log:n,recovery:I,onAutocompact:()=>{c.hasAttemptedReactiveCompact=!1}}),Fo=Xe?"required":e.toolChoice==="required"&&Ke?"auto":e.toolChoice??"auto";Xe=!1;let fe=ft({tools:W,toolChoice:Fo}),ge=De({maxRounds:A,replayMessages:Se,lastStopReason:B.lastStopReason,options:{stopReason:B.lastStopReason}}),Yt=fe.extraSystemPrompt?[{role:"system",content:fe.extraSystemPrompt},...ge.state.replayMessages]:ge.state.replayMessages;B=ge.state,ge.recoveryActions.length>0&&n.debug(`tool loop recovery: ${ge.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),n.debug(`turn ${U}, messages: ${Yt.length}`),E(m,"turn.before_inference",{...M,model:c.currentModel},n);let Ze=!1,Je=[],Vt=new Map,Zt="stop",D,x=null,Ee=!1,Jt=!1,ye=[],G=[];try{for await(let l of t.stream({model:c.currentModel,messages:Yt,...fe.tools.length>0?{tools:fe.tools,toolChoice:fe.normalizedToolChoice??"auto"}:{},temperature:f,maxTokens:(K??v.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:Ae?void 0:c.lastResponseId,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},p,C))switch(l.type){case"delta":Je.push(l.text);break;case"tool_call_delta":Ze=!0,St(Vt,l);break;case"reasoning_delta":ye.push(l.text);break;case"reasoning_block_complete":l.signature&&G.push({thinking:ye.join(""),signature:l.signature}),ye.length=0;break;case"usage":D={inputTokens:l.promptTokens,outputTokens:l.completionTokens,reasoningTokens:l.reasoningTokens,cacheRead:l.cacheReadTokens,cacheWrite:l.cacheCreationTokens};break;case"response_id":Ae||(c.lastResponseId=l.id);break;case"annotations":yield{type:"annotations",turnId:r,annotations:l.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${l.toolType}: ${l.event}`};break;case"done":Jt=!0,Zt=l.finishReason;break}if(Ze||E(m,"turn.after_inference",{...M,model:c.currentModel},n),e.postSamplingHooks&&e.postSamplingHooks.length>0){let l=c.currentModel;for(let d of e.postSamplingHooks)try{d({messages:[...Se],model:l,sessionId:s})}catch{}}}catch(l){let d=yield*io(l,{state:c,guardState:v,fallbackModel:e.fallbackModel,signal:C,querySource:T,turnId:r,log:n,emitRecovery:I});if(d.kind==="return")return;if(d.kind==="continue"){c={...c,...d.patch};continue}x=d.streamError}if(!x&&!Jt){let l="LLM stream closed before a terminal event; the response was likely truncated upstream.";E(m,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:l},n),yield{type:"error",turnId:r,error:l,code:"RETRYABLE_TRANSIENT",usage:c.totalUsage};return}if(x&&E(m,"turn.after_inference",{...M,model:c.currentModel,response:{error:x.message}},n),x){if(!Ae&&c.lastResponseId&&/previous_response_id not found/i.test(x.message)){let l=(c.consecutiveApiRetries??0)+1;if(l<=ie){n.info("previous_response_id not found \u2014 disabling response-id chaining, retrying statelessly"),yield I("stateless_retry","previous_response_id not found; replaying full history"),Ae=!0,c={...c,lastResponseId:void 0,consecutiveApiRetries:l,transition:void 0};continue}}if(Pt(x))Ee=!0,n.info(`withheld prompt_too_long error (status=${x.status})`);else if(Lt(x))Ee=!0,n.info(`withheld media_size error (status=${x.status})`);else{let l=_t({status:x.status??500,message:x.message},v,H);if(l.action==="reactive_compact"&&ce(z)&&(z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,yield I("reactive_compact",`API ${x.status??500}: ${x.message}`)),l.action==="retry"){let h=(c.consecutiveApiRetries??0)+1;if(h>ie){n.info(`API retry limit reached (${ie}), aborting`);let k=le(x.status,x.message);yield{type:"error",turnId:r,error:x.message,code:k,usage:c.totalUsage};return}yield I("retry",l.reason),c={...c,consecutiveApiRetries:h,transition:void 0};continue}let d=le(x.status,x.message);E(m,"stop.failure",{sessionId:s,reason:d,error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:d,usage:c.totalUsage};return}}D&&(c.totalUsage.inputTokens+=D.inputTokens,c.totalUsage.outputTokens+=D.outputTokens,D.reasoningTokens&&(c.totalUsage.reasoningTokens=(c.totalUsage.reasoningTokens??0)+D.reasoningTokens),D.cacheRead&&(c.totalUsage.cacheRead=(c.totalUsage.cacheRead??0)+D.cacheRead),D.cacheWrite&&(c.totalUsage.cacheWrite=(c.totalUsage.cacheWrite??0)+D.cacheWrite)),D?.inputTokens&&(v.promptTokens=D.inputTokens);let we=Je.join(""),j=[...Vt.values()].map((l,d)=>({id:l.id||`tc_${r}_${d}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(j.length===0&&!Ze){if(we&&(c.finalText=we),e.toolChoice==="required"&&!Ke&&W.length>0&&Wt<2){Wt++;let _=W.map(P=>P.function.name).filter(Boolean).slice(0,8).join(", ");c={...c,messages:[...y,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${_}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(Ee&&x&&Pt(x)){if(c.transition?.reason!=="collapse_drain_retry"){let _=ct(Se,Ve);if(_.committed>0){n.info(`collapse drain: committed ${_.committed} stages`),yield I("collapse_drain",`${_.committed} stages committed`),c={...c,messages:_.messages,transition:{reason:"collapse_drain_retry",committed:_.committed}};continue}}if(ce(z)){z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info("withheld 413: reactive compact attempt"),yield I("reactive_compact","withheld prompt_too_long"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld 413: recovery exhausted, surfacing error"),E(m,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:"PROMPT_TOO_LONG",usage:c.totalUsage};return}if(Ee&&x&&Lt(x)){if(ce(z)){z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info("withheld media error: reactive compact strip-retry"),yield I("reactive_compact","media error strip-retry"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld media error: recovery exhausted"),E(m,"stop.failure",{sessionId:s,reason:"media_error",error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:"IMAGE_ERROR",usage:c.totalUsage};return}if(no(Zt)){v.consecutiveTruncations+=1;let _=e.modelMaxOutputTokens??_n,P=Mt(v,H,_);if(P.shouldEscalate&&K===void 0){v.currentMaxOutputTokens=P.newMax,n.info(`max_output_tokens escalate: ${P.newMax} tokens`),yield I("output_escalation",`${P.newMax} tokens`),c={...c,maxOutputTokensOverride:An,transition:{reason:"max_output_tokens_escalate"}};continue}if(N<Mn){let Y={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 #${N+1}`),yield I("max_output_tokens_recovery",`attempt ${N+1}`),c={...c,messages:[...Se,Y],maxOutputTokensRecoveryCount:N+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:N+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else v.consecutiveTruncations=0;B=Be(B,{replayMessages:y,lastStopReason:"completed"});let l=await Ro({hooks:m,sessionId:s,messages:y,finalText:c.finalText,thinkingBlocks:G,log:n});if(l?.action==="end"){let _=Oo(l.content,y,"stop hook prevented continuation before producing the requested final marker");yield F(_);return}if(l?.action==="continue"){c={...c,messages:l.messages,stopHookActive:l.stopHookActive,transition:l.transition};continue}let d=bo({tokenBudget:e.tokenBudget,totalUsage:c.totalUsage,budgetContinuationCount:c.budgetContinuationCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,messages:y,finalText:c.finalText,thinkingBlocks:G,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:n});if(d){yield I("budget_continuation",d.recoveryDetail),c={...c,messages:d.messages,budgetContinuationCount:d.budgetContinuationCount,lastBudgetDeltaTokens:d.lastBudgetDeltaTokens,lastBudgetGlobalTokens:d.lastBudgetGlobalTokens,transition:d.transition};continue}let h=Ht({inputMessages:i,messages:y,finalText:c.finalText,thinkingBlocks:G,stopHookActive:c.stopHookActive,totalToolCallCount:O,distinctToolNames:w,log:n});if(h){if(c.stopHookActive&&(h.reason==="final_marker_verification"||c.finalText.trim()==="")){let _=ae({inputMessages:i,messages:h.messages,reason:"final marker verification produced an empty response after tool use"});if(_){yield F(_);return}if(h.reason==="final_marker_verification"&&c.finalText.trim()===""&&c.finalMarkerEmptyRecoveryCount<1){yield I("final_marker_empty_retry","one extra retry after empty marker nudge"),c={...c,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition,finalMarkerEmptyRecoveryCount:c.finalMarkerEmptyRecoveryCount+1};continue}let P=Ut({inputMessages:i,messages:h.messages});if(P){yield F(P);return}let Y=be({inputMessages:i,reason:"final marker verification produced an empty response after tool use"});if(Y){yield F(Y);return}}c={...c,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition};continue}if(O===0&&W.length>0&&e.toolChoice!=="none"&&Kt<1&&Vn(we)){Kt++,Xe=!0,yield I("intent_without_action","announced but did not act; forcing a tool call"),c={...c,messages:[...y,{role:"assistant",content:we},{role:"user",content:"You announced an action but did not take it. Carry it out NOW, in this response: call the appropriate tool to actually do what you just said you would do. Do not restate your intention or describe a plan \u2014 perform it."}],finalText:"",transition:{reason:"next_turn"}};continue}let k=zt({totalToolCallCount:O,distinctToolNames:w,projectRoot:e.projectRoot});k&&(yield{type:"skill_instruction",turnId:r,instruction:k});let S=ve(y,"the model ended with an empty response after tool use before producing the requested final marker");for(let _ of Je)yield{type:"delta",turnId:r,text:_};yield F(S);return}let No=G.length===0&&ye.length>0?ye.join(""):void 0;y.push(ot(j,void 0,G.length>0?G:void 0,No)),B=Ct(B,{replayMessages:y,pendingToolCallIds:j.map(l=>l.id),completedToolCallIds:B.completedToolCallIds,lastStopReason:"tool_calls"});let Ie=c.identicalCallCounts,Qt=[],Pe=[],en=[],tn=!1;for(let l of j){let d=`${l.function.name}::${l.function.arguments}`,h=Ie.get(d)??0;if(Ie.set(d,h+1),h+1>kn){let k=Gt.has(l.function.name)?c.identicalSuccessfulToolResults.get(d):void 0;if(k){en.push({call:l,result:k,repeatCount:h+1});continue}Pe.push(l),tn||(tn=!0,n.info(`AP4 blocked: ${l.function.name} repeated ${h+1}x`))}else Qt.push(l)}let X=[];for(let l of en){let d=l.call,h=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${l.repeatCount}); no additional tool execution was performed.
|
|
22
|
+
|
|
23
|
+
${l.result.content}`,k=V(d.id,{ok:!0,payload:h,imageUrls:l.result.imageUrls,toolReferences:l.result.toolReferences});y.push(k),X.push(d.id),w.add(d.function.name),O++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!0,outputPreview:h.slice(0,2e3),durationMs:0,details:{type:d.function.name,reusedIdenticalCall:!0,repeatCount:l.repeatCount}}}for(let l of Pe){let d=Ie.get(`${l.function.name}::${l.function.arguments}`),h=je(y,l.function.name),k=h?`This exact tool call has been attempted ${d} times. Last error: ${h}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${d} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,S=V(l.id,{ok:!1,error:k});y.push(S),X.push(l.id),w.add(l.function.name),O++,yield{type:"tool_result",turnId:r,callId:l.id,name:l.function.name,ok:!1,error:k}}if(Pe.length>0){let l=je(y,Pe[0].function.name),d={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(l?`The error was: "${l}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};y.push(d)}let nn=[],Qe=[];for(let l of Qt){let d=ko({inputMessages:i,messages:y,toolCall:l});d?Qe.push({call:l,error:d}):nn.push(l)}for(let l of Qe){let d=l.call;y.push(V(d.id,{ok:!1,error:l.error})),X.push(d.id),w.add(d.function.name),O++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},n.info(`premature completion artifact blocked: ${d.function.name}`)}Qe.length>0&&y.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 Bo=new Set(W.map(l=>l.function.name)),on=[],rn=[];for(let l of nn)Bo.has(l.function.name)?on.push(l):rn.push(l);for(let l of rn){let d=`Tool "${l.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;y.push(V(l.id,{ok:!1,error:d})),X.push(l.id),n.warn(`unoffered tool call suppressed: ${l.function.name}`)}let et=xo(on,c.toolFailureCounts),tt=et.allowed;if(xe&&tt.length>Math.max(0,L-O)){let l=It({currentToolBudget:L,currentRoundBudget:A,toolHardCap:100,roundHardCap:100,continuationCount:me,successfulSinceLastCheck:pe-_e,fileReadCounts:c.fileReadCounts,windowTools:se,windowRounds:25});l&&(L=l.nextToolBudget,A=l.nextRoundBudget,me=l.continuationCount,_e=pe,n.info(`tool budget continuation #${l.continuationCount}: tools\u2192${L}, rounds\u2192${A} (progress detected)`))}let sn=Math.max(0,L-O),he=sn>0?tt.slice(0,sn):[],nt=tt.slice(he.length),Do=nt.length>0;if(et.blocked.length>0){for(let l of et.blocked){let d=l.call,h=V(d.id,{ok:!1,error:l.error});y.push(h),X.push(d.id),w.add(d.function.name),O++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},n.info(`variant tool blocked: ${d.function.name} failed ${l.failCount}x with different args`)}y.push(_o())}if(nt.length>0){let l=`Tool call budget exhausted (${L}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of nt){let h=V(d.id,{ok:!1,error:l});y.push(h),X.push(d.id),w.add(d.function.name),O++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l}}y.push({role:"user",content:`${l} You reached this turn's tool budget after ${me} extension(s). Do NOT claim the task is complete or that all files were created if it is not. Be honest in your reply: (1) state plainly the turn stopped before finishing; (2) list concretely what is DONE vs what is still UNFINISHED; (3) tell the user to reply "\u7EE7\u7EED" to finish the rest. If explicitly requested output files are still missing, respond with the requested FAIL marker and the real reason.`})}for(let l of he){let d=l.function.arguments,h=W.find(k=>k.function.name===l.function.name);if(h?.backfillObservableInput)try{let k=JSON.parse(l.function.arguments),S={...k};h.backfillObservableInput(S),Object.keys(S).some(P=>!(P in k))&&(d=JSON.stringify(S))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:d,inputSummary:wt(d)}}let $o=new Map(c.toolFailureCounts),Le=null;try{let l=e.runtimePorts.createStreamingToolExecutor({toolInvoker:o,hooks:m,sessionId:s,turnId:r,log:n,signal:C,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:Tn});for(let d of he)l.addTool(d);for await(let d of l.getRemainingResults()){d.blocked&&(yield{type:"tool_blocked",turnId:r,callId:d.callId,name:d.toolName,reason:d.blockReason??"blocked"}),y.push(d.message),X.push(d.callId),w.add(d.toolName),O++;let h=d.ok&&Kn(d);if(d.ok&&!h&&(pe+=1),Mo({toolFailureCounts:c.toolFailureCounts,toolName:d.toolName,ok:d.ok,softEmpty:h}),d.ok&&Ds.has(d.toolName)&&$s(c),d.ok&&!h&&Gt.has(d.toolName)){let k=he.find(_=>_.id===d.callId),S=typeof d.message?.content=="string"?d.message.content:"";if(k&&S){let _=Array.isArray(d.message.imageUrls)?d.message.imageUrls.filter(Y=>typeof Y=="string"):void 0,P=Array.isArray(d.message.toolReferences)?d.message.toolReferences.filter(Y=>typeof Y=="string"):void 0;c.identicalSuccessfulToolResults.set(`${k.function.name}::${k.function.arguments}`,{content:S,imageUrls:_,toolReferences:P})}}if(d.ok&&d.toolName==="read"){let k=he.find(S=>S.id===d.callId);if(k)try{let S=JSON.parse(k.function.arguments),_=S.file_path??S.path??S.filePath??"";if(_){let P=c.fileReadCounts.get(_)??0;c.fileReadCounts.set(_,P+1)}}catch{}}yield zn(r,d);for(let k of Gn(r,d))yield k;for(let k of Wn({turnId:r,result:d,toolCalls:j}))yield k;!Le&&Lo&&d.toolName==="stt"&&d.ok&&(Le=Fs(i,d))}}catch(l){let d=l instanceof Error?l.message:String(l);yield{type:"error",turnId:r,error:d,code:"TOOL_EXECUTION_ERROR",usage:c.totalUsage};return}if(Le){yield F(Le);return}if(y.push(...Ao({toolFailureCounts:c.toolFailureCounts,snapshot:$o})),Do){let l=ae({inputMessages:i,messages:y,reason:`tool call budget exhausted (${L}) before completing all required files`});if(l){yield F(l);return}}if(B=Be(B,{replayMessages:y,completedToolCallIds:[...B.completedToolCallIds,...X],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&j.length>0&&(Ke=!0),e.generateToolUseSummary&&j.length>0){let l=j.map(d=>({name:d.function.name,arguments:d.function.arguments}));Me=e.generateToolUseSummary(l).catch(()=>null)}let Uo=j.length>0&&j.every(l=>{let d=y.find(k=>k?.role==="tool"&&k?.tool_call_id===l.id);if(!d)return!0;let h=d.content;return typeof h=="string"&&h.startsWith("Error: ")}),te=c.consecutiveFailedRounds;if(Uo){if(te+=1,te>=Cn){if(We>=3&&c.repeatedToolFailureRecoveryCount<1){let h=Ht({inputMessages:i,messages:y,finalText:c.finalText,thinkingBlocks:[],stopHookActive:c.stopHookActive,totalToolCallCount:O,distinctToolNames:w,log:n});if(h?.reason==="explicit_required_file_verification"||h?.reason==="explicit_extra_file_verification"){yield I("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),c={...c,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}if(c.repeatedToolFailureRecoveryCount<1){let h=to(y);if(h){yield I("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),c={...c,messages:[...y,h],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}let l=`repeated tool failures (${te} rounds in a row)`,d=ae({inputMessages:i,messages:y,reason:`${l} before all required files were produced`})??(c.finalText.trim()?c.finalText:be({inputMessages:i,reason:l})??eo(y,te));n.info(`early exit: ${te} consecutive failed rounds, returning ${c.finalText?"partial":"fallback"} response`),yield F(d);return}}else te=0;let jo=3,an=[...c.fileReadCounts.entries()].filter(([,l])=>l>=jo);if(an.length>0){let l=an.map(([h])=>h).join(", ");n.info(`AP5: file read cycle detected on ${l}, injecting nudge`);let d={role:"user",content:`You are reading the same files repeatedly (${l}). This indicates a circular dependency or cycle. Stop reading files, summarize your findings so far, and explain the circular structure to the user.`};y.push(d),c.fileReadCounts.clear()}let Oe=U+1;if(g>0&&Oe>g){if(n.info(`max turns reached (${g}), completing`),m){let h=await m.invoke("stop",{sessionId:s,reason:"max_turns"});if(h.action==="abort"){let k=h.reason??"Stop hook requested continuation after max_turns",S={role:"assistant",content:c.finalText,...G.length>0&&{thinkingBlocks:[...G]}};c={...c,messages:[...y,S,{role:"user",content:k}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let l=ae({inputMessages:i,messages:y,reason:`tool loop max turns reached (${g}) before completing all required files`});if(l){yield F(l);return}let d=ve(y,`tool loop max turns reached (${g}) before producing the requested final marker`);yield F(d);return}if(xe&&Oe>A){let l=It({currentToolBudget:L,currentRoundBudget:A,toolHardCap:100,roundHardCap:100,continuationCount:me,successfulSinceLastCheck:pe-_e,fileReadCounts:c.fileReadCounts,windowTools:se,windowRounds:25});l&&(A=l.nextRoundBudget,L=l.nextToolBudget,me=l.continuationCount,_e=pe,n.info(`round budget continuation #${l.continuationCount}: rounds\u2192${A}, tools\u2192${L} (progress detected)`))}if(Oe>A){n.info(`tool loop budget exhausted (${A} rounds), returning`);let l=zt({totalToolCallCount:O,distinctToolNames:w,projectRoot:e.projectRoot});l&&(yield{type:"skill_instruction",turnId:r,instruction:l});let d=ae({inputMessages:i,messages:y,reason:`tool budget exhausted (${A} rounds) before completing all required files`});if(d){yield F(d);return}let h=ve(y,`tool budget exhausted (${A} rounds) before producing the requested final marker`);yield F(h);return}c={messages:y,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Oe,transition:{reason:"next_turn"},guardState:v,reactiveCompactState:z,toolLoopState:B,consecutiveFailedRounds:te,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:Ve,currentModel:c.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:c.stopHookActive,lastResponseId:c.lastResponseId,snipRemovedIds:c.snipRemovedIds,contentReplacementState:c.contentReplacementState,budgetContinuationCount:c.budgetContinuationCount,finalMarkerEmptyRecoveryCount:c.finalMarkerEmptyRecoveryCount,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,identicalCallCounts:Ie,identicalSuccessfulToolResults:c.identicalSuccessfulToolResults,toolFailureCounts:c.toolFailureCounts,fileReadCounts:c.fileReadCounts,recoveryTrace:c.recoveryTrace}}}var Us=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function wo(e){let t=js(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: ${Eo(n.l1Amount)}; L2 long-term says: ${Eo(n.l2Amount)}; action: ask the user which value is current before using it.`)}for(let n of e){let r=zs(n);o.push(`- [${r}] ${n.text}`)}return o.join(`
|
|
24
|
+
`)}function js(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>So(r.text)),o=e.filter(r=>r.source==="l2-long-term").flatMap(r=>So(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 Gs(n)}function So(e){let t=[];for(let o of e.split(/\r?\n/)){let n=o.trim();if(n)for(let r of Us){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(n))continue;let s=new RegExp(`${Ws(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let i of n.matchAll(s)){let a=Hs(i[1]);a!==null&&t.push({entity:qs(n,r),predicate:r,amount:a,text:n})}}}return t}function qs(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 Hs(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 zs(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 Eo(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function Gs(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 Ws(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ks=8192;async function Io(e){let{hooks:t,detectRecallCategories:o,log:n,sessionId:r,turnId:s,query:i}=e;try{let a=o(i),p=(await t.invoke("memory.before_recall",{sessionId:r,turnId:s,query:i,preferredCategories:a.preferred.length>0?a.preferred:void 0,deprioritizedCategories:a.deprioritized.length>0?a.deprioritized:void 0}))?.context?.recalledMemories,f=null;if(p&&p.length>0){let m=0,C=[];for(let M of p){let g=(M.text?.length??0)*2;if(m+g>Ks)break;C.push(M),m+=g}C.length>0&&(f=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
|
|
25
|
+
${wo(C)}`)}return E(t,"memory.after_recall",{sessionId:r,turnId:s,blockCount:p?.length??0},n),f}catch{return null}}var Po=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;configuredMaxRounds;projectRoot;runtimePorts;constructor(t){this.transport=t.llmTransport,this.apiKey=t.apiKey,this.toolInvoker=t.toolInvoker,this.log=t.log,this.hooks=t.hooks,this.projectRoot=t.projectRoot,this.runtimePorts=t.runtimePorts,this.configuredMaxRounds=typeof t.maxRounds=="number"&&Number.isFinite(t.maxRounds)?Math.min(t.maxRounds,100):void 0,this.maxRounds=Math.min(this.configuredMaxRounds??25,100)}async*run(t,o){let{turnId:n,messages:r,tools:s,systemPrompt:i,config:a}=t,u={sessionId:t.sessionId,turnId:n};yield{type:"start",turnId:n},E(this.hooks,"turn.submitted",{...u,prompt:r[r.length-1]?.content??void 0},this.log);let p=Tt(r),f=[];if(i&&f.push({role:"system",content:i}),f.push(...p),this.hooks){let g=p.filter(b=>b.role==="user").pop(),T=typeof g?.content=="string"?g.content.slice(0,500):void 0;if(T){let b=await Io({hooks:this.hooks,detectRecallCategories:R=>this.runtimePorts.detectRecallCategories(R),log:this.log,sessionId:t.sessionId,turnId:n,query:T});b&&f.splice(i?1:0,0,{role:"system",content:b})}}let m=a?.model??"",C=typeof a?.maxRounds=="number"&&Number.isFinite(a.maxRounds)?a.maxRounds:this.configuredMaxRounds,M=C===void 0?void 0:Math.min(C,100);try{let g=async A=>{let L=this.runtimePorts.resolveModelForPurpose("smallModel");if(!L)return null;try{let xe=A.map(w=>`${w.name}(${w.arguments.slice(0,200)})`).join(", "),We=this.transport.stream({model:L,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:xe}],tools:[],maxTokens:60},a?.apiKey??this.apiKey),H="";for await(let w of We)w.type==="delta"&&(H+=w.text);return H.trim()||null}catch{return null}},T=a?.reasoning;a?.reasoning?.effort==="auto"&&(T={...a?.reasoning,effort:"medium"});let b={turnId:n,sessionId:t.sessionId,messages:f,tools:s,model:m,apiKey:a?.apiKey??this.apiKey,temperature:a?.temperature,maxRounds:M,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:T,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:g,runtimePorts:this.runtimePorts.toolLoop,signal:o},R;for await(let A of vo(b,this.transport,this.toolInvoker,this.log))R=A,yield A;R?.type==="end"?E(this.hooks,"turn.completed",{...u},this.log):R?.type==="error"&&E(this.hooks,"turn.failed",{...u,code:R.code,error:R.error},this.log)}catch(g){if(o?.aborted)E(this.hooks,"turn.failed",{...u,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED"};else{let T=g instanceof Error?g.message:String(g),b=typeof g?.status=="number"?g.status:void 0,R=le(b,T);this.log.error(`turn ${n} error [${R}, retryable=${st(R)}]: ${T}`),E(this.hooks,"turn.failed",{...u,code:R,error:T},this.log),yield{type:"error",turnId:n,error:T,code:R}}}}};export{Po as Agent};
|