qlogicagent 2.15.8 → 2.15.10
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 +28 -14
- package/dist/cli.js +372 -358
- package/dist/index.js +370 -356
- package/dist/protocol.js +1 -1
- package/dist/types/agent/tool-loop/artifact-final-contract.d.ts +65 -0
- package/dist/types/agent/tool-loop/completion-action-policy.d.ts +1 -9
- package/dist/types/agent/tool-loop/tool-failure-policy.d.ts +1 -0
- package/dist/types/agent/tool-loop.d.ts +2 -10
- package/dist/types/agent/types.d.ts +74 -1
- package/dist/types/cli/agent-config-coordinator.d.ts +11 -0
- package/dist/types/cli/handlers/agents-handler.d.ts +14 -6
- package/dist/types/cli/handlers/project-handler.d.ts +8 -0
- package/dist/types/cli/turn-core.d.ts +2 -0
- package/dist/types/orchestration/solo-evaluator.d.ts +1 -6
- package/dist/types/protocol/notifications.d.ts +1 -1
- package/dist/types/protocol/wire/acp-agent-management.d.ts +13 -0
- package/dist/types/protocol/wire/agent-events.d.ts +3 -3
- package/dist/types/protocol/wire/agent-methods.d.ts +3 -1
- package/dist/types/protocol/wire/index.d.ts +1 -1
- package/dist/types/protocol/wire/notification-payloads.d.ts +81 -11
- package/dist/types/runtime/infra/acp-detector.d.ts +34 -2
- package/dist/types/runtime/infra/agent-install-runner.d.ts +23 -0
- package/dist/types/runtime/infra/agent-process.d.ts +10 -0
- package/dist/types/runtime/ports/agent-execution-contracts.d.ts +74 -1
- package/package.json +1 -1
package/dist/agent.js
CHANGED
|
@@ -1,25 +1,39 @@
|
|
|
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(`
|
|
1
|
+
function mt(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function H(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var kr=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,te={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]},xr=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,_r=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Ar=512,vr=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Sr=new Set([500,502,503,504,521,522,523,524,529]),Mr=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Er=["upgrade your plan","upgrade plan","current plan","subscription"],wr=["daily","weekly","monthly"],Ir=["try again","retry","temporary","cooldown"],Pr=["usage limit","rate limit","organization usage"],Lr=["organization","workspace"],Or=["billing period","exceeded","reached","exhausted"],Nr=/["']?(?: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,Fr=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function ne(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Br(e){return ne(e,te.format)}function _n(e){return ne(e,te.rateLimit)}function Dr(e){return ne(e,te.timeout)}function $r(e){return kr.test(e)}function gt(e){let t=e.toLowerCase();return t?e.length>Ar?_r.test(t):ne(t,te.billing)?!0:xr.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function An(e){return ne(e,te.authPermanent)}function Ur(e){return ne(e,te.auth)}function vn(e){return ne(e,te.overloaded)}function ee(e,t){return t.some(n=>e.includes(n))}function jr(e){return ee(e,Mr)||ee(e,Er)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function qr(e){let t=ee(e,wr),n=e.includes("spend limit")||e.includes("spending limit"),o=ee(e,Lr);return ee(e,Ir)&&ee(e,Pr)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||ee(e,Or))}function Hr(e){return e.trim().toLowerCase().replace(Fr,"").trim()}function Sn(e){let t=Hr(e);return!t||jr(t)?"billing":_n(t)||qr(t)?"rate_limit":"billing"}function zr(e){return Nr.test(e)?Sn(e):null}function Mn(e){let t=e.match(vr);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Gr(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Wr(e){let t=e.trim();if(!t)return!1;let n=Mn(t);return n?Sr.has(n.code):!1}function En(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?Sn(t):"billing":e===429?"rate_limit":e===401||e===403?t&&An(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&vn(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&>(t)?"billing":"format":null}function Kr(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 Xr(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 wn(e){if(Xr(e))return"session_expired";if(Kr(e))return"model_not_found";let t=zr(e);return t||($r(e)?gt(e)?"billing":"rate_limit":_n(e)?"rate_limit":vn(e)?"overloaded":Wr(e)?Mn(e.trim())?.code===529?"overloaded":"timeout":Gr(e)?"timeout":Br(e)?"format":gt(e)?"billing":Dr(e)?"timeout":An(e)?"auth_permanent":Ur(e)?"auth":null)}var Yr={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"},Vr=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function le(e,t){let n=En(e,t)??(t?wn(t):null);return n?Yr[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function ht(e){return Vr.has(e)}function In(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var Zr=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"]),be=class{constructor(t=20,n=In){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=t.length-this.preserveRecentCount,r=0,s=0;return{messages:t.map((l,c)=>{if(c>=o||l.role!=="tool"||typeof l.content!="string"||!l.name||!Zr.has(l.name)||l.content.length<=200)return l;let f=this.estimateTokens(l);return s+=f,r++,{...l,content:`[result cleared \u2014 ${l.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 yt(e,t,n=In){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let l of e){let c=l.tool_call_id??"";if(c&&t.has(c)){o+=n(l),r++,t.delete(c);continue}s.push(l)}let a=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:a}}function Tt(){return{stages:[]}}function Ct(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(l=>l.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=Pn(e,t),a=Jr(s,t,o);if(a.length===0)return{messages:s,stagedCount:0};for(let l of a)t.stages.push(l);return s=Pn(e,t),{messages:s,stagedCount:a.length}}function bt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:Ln(e,t),committed:n}}function Pn(e,t){return t.stages.filter(o=>o.committed).length===0?e:Ln(e,t)}function Ln(e,t){let n=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),o=[...e];for(let r of n){let[s,a]=r.range;if(s>=o.length)continue;let l=Math.min(a,o.length),c={role:"system",content:r.summary};o.splice(s,l-s,c)}return o}function Jr(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(c=>`${c.range[0]}-${c.range[1]}`)),a=-1,l=0;for(let c=0;c<o;c++){let f=e[c];if(f.role==="tool"||f.role==="assistant"&&typeof f.content=="string"&&f.content==="")a<0&&(a=c),l++;else{if(l>=3){let h=`${a}-${a+l}`;s.has(h)||r.push({id:`collapse_${a}_${a+l}`,range:[a,a+l],summary:`[${l} tool results collapsed]`,committed:!1})}a=-1,l=0}}if(l>=3){let c=`${a}-${a+l}`;s.has(c)||r.push({id:`collapse_${a}_${a+l}`,range:[a,a+l],summary:`[${l} tool results collapsed]`,committed:!1})}return r}import{existsSync as kt,readFileSync as Qn,writeFileSync as Qr,readdirSync as eo,mkdirSync as es}from"node:fs";import{join as xt,dirname as ts}from"node:path";var oe=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),On=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),Nn=3,Fn=2,Re=2,Bn=128e3,Dn=13e3,$n=16384,Un=65536,jn=3,qn=65536,Rt=500,Hn=3;var zn=3e4,Gn=3,re=2;var Wn=20;var Kn=3,Xn=2,Yn=300*1e3,Vn=3,Zn=720*60*60*1e3;var ga=300*1e3;var ha=3600*1e3;var ya=50*1024,Ta=500*1024,Ca=500*1024*1024,ba=50*1024*1024;var Ra=60*1024;var to=0;var ns="skill-patterns.json";function no(e){return xt(e,".qlogicagent",ns)}function os(e){let t=no(e);try{return JSON.parse(Qn(t,"utf8"))}catch{return{version:1,patterns:{}}}}function Jn(e,t){let n=no(e);es(ts(n),{recursive:!0}),Qr(n,JSON.stringify(t,null,2),"utf8")}function rs(e){let t=Date.now()-Zn;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function oo(e,t){if(t.length===0)return!1;let n=Ue(t),o=os(e);rs(o);let r=new Date().toISOString(),s=o.patterns[n];if(s||(s={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=s),s.promoted)return Jn(e,o),!1;s.count++,s.lastSeen=r;let a=s.count>=Vn;return a&&(s.promoted=!0),Jn(e,o),a}function Ue(e){return[...e].sort().join("+")}function ss(e,t){if(!kt(t))return null;let n=Ue(e);try{let o=eo(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let s=xt(t,r.name,"SKILL.md");try{let l=Qn(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(l){let c=l[1].split(`
|
|
2
|
+
`).map(f=>f.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(Ue(c)===n)return r.name}}catch{}}}catch{}return null}function is(e){if(!kt(e))return 0;try{return eo(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&kt(xt(e,t.name,"SKILL.md"))).length}catch{return 0}}function as(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<Kn||e.distinctToolCount<Xn||Date.now()-to<Yn||t?.projectSkillsDir&&(is(t.projectSkillsDir)>=Wn||t.tools.length>0&&ss(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!oo(t.projectRoot,t.tools))}function ls(e){return e.existingSkillName?e.feedback==="negative":!1}function _t(e,t){return ls(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:as(e,t)?(to=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 ro(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 cs(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function us(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function ds(e){if(!e.eligibility?.length)return[...e.tools];let t=us(e.eligibility);return e.tools.filter(n=>{let o=ro(n);if(!o)return!1;let r=t.get(o);return!r||cs(r.status)})}function ps(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function At(e){let t=ps({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=ds({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,a=typeof s?.name=="string"?s.name.trim():"";if(!a)throw new Error("tool_choice.function.name is required");let l=r.filter(c=>ro(c)===a);if(l.length===0)throw new Error(`tool_choice requested unknown tool: ${a}`);return{tools:l,normalizedToolChoice:{type:"function",function:{name:a}},extraSystemPrompt:`You must call the ${a} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var fs=["stop","aborted","timeout","cancelled","interrupted","error"],ms=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function so(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function gs(e,t){return{...e,content:[...so(e.content),...so(t.content)]}}function hs(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function ys(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let s=hs(r);if(s.size!==0)for(let a=o+1;a<e.length;a+=1){if(t.has(a))continue;let l=e[a];l?.role==="tool"&&typeof l.tool_call_id=="string"&&s.has(l.tool_call_id)&&(n.push(l),t.add(a))}}return n}function Ts(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 Cs(e){return new Set((e??fs).map(t=>t.trim().toLowerCase()))}function bs(e,t){return e?Cs(t).has(e.trim().toLowerCase()):!1}function vt(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(c=>{if(c.role==="assistant"&&Array.isArray(c.tool_calls)){let f=c.tool_calls.filter(g=>Ts(g));return{...c,...f.length>0?{tool_calls:f}:{tool_calls:void 0}}}return{...c}}),n=new Set;for(let c of t)if(!(c.role!=="assistant"||!Array.isArray(c.tool_calls)))for(let f of c.tool_calls)typeof f.id=="string"&&f.id&&n.add(f.id);let o=t.filter(c=>c.role!=="tool"?!0:!!(c.tool_call_id&&n.has(c.tool_call_id))),r=new Set;for(let c of o)c.role==="tool"&&typeof c.tool_call_id=="string"&&c.tool_call_id&&r.add(c.tool_call_id);let s=[];for(let c of o){if(c.role==="assistant"&&Array.isArray(c.tool_calls)&&c.tool_calls.length>0){let f=c.tool_calls.filter(g=>typeof g.id=="string"&&r.has(g.id));if(f.length===0){let{tool_calls:g,...h}=c;h.content!=null&&h.content!==""&&s.push(h);continue}if(f.length<c.tool_calls.length){s.push({...c,tool_calls:f});continue}}s.push(c)}let a=ys(s),l=[];for(let c of a){let f=l.length>0?l[l.length-1]:void 0;if(c.role==="user"&&f?.role==="user"){l[l.length-1]=gs(f,c);continue}l.push(c)}return l}function St(e,t){return bs(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of ms)delete o[r];return o}):[...e]}function Mt(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.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 a of s.tool_calls)typeof a.id!="string"||!a.id||o.has(a.id)||(o.add(a.id),r.push({role:"tool",tool_call_id:a.id,content:n}));return r}function Et(e,t){let n=vt(e),o=St(n,t);return Mt(o,t)}function Rs(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function ks(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function xs(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function wt(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 je(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 qe(e){let t=[],n=vt(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=St(n,e.options);o.some((s,a)=>s!==n[a])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=Mt(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:xs({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Rs(r),completedToolCallIds:ks(r)}),recoveryActions:t}}var _s=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function It(e){return e?_s.has(e):!0}function Pt(e){return e===429||e===529}function He(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var La={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function ze(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var ke=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function Lt(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Ot(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function Nt(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function Ft(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function Bt(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var vs={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Dt(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function ce(e,t=vs){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}import{createHash as Li}from"node:crypto";function $t(e,t){let n=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(n.id=t.id),t.name&&(n.name=t.name),n.arguments+=t.arguments??"",e.set(t.index,n)}function M(e,t,n,o){e?.invoke(t,n).catch(r=>{let s=r instanceof Error?r.message:String(r);o.warn(`[hook:${t}] handler failed: ${s}`)})}function io(e,t){let n=typeof t.message?.content=="string"?t.message.content:"",o=n?n.slice(0,2e3):void 0,r=t.details,s=typeof r?.stdout=="string"?r.stdout.slice(0,8e3):void 0,a=typeof r?.stderr=="string"?r.stderr.slice(0,4e3):void 0,l=typeof r?.exitCode=="number"?r.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:o,durationMs:t.durationMs,exitCode:l,stdout:s,stderr:a,details:r}}function ao(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=Ss(n);return o?(Array.isArray(n.mediaUrls)?n.mediaUrls.filter(s=>typeof s=="string"&&s.trim().length>0):[]).map(s=>({type:"media_result",turnId:e,mediaType:o,url:s,model:typeof n.model=="string"?n.model:void 0,provider:typeof n.provider=="string"?n.provider:void 0,durationSeconds:typeof n.durationMs=="number"?n.durationMs/1e3:void 0,taskId:typeof n.taskId=="string"?n.taskId:void 0})):[]}function Ss(e){let t=typeof e.type=="string"?e.type:"";if(!t)return null;if(t==="three_d_generate")return"3d";let n=t.split("_")[0];return n==="image"||n==="tts"||n==="video"||n==="music"?n:null}var Ms=new Set(["write","edit","patch"]);function lo(e){let{turnId:t,result:n,toolCalls:o}=e;if(!n.ok)return[];let r=o.find(l=>l.id===n.callId);if(!r)return[];let s=[],a=Es(r.function.arguments);if(!a)return s;if(Ms.has(n.toolName)){let l=ws(a);l&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:Is(l),title:l.split(/[\\/]/).pop()||l,filePath:l,language:Ps(l)})}return s}function Es(e){try{return JSON.parse(e)}catch{return null}}function ws(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 Is(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 Ps(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 Ls=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,Os=new Set(["search","web_search","grep","glob","find","list","read","exec"]),Ns=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,Fs=/(?:^|[\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,Bs=/(?:^|[\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,Ds=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i;function co(e){if(!Os.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&Ls.test(t)}function Ge(e,t){for(let n=e.length-1;n>=0;n--){let o=e[n];if(!o||o.role!=="tool")continue;let r=typeof o.content=="string"?o.content:"";if(r.startsWith("Error: "))return r.slice(7).trim()}}var $s=/\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,uo=50;function po(e){if(!e)return!1;for(let t of e)if(t.role==="user"&&typeof t.content=="string"&&$s.test(t.content))return!0;return!1}var Us=/(?:我来|我先|我现在就?|让我先?|接下来我?|我帮你|我这就|我会|我将|我去|我看)[^。.!?!?\n]{0,12}(?:做|搭建?|写|开发|实现|构建|生成|创建|新建|建立|改|修复?|检查|读取?|运行|跑|执行|看一?下?|查看|配置|安装|部署|分析|整理|定位|排查|找)/,js=/\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 fo(e){let t=e.trim();return t.length===0||t.length>200||t.includes("```")?!1:Us.test(t)||js.test(t)}function mo(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=We(t);return n>=3?Math.min(Math.max(25,20+n*15),100):po(t)?Math.min(Math.max(25,uo),100):25}function We(e){if(!e)return 0;let t=new Set,n=new Set,o=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase();t.add(`path:${s}`);let a=s.split("/").pop();a&&n.add(a)};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content;for(let a of r.content.matchAll(Ns))o(a[0]);if(Ds.test(s)){for(let a of s.matchAll(Fs)){let l=a[1]?.toLowerCase();if(!l)continue;t.add(`relative:${l.replace(/\\/g,"/")}`);let c=l.replace(/\\/g,"/").split("/").pop();c&&n.add(c)}for(let a of s.matchAll(Bs)){let l=a[1]?.toLowerCase();!l||n.has(l)||t.add(`name:${l}`)}}}return t.size}function go(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=We(t);return n>=3?Math.min(Math.max(oe,20+n*15),100):po(t)?Math.min(Math.max(oe,uo),100):oe}function ho(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function Ut(e,t){let n=[];for(let o=e.length-1;o>=0;o--){let r=e[o];if(r.role==="tool"&&typeof r.content=="string")n.unshift(r.content.slice(0,500));else if(r.role==="assistant"){if(typeof r.content=="string"&&r.content.trim())return t.info("synthesizeFallbackContent: found assistant text, using it"),r.content;break}else break}return n.length>0?(t.info(`synthesizeFallbackContent: synthesized from ${n.length} tool result(s)`),n.join(`
|
|
3
3
|
|
|
4
|
-
`)):""}function
|
|
4
|
+
`)):""}function jt(e,t){let n=Ge(e,"")?.slice(0,600).trim(),o=`\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 n?`${o}
|
|
5
5
|
|
|
6
6
|
\u6700\u540E\u4E00\u6B21\u5DE5\u5177\u9519\u8BEF\uFF1A
|
|
7
|
-
${
|
|
7
|
+
${n}
|
|
8
8
|
|
|
9
|
-
\u8BF7\u6839\u636E\u4E0A\u9762\u7684\u9519\u8BEF\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`:`${
|
|
9
|
+
\u8BF7\u6839\u636E\u4E0A\u9762\u7684\u9519\u8BEF\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`:`${o}
|
|
10
10
|
|
|
11
|
-
\u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function
|
|
11
|
+
\u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function yo(e){let t,n;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(),n=typeof s.tool_call_id=="string"?s.tool_call_id:void 0;break}}if(!t)return null;let o;if(n)for(let r of e){let s=r.tool_calls;if(Array.isArray(s))for(let a of s){let l=a;if(l.id!==n)continue;let c=l.function;typeof c?.arguments=="string"&&(o=qt(c.arguments)??c.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
12
|
|
|
13
|
-
`+(
|
|
13
|
+
`+(o?`\u6700\u540E\u4E00\u6B21\u8C03\u7528\uFF1A${o}
|
|
14
14
|
`:"")+`\u6700\u540E\u4E00\u6B21\u9519\u8BEF\uFF1A
|
|
15
15
|
${t}
|
|
16
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
|
|
18
|
-
`,t),e.lastIndexOf(";",t),e.lastIndexOf("\u3002",t),e.lastIndexOf("\uFF1B",t))+1,r=e.slice(
|
|
19
|
-
`).replace(/\\/g,"/").toLowerCase()}function
|
|
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 qt(e){try{let t=JSON.parse(e),o=[t.description,t.command,t.query,t.url,t.path,t.file_path,t.filePath,t.pattern,t.model].find(s=>typeof s=="string"&&s.trim().length>0);if(typeof o=="string")return o.trim().slice(0,240);let r=Object.keys(t);return r.length>0?r.slice(0,5).join(" / "):void 0}catch{return}}function Ht(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 zt(e){let t=e.message.toLowerCase();return e.status===413||t.includes("prompt_too_long")||t.includes("context_length_exceeded")||t.includes("maximum context length")}function To(e){return e==="length"||e==="max_tokens"}function Gt(e){let t=e.message.toLowerCase();return(t.includes("image")||t.includes("media")||t.includes("file too large")||t.includes("payload too large"))&&(e.status===413||t.includes("too large")||t.includes("size"))}function Co(e){let t=e.headers;if(!t)return null;let n=t["retry-after"]??t["Retry-After"];if(!n)return null;let o=parseInt(n,10);return!isNaN(o)&&o>0?o*1e3:null}function bo(e){if(e.status!==400)return null;let t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!t?.[1]||!t?.[3])return null;let n=parseInt(t[1],10),o=parseInt(t[3],10);if(isNaN(n)||isNaN(o))return null;let r=o-n-1e3;return r>=3e3?r:null}async function*Ro(e){let{messages:t,contentReplacementState:n,snipRemovedIds:o,collapseStore:r,guardConfig:s,runtimePorts:a,hooks:l,hookCtx:c,sessionId:f,currentModel:g,log:h,recovery:T,onAutocompact:_}=e,x;{let C=await a.enforceToolResultBudget(t,n,f);x=C.messages,C.newlyReplacedCount>0&&(h.info(`tool-result-budget: persisted ${C.newlyReplacedCount} oversized tool results`),yield T("tool_result_budget",`${C.newlyReplacedCount} persisted`))}{let C=yt(x,o);x=C.messages,C.removedCount>0&&(h.info(`snip: removed ${C.removedCount} messages, freed ~${C.tokensFreed} tokens`),yield T("snip",`${C.removedCount} messages`))}{let k=new be().compress(x,0);k.droppedCount>0&&(x=k.messages,h.info(`microcompact: cleared ${k.droppedCount} old tool results`))}if(x=Ct(x,r).messages,s.contextWindowTokens>0){let C=s.contextWindowTokens*.75,k=a.getActiveContextCompressionEngine(),b;k?b=await k.compressAsync(x,C,{model:g,sessionId:f}):b=a.compressMessages(x,{budget:C,model:g}),b.droppedCount>0&&(x=b.messages,h.info(`autocompact: ${b.strategy}, dropped ${b.droppedCount}`),yield T("autocompact",`${b.strategy}: ${b.droppedCount} dropped`),yield{type:"lifecycle",turnId:c.turnId,kind:"context_compression",status:"completed",detail:`${b.strategy}: ${b.droppedCount} dropped`},_(),M(l,"context.after_compact",{...c,removedCount:b.droppedCount},h))}return x=ho(x),x}async function*ko(e,t){let{state:n,guardState:o,fallbackModel:r,signal:s,querySource:a,turnId:l,log:c,emitRecovery:f}=t;if(e instanceof ke&&r)return c.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield f("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let g=e instanceof Error?e.message:String(e),h=typeof e?.status=="number"?e.status:void 0;if(!h&&g&&(g.includes("ECONNRESET")||g.includes("EPIPE"))){let _=(n.consecutiveApiRetries??0)+1;return _>re?(c.info(`stale connection retry limit reached (${re}), aborting`),yield{type:"error",turnId:l,error:g,code:"RETRIES_EXHAUSTED",usage:n.totalUsage},{kind:"return"}):(c.info(`stale connection (${g.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield f("stale_connection_retry",g.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:_,transition:void 0}})}let T=bo({status:h,message:g});if(T!==null)return c.info(`max_tokens overflow: adjusting to ${T}`),o.currentMaxOutputTokens=T,{kind:"continue",patch:{maxOutputTokensOverride:T,transition:void 0}};if(Pt(h)){n.consecutive529Errors++;let _=2,x=r&&n.currentModel!==r;if(n.consecutive529Errors>_&&!x&&!ze())return c.info(`transient ${h} \u8133 ${n.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:l,error:`API unavailable after ${n.consecutive529Errors} consecutive ${h} errors`,code:"API_ERROR",usage:n.totalUsage},{kind:"return"};if(n.consecutive529Errors>=Gn&&r&&n.currentModel!==r)return c.info(`529 \u8133 ${n.consecutive529Errors}: triggering fallback to ${r}`),yield f("model_fallback",`529 \u8133 ${n.consecutive529Errors}`),{kind:"continue",patch:{currentModel:r,consecutive529Errors:0,transition:void 0}};if(ze()){let C=He(n.consecutive529Errors);c.info(`persistent retry: waiting ${C}ms (attempt ${n.consecutive529Errors})`);let k=C;for(;k>0;){if(s?.aborted)return yield{type:"error",turnId:l,error:"Aborted during retry wait",code:"ABORTED",usage:n.totalUsage},{kind:"return"};yield{type:"heartbeat",turnId:l,message:`Retrying in ${Math.ceil(k/1e3)}s (${h})`};let b=Math.min(k,zn);await new Promise(P=>setTimeout(P,b)),k-=b}return{kind:"continue",patch:{transition:void 0}}}if(It(a)){let k=Co({status:h,message:g})??He(n.consecutive529Errors);return c.info(`transient ${h}: retry in ${k}ms`),yield f("retry",`${h} retry in ${k}ms`),await new Promise(b=>setTimeout(b,k)),{kind:"continue",patch:{transition:void 0}}}c.info(`background source ${a}: not retrying ${h}`)}return{kind:"streamError",streamError:{status:h,message:g}}}import{readdirSync as So,statSync as Xe}from"node:fs";var qs=/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,Hs=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,xo=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,zs=/\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,Gs=/(?:^|[\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,Ws=/(?:^|[\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,Ks=/(?:^|[\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,Xs=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i,Ys=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i;function z(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 _o(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function Ao(e,t,n){let o=Math.max(e.lastIndexOf(".",t),e.lastIndexOf(`
|
|
18
|
+
`,t),e.lastIndexOf(";",t),e.lastIndexOf("\u3002",t),e.lastIndexOf("\uFF1B",t))+1,r=e.slice(o,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+n.length);return new RegExp(`\\bno\\s+${Po(n)}\\b`,"i").test(s)}function vo(e){return e.replace(/https?:\/\/\S+/gu," ")}function Kt(e){let t=new Set,n=[],o=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B]+$/u,""),a=z(s);t.has(a)||(t.add(a),n.push(s))};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=vo(r.content);for(let a of s.matchAll(Hs)){let l=a[0],c=(a.index??0)+l.length;if(s[c]==="/"||s[c]==="\\")continue;o(l);let f=l.replace(/\\/g,"/"),g=f.lastIndexOf("/");if(g>=0){let h=f.slice(0,g+1);xo.lastIndex=c;let T;for(;(T=xo.exec(s))!==null;)o(`${h}${T[1]}`)}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=vo(r.content);if(!Xs.test(s))continue;let a=Array.from(s.matchAll(zs)).map(c=>Mo(c[1]??"")).filter(c=>c&&!_o(c));if(a.length===0)continue;let l=a[a.length-1];for(let c of s.matchAll(Gs)){let f=c[1];f&&(Ao(s,c.index??0,f)||o(`${l}/${f}`))}for(let c of s.matchAll(Ws)){let f=c[1];f&&(Ao(s,c.index??0,f)||o(`${l}/${f}`))}for(let c of s.matchAll(Ks)){let f=c[1];f&&(_o(f)||/(?:assets[\\/]generated|screenshots(?:[\\/]|$)|previews(?:[\\/]|$))/i.test(f)&&/\b(?:generated|bitmap|png|screenshots?|preview|previews|evidence|assets?|containing)\b/i.test(s)&&o(`${l}/${f}/*`))}Ys.test(s)&&o(`${l}/previews/*`)}return n}function Ye(e){if(e.role!=="tool")return!1;let t=typeof e.content=="string"?e.content:"";return e.is_error!==!0&&!t.startsWith("Error:")}function Eo(e){let t=new Set,n=new Map,o=[];for(let r of e){let s=r,a=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let l of a){let c=l,f=c.id,g=c.function;typeof f=="string"&&typeof g?.name=="string"&&n.set(f,g.name)}}for(let r of e){let s=r;if(Ye(s)){let a=s.tool_call_id;typeof a=="string"&&t.add(a),(typeof a=="string"?n.get(a):void 0)==="exec"&&typeof s.content=="string"&&o.push(s.content)}}for(let r of e){let s=r,a=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let l of a){let c=l,f=c.id;if(typeof f=="string"&&t.size>0&&!t.has(f))continue;let g=c.function;if(!(typeof g?.name!="string"||typeof g.arguments!="string"))try{let h=JSON.parse(g.arguments);if(g.name==="write"||g.name==="edit"){for(let T of["path","filePath","file_path"]){let _=h[T];typeof _=="string"&&o.push(_)}continue}if(g.name==="exec"){let T=h.command;typeof T=="string"&&o.push(T)}}catch{g.name==="exec"&&o.push(g.arguments)}}}return o.join(`
|
|
19
|
+
`).replace(/\\/g,"/").toLowerCase()}function Xt(e){try{if(e.endsWith("/*")){let n=e.slice(0,-2);return So(n,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return Xe(`${n}/${r.name}`).size>0}catch{return!1}})}let t=Xe(e);return t.isFile()&&t.size>0}catch{return!1}}function Vs(e,t){let n=z(t);if(!n.endsWith("/*"))return e.includes(n);let o=n.slice(0,-1);return e.includes(o)}function Zs(e){let t=new Set;for(let n of e){let o=n,r=Array.isArray(o.tool_calls)?o.tool_calls:[];for(let s of r){let a=s,l=a.id,c=a.function;typeof l=="string"&&c?.name==="agent"&&t.add(l)}}for(let n of e){let o=n,r=o.tool_call_id;if(typeof r=="string"&&t.has(r)&&Ye(o))return!0}return!1}function Js(e){let t=Io(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 Qs(e){let t=Mo(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function ei(e){if(e.length===0)return"";let t=e.map(o=>Qs(o).split("/")),n=[];for(let o=0;o<t[0].length;o++){let r=t[0][o];if(t.every(s=>s[o]?.toLowerCase()===r.toLowerCase()))n.push(r);else break}return n.join("/")}function ti(e,t){let n=z(e);return t.some(o=>{let r=z(o);return r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r})}function ni(e){let t=new Set,n=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let a of s){let l=a,c=l.id,f=l.function;if(typeof c!="string"||f?.name!=="write"&&f?.name!=="edit"||typeof f.arguments!="string")continue;let g=Vt(f.arguments);if(!g)continue;let h=Zt(g);h&&n.set(c,h)}}for(let o of e){let r=o;if(!Ye(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...n.entries()].filter(([o])=>t.has(o)).map(([,o])=>o)}function oi(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 ri(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function si(e){let t=new Set,n=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let a of s){let l=a,c=l.id,f=l.function;if(typeof c!="string"||f?.name!=="write"&&f?.name!=="edit"||typeof f.arguments!="string")continue;let g=Vt(f.arguments);if(!g)continue;let h=Zt(g)??"",T=Lo(g);(/\bartifact[-_\s]?index\b/i.test(h)||/\bartifact[-_\s]?index\b/i.test(T))&&n.set(c,T)}}for(let o of e){let r=o;if(!Ye(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...n.entries()].filter(([o])=>t.has(o)).map(([,o])=>o).filter(o=>o.trim().length>0)}function ii(e){let t=Io(e.inputMessages);if(!oi(t))return[];let n=si(e.messages).at(-1);if(!n)return[];let o=[],r=ri(t).filter(c=>!new RegExp(`\\b${Po(c)}\\b`,"i").test(n));r.length>0&&o.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(n),a=/\b(?:all\s+checks\s+pass|confirmed\s*:\s*all|everything\s+(?:passes|passed)|fully\s+verified)\b/i.test(e.finalText);s&&a&&o.push({type:"overconfident_final",detail:"Final response claimed all checks pass while the generated index contains failed, partial, missing, or no-evidence rows."});let l=n.split(/\r?\n/u).filter(c=>/\bno\s+[^|\n]*(?:found|evidence|files?)\b/i.test(c)&&!/\b(?:not\s+verified|unverified|unknown|not\s+checked|search\s+scope|checked\s+path)\b/i.test(c));return l.length>0&&o.push({type:"unsupported_absence",detail:`Absence claims need scoped evidence or must be marked unverified: ${l.slice(0,3).join(" ; ")}`}),o}function ai(e){let t=[],n=o=>{let r;try{r=So(o,{withFileTypes:!0})}catch{return}for(let s of r){let a=`${o}/${s.name}`;if(s.isDirectory()){n(a);continue}if(s.isFile())try{Xe(a).size>0&&t.push(a)}catch{}}};try{if(!Xe(e).isDirectory())return[]}catch{return[]}return n(e),t}function li(e,t){if(!Js(e))return[];let n=Kt(e),o=n.filter(a=>!z(a).endsWith("/*"));if(o.length<2)return[];let r=ei(o);if(!r||r.split("/").length<3)return[];let s=z(r);return[...new Set([...ni(t),...ai(r)])].filter(a=>z(a).startsWith(`${s}/`)&&!ti(a,n)&&Xt(a))}function wo(e,t){let n=Kt(e);if(n.length===0)return[];let o=Eo(t);return n.filter(r=>!Vs(o,r))}function Wt(e){return Yt(e).fail}function ci(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function Ke(e){if(!e)return!1;let t=ci(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function Yt(e){let t=r=>r.replace(/[.,;:]+$/u,""),n,o;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))Ke(s[2])&&(n=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))Ke(s[1])&&(o=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))Ke(s[1])&&(n=`${t(s[1])} ${s[2].toUpperCase()}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+FAIL\b/gi))Ke(s[1])&&(o=`${t(s[1])} FAIL`)}return{done:n,fail:o}}function Io(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user"&&typeof n.content=="string")return n.content}return""}function Po(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function se(e){let t=wo(e.inputMessages,e.messages).filter(o=>!Xt(o));return t.length===0?void 0:`${Wt(e.inputMessages)??"FAIL"} ${e.reason}. Missing required output file evidence: ${t.join(", ")}`}function Vt(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Zt(e){for(let t of["path","filePath","file_path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n}}function Lo(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function Oo(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let n=Yt(e.inputMessages);if(!n.done)return;let o=Vt(e.toolCall.function.arguments);if(!o)return;let r=Zt(o),s=Lo(o);if(!r||!s.includes(n.done))return;let a=Kt(e.inputMessages);if(a.length<2)return;let l=z(r);if(!a.some(h=>z(h)===l))return;let f=Eo(e.messages),g=a.filter(h=>z(h)!==l).filter(h=>!f.includes(z(h)));if(g.length!==0)return`Premature completion artifact blocked: this write/edit attempted to store the requested DONE marker in ${r} before evidence existed for sibling required output files: ${g.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function xe(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function ui(e){let t=e,n=t.is_error===!0||typeof t.content=="string"&&t.content.startsWith("Error:");return t.role==="tool"&&typeof t.content=="string"&&!n}function di(e){let t=[...e].reverse().find(n=>n.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
|
|
20
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.
|
|
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 _e(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function Jt(e){let t=e.inputMessages.find(g=>g.role==="user"),n=typeof t?.content=="string"?t.content:"",o=qs.test(n),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=Yt(e.inputMessages),a=Zs(e.messages),l=wo(e.inputMessages,e.messages).filter(g=>!(a&&Xt(g)));if(l.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${l.length} file(s) missing`);let g=Wt(e.inputMessages),h={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${l.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 _e("explicit_required_file_verification",e.messages,xe(e.finalText,e.thinkingBlocks),h)}let c=li(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=Wt(e.inputMessages),h={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${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 _e("explicit_extra_file_verification",e.messages,xe(e.finalText,e.thinkingBlocks),h)}let f=ii({inputMessages:e.inputMessages,messages:e.messages,finalText:e.finalText});if(f.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`artifact index evidence verification: ${f.length} issue(s)`);let g={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+f.map(h=>h.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, finish with the final status contract."};return _e("artifact_index_evidence_verification",e.messages,xe(e.finalText,e.thinkingBlocks),g)}if(e.stopHookActive)return null;if(o&&!r){e.log.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),e.totalToolCallCount>0&&di(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 _e("file_action_verification",e.messages,xe(e.finalText,e.thinkingBlocks),g)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(ui).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let h={role:"user",content:"You created multiple files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. If everything is correct, confirm completion. If not, fix the issues now."};return _e("multi_file_skeleton_verification",e.messages,xe(e.finalText,e.thinkingBlocks),h)}return null}function pi(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function No(e){if(!e.hooks)return null;let t=await e.hooks.invoke("stop",{sessionId:e.sessionId,reason:"completed"});if(t.action==="prevent")return e.log.info(`stop hook prevented continuation: ${t.reason??"no reason"}`),{action:"end",content:e.finalText};if(t.action==="abort"){let n=t.reason??"Stop hook requested continuation";e.log.info(`stop hook blocking: ${n}`);let o={role:"user",content:n};return{action:"continue",messages:[...e.messages,pi(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var fi=5;function mi(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function gi(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Fo(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=fi)return null;let t=mi(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=Hn&&o<Rt&&e.lastBudgetDeltaTokens<Rt)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(n)}% (delta=${o})`),null;if(n>=90)return null;let s=e.budgetContinuationCount+1,a={role:"user",content:e.getBudgetContinuationMessage(n,t,e.tokenBudget)};return e.log.info(`token budget continuation #${s}: ${Math.round(n)}% used`),{messages:[...e.messages,gi(e.finalText,e.thinkingBlocks),a],budgetContinuationCount:s,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function Qt(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 _t(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function Bo(e,t){let n=[],o=[];for(let r of e){let s=t.get(r.function.name)??0;s>=Re?o.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.`}):n.push(r)}return{allowed:n,blocked:o}}function Do(){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 $o(e){if(e.ok&&!e.softEmpty)return;let t=e.toolFailureCounts.get(e.toolName)??0;e.toolFailureCounts.set(e.toolName,t+1)}function Uo(e,t){e.set(t,Math.max(e.get(t)??0,Re))}function jo(e){let t=[];for(let[n,o]of e.toolFailureCounts)o>=Re&&(e.snapshot.get(n)??0)<Re&&t.push({role:"user",content:`Tool "${n}" has now failed/returned empty results ${o} times with different arguments. The target clearly does not exist. Do NOT call "${n}" again. Report the result to the user immediately.`});return t}var hi=new Set(["write","edit","patch"]),yi=new Set(["image_generate"]),Ti=/\b(?:build|create|make|develop|implement|scaffold|generate)\b[\s\S]{0,80}\b(?:app|application|web ?app|website|site|dashboard|frontend|react|vite|vue|next|svelte|game)\b|\b(?:vite|react|vue|next\.js|frontend|browser-visible)\b|(?:构建|创建|开发|实现|生成|搭建)[\s\S]{0,24}(?:应用|网站|网页|前端|页面|项目|游戏|看板|仪表盘|app)/i;var Ci=/\b(?:under|inside|in|at|to|root|directory|folder|output directory|output folder)\s+([A-Za-z]:[\\/][^\s"'`<>|]+)|(?:目录|文件夹|根目录|输出到|放到|位于)\s*([A-Za-z]:[\\/][^\s"'`<>|]+)/gi,bi=/https?:\/\/[^\s"'`<>),;]+/gi,Ri=/\b(?:default vite|vite \+ react|edit src\/app|click on the vite|vite page)\b|默认\s*Vite/i,qo=/\b(?:browser|playwright|puppeteer|screenshot|opened|loaded|navigated|visible|locator|page\.goto|http:\/\/127\.0\.0\.1|http:\/\/localhost)\b|(?:浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化)/i;function Wo(e){let t=nn(e);return{artifactRoot:t,rootSource:t?"explicit":void 0,writePaths:[],outOfRootWrites:[],devServerUrls:[],browserVerified:!1,browserEvidence:[]}}function Ve(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&Ti.test(t.content))}function ki(e){return e.some(t=>{if(t.role!=="user"||typeof t.content!="string")return!1;let n=t.content.replace(/[A-Za-z]:[\\/][^\s"'`<>|]+/g," ").replace(/\b[A-Za-z0-9._-]*review\.(?:md|txt|docx|pdf)\b/gi," ").toLowerCase();return/\b(?:research|market|analysis|analyze|audit|recommendation|strategy|sourced|citations?)\b/.test(n)?!0:/(?:研究|分析|审计|评估|建议|策略|引用|来源|事实)/.test(n)})}function xi(e){return["Done","Not done","Artifacts","Verification","Blockers","Next action"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function Ko(e){return["Sourced facts","Assumptions","Recommendations","Unsupported claims"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function Xo(e,t){let n=vi(t);return n?hi.has(e)?Ho(n.path,n.file_path,n.filePath,n.filename,n.file):yi.has(e)?Ho(n.output_path,Array.isArray(n.output_paths)?n.output_paths[0]:void 0):null:null}function Yo(e){let t=Xo(e.toolName,e.rawArguments);if(!t||!Ve(e.inputMessages))return null;if(!e.state.artifactRoot){let r=nn(e.inputMessages);r?(e.state.artifactRoot=r,e.state.rootSource="explicit"):(e.state.artifactRoot=Jo(t),e.state.rootSource=e.state.artifactRoot?"inferred":void 0)}let n=e.state.artifactRoot;if(!n||e.state.rootSource!=="explicit"||Qo(t,n))return null;let o=`Artifact root contract blocked ${e.toolName}: attempted to write ${t}, but this deliverable root is ${n}. Keep generated app/project files inside the declared artifactRoot, or ask for explicit approval before changing scope.`;return{path:t,artifactRoot:n,error:o}}function en(e,t){e.writePaths.includes(t.path)||e.writePaths.push(t.path),e.outOfRootWrites.some(n=>n.path===t.path&&n.toolName===t.toolName)||e.outOfRootWrites.push(t)}function Vo(e){let t=Xo(e.toolName,e.rawArguments);if(t){if(!e.state.artifactRoot){let o=nn(e.inputMessages);e.state.artifactRoot=o??Jo(t),e.state.rootSource=o?"explicit":e.state.artifactRoot?"inferred":void 0}e.state.writePaths.includes(t)||e.state.writePaths.push(t),Ve(e.inputMessages)&&e.state.artifactRoot&&e.state.rootSource==="explicit"&&!Qo(t,e.state.artifactRoot)&&en(e.state,{path:t,artifactRoot:e.state.artifactRoot,toolName:e.toolName})}let n=`${e.rawArguments}
|
|
22
|
+
${e.content}`;for(let o of n.matchAll(bi)){let r=wi(o[0]);r&&(e.state.devServerUrls.includes(r)||e.state.devServerUrls.push(r))}if(Si(e.toolName,e.rawArguments,e.content)){e.state.browserVerified=!0;let o=e.content.trim().slice(0,500);o&&!e.state.browserEvidence.includes(o)&&e.state.browserEvidence.push(o)}}function tn(e,t){return{artifactRoot:e.artifactRoot,writePaths:[...e.writePaths],outOfRootWrites:[...e.outOfRootWrites],devServerUrls:[...e.devServerUrls],browserVerified:e.browserVerified,browserEvidence:[...e.browserEvidence],requiresBrowserAcceptance:Ve(t)}}function Zo(e){let t=e.content.trim(),n=Ve(e.inputMessages),o=ki(e.inputMessages),r=Ii(t),s=!r&&e.totalToolCallCount>0&&(n||o||t===""),a=t;if(s&&!xi(a)){let l=_i({...e,content:a,needsBrowser:n,needsResearch:o});a=a?`${a}
|
|
22
23
|
|
|
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
|
-
|
|
25
|
-
${
|
|
24
|
+
${l}`:l}if(!r&&o&&!Ko(a)){let l=Ai(a);a=a?`${a}
|
|
25
|
+
|
|
26
|
+
${l}`:l}return a}function _i(e){let t=[],n=[];e.artifactContract.outOfRootWrites.length>0&&(n.push("Artifact root drift was detected and at least one write was outside the deliverable root."),t.push(...e.artifactContract.outOfRootWrites.slice(0,3).map(l=>`${l.toolName} attempted ${l.path} outside ${l.artifactRoot}.`))),e.needsBrowser&&!e.artifactContract.browserVerified&&(n.push("Browser-visible acceptance was not recorded for this app/frontend deliverable."),t.push("Load the served app in a browser-capable tool and verify visible UI behavior before claiming completion.")),e.needsResearch&&!Ko(e.content)&&n.push("Research/report quality audit sections were not separated in the model response.");let o=e.totalToolCallCount>0?`Ran ${e.totalToolCallCount} tool call${e.totalToolCallCount===1?"":"s"} (${[...e.distinctToolNames].join(", ")||"unknown tools"}).`:"No tool work was recorded.",r=[e.artifactContract.artifactRoot?`artifactRoot: ${Ae(e.artifactContract.artifactRoot)}`:"artifactRoot: not declared",e.artifactContract.writePaths.length>0?`files: ${e.artifactContract.writePaths.slice(0,8).map(Ae).join(", ")}`:"files: no write paths recorded",e.artifactContract.devServerUrls.length>0?`urls: ${e.artifactContract.devServerUrls.join(", ")}`:"urls: none recorded"],s=e.artifactContract.browserVerified?`Browser evidence recorded: ${e.artifactContract.browserEvidence[0]??"yes"}`:e.needsBrowser?"Browser evidence missing.":"No browser acceptance required for this request.",a=t.length>0?"Resolve the blocker(s), then rerun verification and issue a new final status.":"Proceed with user review or requested follow-up.";return["Done:",`- ${o}`,"","Not done:",...n.length>0?n.map(l=>`- ${l}`):["- None recorded."],"","Artifacts:",...r.map(l=>`- ${l}`),"","Verification:",`- ${s}`,"","Blockers:",...t.length>0?t.map(l=>`- ${l}`):["- None recorded."],"","Next action:",`- ${a}`].join(`
|
|
27
|
+
`)}function Ai(e){return["Sourced facts:",/\b(?:source|citation|cited|http|https|来源|引用)\b/i.test(e)?"- Source-backed claims are present in the response, but they still require reviewer audit.":"- Not separated; source-backed facts were not clearly isolated.","","Assumptions:","- Not separated.","","Recommendations:","- Not separated.","","Unsupported claims:","- Any claim without visible evidence must be treated as unsupported until reviewed."].join(`
|
|
28
|
+
`)}function vi(e){try{return JSON.parse(e)}catch{return null}}function Ho(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim();return null}function nn(e){for(let t of e)if(!(t.role!=="user"||typeof t.content!="string"))for(let n of t.content.matchAll(Ci)){let o=n[1]??n[2],r=Ze(o??"");if(r&&!Ei(r))return Ae(r)}}function Jo(e){let t=Ae(Ze(e));if(!t)return;let n=t.toLowerCase();if(n.endsWith("/package.json"))return Go(t);let o=n.lastIndexOf("/src/");if(o>0)return t.slice(0,o);if(n.endsWith("/index.html")||n.endsWith("/vite.config.ts")||n.endsWith("/vite.config.js"))return Go(t)}function Si(e,t,n){let o=qo.test(n),r=Mi(e)&&qo.test(t)&&/\b(?:200|ok|success|passed|loaded|visible)\b/i.test(n);return!(!o&&!r||Ri.test(n)&&!/\b(?:absent|removed|not present|gone|没有|不是默认|已移除)\b/i.test(n))}function Mi(e){return/^(?:exec|bash|shell|powershell|terminal|playwright|browser|computer)$/i.test(e)}function Ei(e){return/\.[A-Za-z0-9]{1,12}$/.test(e)}function Qo(e,t){let n=zo(e),o=zo(t);return n===o||n.startsWith(`${o}/`)}function zo(e){return Ze(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"").toLowerCase()}function Ae(e){return Ze(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"")}function wi(e){let t=e.replace(/[).,;]+$/u,"");if(t.endsWith(":"))return null;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"||!n.hostname?null:t}catch{return null}}function Ze(e){return e.trim().replace(/[).,;:,。;、:]+$/u,"")}function Ii(e){return/^[A-Z0-9_ -]{6,80}$/.test(e.trim())}function Go(e){let t=Ae(e),n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function Oi(e,t){if(e.length!==1||e[0]?.function.name!=="stt")return!1;let n=[...t].reverse().find(a=>a.role==="user");if(!n)return!1;let o=Array.isArray(n.audioUrls)&&n.audioUrls.some(a=>typeof a=="string"&&a.trim()),r=typeof n.content=="string"?n.content:"",s=/\b(?:stt|speech[-\s]?to[-\s]?text|transcribe|transcription|audio[-\s]?to[-\s]?text)\b|转写|转录|语音转文字|音频转文字|听写/i.test(r);return o&&s}function Ni(e,t){let n=Fi(t);if(!n)return null;let o=Bi(n);if(!o)return null;let r=[...e].reverse().find(l=>l.role==="user"),s=typeof r?.content=="string"?r.content:"",a=/\bAUDIO_STT_RESULT\s+([^\s<]+)\s+<transcription\b/i.exec(s);return a?.[1]?`AUDIO_STT_RESULT ${a[1]} ${o}`:o}function Fi(e){let t=[e.details?.transcription,e.details?.text,e.details?.preview];for(let o of t)if(typeof o=="string"&&o.trim())return o.trim();let n=e.message?.content;return typeof n=="string"?n.trim():""}function Bi(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}function de(e){return[...new Set(e.map(t=>t.function.name))].sort()}function on(e){let t=new Set,n=[];for(let o of e){let r=`${o.name}\0${o.reason}`;t.has(r)||(t.add(r),n.push(o))}return n.sort((o,r)=>`${o.name}:${o.reason}`.localeCompare(`${r.name}:${r.reason}`))}function Di(e,t,n,o,r){let s=r.filter(a=>a.name===e).sort((a,l)=>er(a.reason)-er(l.reason))[0];return t.includes(e)?s?`${e}=policy-filtered:${s.reason}`:n.includes(e)?o.includes(e)?`${e}=called`:`${e}=enabled-not-used`:`${e}=policy-filtered:not-enabled`:`${e}=not-exposed`}function er(e){return e==="invalid-arguments"?0:e==="blocked-by-policy"?1:e==="not-offered"?2:e==="read-cycle-policy"?3:e==="identical-repeat-policy"?4:e==="variant-failure-policy"?5:10}function tr(e,t){let n=t.blockedToolCalls.length>0?t.blockedToolCalls.map(s=>`${s.name}:${s.reason}`).join(", "):"none",r=[...new Set([...t.toolCallNames,"write","edit","patch"])].sort().map(s=>Di(s,t.availableToolNames,t.enabledToolNames,t.toolCallNames,t.blockedToolCalls)).join(", ");return`${e}
|
|
29
|
+
|
|
30
|
+
Tool availability diagnostics:
|
|
31
|
+
availableToolNames: ${t.availableToolNames.join(", ")}
|
|
32
|
+
enabledToolNames: ${t.enabledToolNames.join(", ")}
|
|
33
|
+
toolCallNames: ${t.toolCallNames.join(", ")||"none"}
|
|
34
|
+
blockedToolCalls: ${n}
|
|
35
|
+
attribution: ${r}`}function $i(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ui(e,t){if(!e)return null;let n=$i(e.function.parameters),o=Array.isArray(n?.required)?n.required.filter(s=>typeof s=="string"&&s.trim().length>0):[];if(o.length===0)return null;let r=rr(t);if(!r)return`Tool "${e.function.name}" arguments must be a JSON object.`;for(let s of o){let a=r[s];if(typeof a=="string"?a.trim().length===0:a==null)return`Tool "${e.function.name}" missing required field \`${s}\`. Use the tool schema exactly instead of substituting another field.`}return null}var rn=new Set(["read","search"]),ji=new Set(["write","edit","patch","image_generate"]),ve=3,or=new Map([["requirements.md","requirements"],["decisions.md","decisions"],["defects.md","defects"],["acceptance.md","acceptance"]]);function nr(e){try{let t=JSON.parse(e),n=t.file_path??t.path??t.filePath;return typeof n=="string"&&n.trim()?n:void 0}catch{return}}function qi(e){return e.flatMap(t=>{if(Hi(t.function.arguments))return[t];let n=zi(t.function.arguments);return n.length<2?[t]:n.map((o,r)=>({...t,id:`${t.id}__json_${r+1}`,function:{...t.function,arguments:JSON.stringify(o)}}))})}function Hi(e){try{let t=JSON.parse(e);return!!t&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function zi(e){let t=[],n=0,o=-1,r=!1,s=!1,a=0;for(let l=0;l<e.length;l+=1){let c=e[l];if(r){s?s=!1:c==="\\"?s=!0:c==='"'&&(r=!1);continue}if(c==='"'){r=!0;continue}if(c==="{"){if(n===0){if(e.slice(a,l).trim())return[];o=l}n+=1;continue}if(c!=="}"||(n-=1,n!==0||o<0))continue;let f=rr(e.slice(o,l+1));if(!f)return[];t.push(f),a=l+1,o=-1}return n!==0||r||e.slice(a).trim()?[]:t}function rr(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function sn(e){let t=e.trim().replace(/\\/g,"/");for(t=t.replace(/\/{2,}/g,"/");t.includes("/./");)t=t.replace(/\/\.\//g,"/");return t=t.replace(/\/\.$/,""),/^[a-z]:\//i.test(t)&&(t=t.toLowerCase()),t.replace(/\/$/,"")}function Gi(e){let t=e.trim().replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function Wi(e){return`sha256:${Li("sha256").update(e).digest("hex")}`}function Ki(e,t){let n=t.split(/\r?\n/).map(r=>r.trim()).find(Boolean)??e,o=n.length>140?`${n.slice(0,137)}...`:n;return o.toLowerCase().includes(e.toLowerCase())?o:`${e}: ${o}`}function Xi(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function Yi(e,t,n,o){let r=[...t.values()].sort((l,c)=>(l.name??"").localeCompare(c.name??""));if(r.length===0)return null;let s=r.map(l=>{let c=l.name??"document";return{id:or.get(c)??c.replace(/\.[^.]+$/,""),decision:`Maintain ${c} through the long-horizon document index`,status:"confirmed",evidence:`read:${c}:${l.contentHash}`,lastConfirmedTurn:o}}),a={strategy:"maintained-document-index",nextReadPolicy:"use maintained index before full document reread",budgetStatus:"within-budget",maxReadsPerDocument:ve,observedReadsByPath:Xi(n)};return{type:"document_maintenance",turnId:e,checkpointId:`${e}-docs-${r.length}`,documents:r,decisionStateTable:s,readCycleFindings:[],readCycleGuard:a}}function Vi(e){let t=e.find(o=>o.path)?.path??"",n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function Je(e,t){return e.get(t)??null}function Zi(e){let t=Je(e,"requirements.md"),n=Je(e,"decisions.md"),o=Je(e,"defects.md"),r=Je(e,"acceptance.md");if(!t||!n||!o||!r)return null;let s=[t,n,o,r];return{goal:`Maintain long-horizon project state from ${t.name}, ${n.name}, ${o.name}, and ${r.name}`,artifactRoot:Vi(s),decisions:[n.summary],defects:[o.summary],acceptanceCriteria:[r.summary],blockers:[],nextAction:"Continue from the maintained document index and read only explicitly missing sections"}}function Ji(e,t){let n=Zi(t);return n?[{type:"lifecycle",turnId:e,kind:"goal_reconstruction",reconstruction:n},{type:"lifecycle",turnId:e,kind:"memory_drift",status:"none",detail:"No memory drift detected against the maintained document index."}]:[]}function Qi(e,t,n,o){let r=Gi(t);if(!or.has(r))return!1;let s=Wi(n);return e.maintainedDocuments.set(r,{name:r,path:sn(t),indexed:!0,maintained:!0,indexVersion:s,contentHash:s,summary:Ki(r,n),lastReviewedTurn:o}),!0}function ea(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let n=t.slice(0,t.indexOf("::"));rn.has(n)&&e.identicalCallCounts.delete(t)}}async function*sr(e,t,n,o){let{turnId:r,sessionId:s,messages:a,availableTools:l,tools:c,model:f,apiKey:g,temperature:h=0,hooks:T,signal:_}=e,x={sessionId:s,turnId:r},C=e.maxTurns??0,k=e.querySource,b=e.runtimePorts.resolveToolEligibility(c,e.toolEligibilityContext),P=b.eligibleTools,N=[];for(let m of b.blockedTools)N.push({name:m.toolName,reason:"blocked-by-policy"}),yield{type:"tool_blocked",turnId:r,callId:"",name:m.toolName,reason:"blocked-by-policy"};let O=mo(e.maxRounds,a),G=go(e.maxToolCalls,a),an=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),dr=We(a),ie={contextWindowTokens:e.contextWindowTokens??Bn,responseBufferTokens:Dn,maxOutputTokens:e.maxOutputTokens??$n,abortSignal:_,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},S=new Set,E=0,pe=0,fe=0,Se=0,F=P,pr=Oi(P,a),Qe=!1,ln=0,cn=0,et=!1,Me=!1,u={messages:[...a],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Lt(ie),reactiveCompactState:Dt(),toolLoopState:qe({maxRounds:O,replayMessages:[...a]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:Tt(),currentModel:f,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,fileReadCounts:new Map,fileReadCycleNudgedPaths:new Set,maintainedDocuments:new Map,recoveryTrace:new Map,artifactContract:Wo(a)},tt=Math.max(C*5,200),un=0,I=(m,L)=>(u.recoveryTrace.set(m,(u.recoveryTrace.get(m)??0)+1),{type:"recovery",turnId:r,action:m,detail:L}),fr=()=>({type:"tool_use_summary",turnId:r,availableToolNames:de(l??c),enabledToolNames:de(F),toolCallNames:[...S].sort(),blockedToolCalls:on(N)}),mr=m=>{let L=Zo({content:m,inputMessages:a,messages:u.messages,totalToolCallCount:E,distinctToolNames:S,artifactContract:u.artifactContract});return{type:"end",turnId:r,content:L,usage:u.totalUsage,model:u.currentModel,...u.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(u.recoveryTrace)}:{}}};function*B(m){yield fr(),yield mr(m)}let dn=()=>({type:"artifact_contract",turnId:r,...tn(u.artifactContract,a)}),pn=()=>{let m=tn(u.artifactContract,a);return!!(m.requiresBrowserAcceptance||m.artifactRoot||m.writePaths.length>0||m.outOfRootWrites.length>0||m.devServerUrls.length>0||m.browserVerified)},Ee=(m,L)=>u.finalText||Ut(m,o),gr=(m,L,me)=>{let Z=se({inputMessages:a,messages:L,reason:me});return Z||m||Ut(L,o)};for(;;){if(un++,un>tt){o.info(`hard iteration cap reached (${tt}), forcing completion`);let i=Ee(u.messages,`hard iteration cap reached (${tt}) before completing the final status contract`);yield*B(i);return}let{messages:m,maxOutputTokensRecoveryCount:L,maxOutputTokensOverride:me,turnCount:Z,guardState:w,reactiveCompactState:X,collapseStore:nt}=u,{toolLoopState:D}=u;if(e.refreshTools&&Z>1){let i=e.refreshTools();i!==F&&(F=i,o.debug(`tools refreshed: ${i.length} tools`))}if(Bt(w,ie)){o.info(`turn aborted by guard at turn ${Z}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:u.totalUsage};return}let J=Ot(w,ie);if(J.level==="blocking"){J.reason==="prompt_too_long"&&ce(X)&&(X.attemptedThisTurn=!0,w.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${J.reason}), reactive compact needed`),yield I("reactive_compact","token budget pre-check")),o.info(`token budget blocking (${J.reason}), ending tool loop`);break}J.level==="warning"&&o.info(`token budget warning: ${J.usagePercent}% used, ${J.remainingTokens} remaining`);let we=yield*Ro({messages:m,contentReplacementState:u.contentReplacementState,snipRemovedIds:u.snipRemovedIds,collapseStore:nt,guardState:w,guardConfig:ie,runtimePorts:e.runtimePorts,hooks:T,hookCtx:x,sessionId:s,currentModel:u.currentModel,log:o,recovery:I,onAutocompact:()=>{u.hasAttemptedReactiveCompact=!1}}),hr=et?"required":e.toolChoice==="required"&&Qe?"auto":e.toolChoice??"auto";et=!1;let ge=At({tools:F,toolChoice:hr}),he=qe({maxRounds:O,replayMessages:we,lastStopReason:D.lastStopReason,options:{stopReason:D.lastStopReason}}),fn=ge.extraSystemPrompt?[{role:"system",content:ge.extraSystemPrompt},...he.state.replayMessages]:he.state.replayMessages;D=he.state,he.recoveryActions.length>0&&o.debug(`tool loop recovery: ${he.recoveryActions.map(i=>i.detail??i.kind).join("; ")}`),o.debug(`turn ${Z}, messages: ${fn.length}`),M(T,"turn.before_inference",{...x,model:u.currentModel},o);let ot=!1,rt=[],mn=new Map,gn="stop",$,R=null,Ie=!1,hn=!1,ye=[],Y=[];try{for await(let i of t.stream({model:u.currentModel,messages:fn,...ge.tools.length>0?{tools:ge.tools,toolChoice:ge.normalizedToolChoice??"auto"}:{},temperature:h,maxTokens:(me??w.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:Me?void 0:u.lastResponseId,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},g,_))switch(i.type){case"delta":rt.push(i.text);break;case"tool_call_delta":ot=!0,$t(mn,i);break;case"reasoning_delta":ye.push(i.text);break;case"reasoning_block_complete":i.signature&&Y.push({thinking:ye.join(""),signature:i.signature}),ye.length=0;break;case"usage":$={inputTokens:i.promptTokens,outputTokens:i.completionTokens,reasoningTokens:i.reasoningTokens,cacheRead:i.cacheReadTokens,cacheWrite:i.cacheCreationTokens};break;case"response_id":Me||(u.lastResponseId=i.id);break;case"annotations":yield{type:"annotations",turnId:r,annotations:i.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${i.toolType}: ${i.event}`};break;case"done":hn=!0,gn=i.finishReason;break}if(ot||M(T,"turn.after_inference",{...x,model:u.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let i=u.currentModel;for(let d of e.postSamplingHooks)try{d({messages:[...we],model:i,sessionId:s})}catch{}}}catch(i){let d=yield*ko(i,{state:u,guardState:w,fallbackModel:e.fallbackModel,signal:_,querySource:k,turnId:r,log:o,emitRecovery:I});if(d.kind==="return")return;if(d.kind==="continue"){u={...u,...d.patch};continue}R=d.streamError}if(!R&&!hn){let i="LLM stream closed before a terminal event; the response was likely truncated upstream.";M(T,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:i},o),yield{type:"error",turnId:r,error:i,code:"RETRYABLE_TRANSIENT",usage:u.totalUsage};return}if(R&&M(T,"turn.after_inference",{...x,model:u.currentModel,response:{error:R.message}},o),R){if(!Me&&u.lastResponseId&&/previous_response_id not found/i.test(R.message)){let i=(u.consecutiveApiRetries??0)+1;if(i<=re){o.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"),Me=!0,u={...u,lastResponseId:void 0,consecutiveApiRetries:i,transition:void 0};continue}}if(zt(R))Ie=!0,o.info(`withheld prompt_too_long error (status=${R.status})`);else if(Gt(R))Ie=!0,o.info(`withheld media_size error (status=${R.status})`);else{let i=Nt({status:R.status??500,message:R.message},w,ie);if(i.action==="reactive_compact"&&ce(X)&&(X.attemptedThisTurn=!0,w.hasAttemptedReactiveCompact=!0,yield I("reactive_compact",`API ${R.status??500}: ${R.message}`)),i.action==="retry"){let p=(u.consecutiveApiRetries??0)+1;if(p>re){o.info(`API retry limit reached (${re}), aborting`);let y=le(R.status,R.message);yield{type:"error",turnId:r,error:R.message,code:y,usage:u.totalUsage};return}yield I("retry",i.reason),u={...u,consecutiveApiRetries:p,transition:void 0};continue}let d=le(R.status,R.message);M(T,"stop.failure",{sessionId:s,reason:d,error:R.message},o),yield{type:"error",turnId:r,error:R.message,code:d,usage:u.totalUsage};return}}$&&(u.totalUsage.inputTokens+=$.inputTokens,u.totalUsage.outputTokens+=$.outputTokens,$.reasoningTokens&&(u.totalUsage.reasoningTokens=(u.totalUsage.reasoningTokens??0)+$.reasoningTokens),$.cacheRead&&(u.totalUsage.cacheRead=(u.totalUsage.cacheRead??0)+$.cacheRead),$.cacheWrite&&(u.totalUsage.cacheWrite=(u.totalUsage.cacheWrite??0)+$.cacheWrite)),$?.inputTokens&&(w.promptTokens=$.inputTokens);let Pe=rt.join(""),j=[...mn.values()].map((i,d)=>({id:i.id||`tc_${r}_${d}`,type:"function",function:{name:i.name,arguments:i.arguments}}));if(j=qi(j),j.length===0&&!ot){if(Pe&&(u.finalText=Pe),e.toolChoice==="required"&&!Qe&&F.length>0&&ln<2){ln++;let v=F.map(A=>A.function.name).filter(Boolean).slice(0,8).join(", ");u={...u,messages:[...m,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${v}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(Ie&&R&&zt(R)){if(u.transition?.reason!=="collapse_drain_retry"){let v=bt(we,nt);if(v.committed>0){o.info(`collapse drain: committed ${v.committed} stages`),yield I("collapse_drain",`${v.committed} stages committed`),u={...u,messages:v.messages,transition:{reason:"collapse_drain_retry",committed:v.committed}};continue}}if(ce(X)){X.attemptedThisTurn=!0,w.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield I("reactive_compact","withheld prompt_too_long"),u={...u,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),M(T,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:R.message},o),yield{type:"error",turnId:r,error:R.message,code:"PROMPT_TOO_LONG",usage:u.totalUsage};return}if(Ie&&R&&Gt(R)){if(ce(X)){X.attemptedThisTurn=!0,w.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield I("reactive_compact","media error strip-retry"),u={...u,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),M(T,"stop.failure",{sessionId:s,reason:"media_error",error:R.message},o),yield{type:"error",turnId:r,error:R.message,code:"IMAGE_ERROR",usage:u.totalUsage};return}if(To(gn)){w.consecutiveTruncations+=1;let v=e.modelMaxOutputTokens??Un,A=Ft(w,ie,v);if(A.shouldEscalate&&me===void 0){w.currentMaxOutputTokens=A.newMax,o.info(`max_output_tokens escalate: ${A.newMax} tokens`),yield I("output_escalation",`${A.newMax} tokens`),u={...u,maxOutputTokensOverride:qn,transition:{reason:"max_output_tokens_escalate"}};continue}if(L<jn){let W={role:"user",content:"Output token limit hit. Resume directly - no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};o.info(`max_output_tokens recovery #${L+1}`),yield I("max_output_tokens_recovery",`attempt ${L+1}`),u={...u,messages:[...we,W],maxOutputTokensRecoveryCount:L+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:L+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else w.consecutiveTruncations=0;D=je(D,{replayMessages:m,lastStopReason:"completed"});let i=await No({hooks:T,sessionId:s,messages:m,finalText:u.finalText,thinkingBlocks:Y,log:o});if(i?.action==="end"){let v=gr(i.content,m,"stop hook prevented continuation before completing the final status contract");yield*B(v);return}if(i?.action==="continue"){u={...u,messages:i.messages,stopHookActive:i.stopHookActive,transition:i.transition};continue}let d=Fo({tokenBudget:e.tokenBudget,totalUsage:u.totalUsage,budgetContinuationCount:u.budgetContinuationCount,lastBudgetDeltaTokens:u.lastBudgetDeltaTokens,lastBudgetGlobalTokens:u.lastBudgetGlobalTokens,messages:m,finalText:u.finalText,thinkingBlocks:Y,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o});if(d){yield I("budget_continuation",d.recoveryDetail),u={...u,messages:d.messages,budgetContinuationCount:d.budgetContinuationCount,lastBudgetDeltaTokens:d.lastBudgetDeltaTokens,lastBudgetGlobalTokens:d.lastBudgetGlobalTokens,transition:d.transition};continue}let p=Jt({inputMessages:a,messages:m,finalText:u.finalText,thinkingBlocks:Y,stopHookActive:u.stopHookActive,totalToolCallCount:E,distinctToolNames:S,log:o});if(p){if(u.stopHookActive&&u.finalText.trim()===""){let v=se({inputMessages:a,messages:p.messages,reason:"stop hook produced an empty response after tool use"});if(v){yield*B(v);return}}u={...u,messages:p.messages,stopHookActive:p.stopHookActive,transition:p.transition};continue}if(E===0&&F.length>0&&e.toolChoice!=="none"&&cn<1&&fo(Pe)){cn++,et=!0,yield I("intent_without_action","announced but did not act; forcing a tool call"),u={...u,messages:[...m,{role:"assistant",content:Pe},{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 y=Qt({totalToolCallCount:E,distinctToolNames:S,projectRoot:e.projectRoot});y&&(yield{type:"skill_instruction",turnId:r,instruction:y});let U=Ee(m,"the model ended with an empty response after tool use before completing the final status contract");for(let v of rt)yield{type:"delta",turnId:r,text:v};yield*B(U);return}let yr=Y.length===0&&ye.length>0?ye.join(""):void 0;m.push(mt(j,void 0,Y.length>0?Y:void 0,yr)),D=wt(D,{replayMessages:m,pendingToolCallIds:j.map(i=>i.id),completedToolCallIds:D.completedToolCallIds,lastStopReason:"tool_calls"});let Le=u.identicalCallCounts,yn=[],Oe=[],Tn=[],Cn=!1;for(let i of j){let d=`${i.function.name}::${i.function.arguments}`,p=Le.get(d)??0;if(Le.set(d,p+1),p+1>Fn){let y=rn.has(i.function.name)?u.identicalSuccessfulToolResults.get(d):void 0;if(y){Tn.push({call:i,result:y,repeatCount:p+1});continue}Oe.push(i),Cn||(Cn=!0,o.info(`AP4 blocked: ${i.function.name} repeated ${p+1}x`))}else yn.push(i)}let q=[];for(let i of Tn){let d=i.call,p=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${i.repeatCount}); no additional tool execution was performed.
|
|
36
|
+
|
|
37
|
+
${i.result.content}`,y=H(d.id,{ok:!0,payload:p,imageUrls:i.result.imageUrls,toolReferences:i.result.toolReferences});m.push(y),q.push(d.id),S.add(d.function.name),E++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!0,outputPreview:p.slice(0,2e3),durationMs:0,details:{type:d.function.name,reusedIdenticalCall:!0,repeatCount:i.repeatCount}}}for(let i of Oe){N.push({name:i.function.name,reason:"identical-repeat-policy"});let d=Le.get(`${i.function.name}::${i.function.arguments}`),p=Ge(m,i.function.name),y=p?`This exact tool call has been attempted ${d} times. Last error: ${p}. 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.`,U=H(i.id,{ok:!1,error:y});m.push(U),q.push(i.id),S.add(i.function.name),E++,yield{type:"tool_result",turnId:r,callId:i.id,name:i.function.name,ok:!1,error:y}}if(Oe.length>0){let i=Ge(m,Oe[0].function.name),d={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(i?`The error was: "${i}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};m.push(d)}let bn=[],st=[];for(let i of yn){let d=Yo({state:u.artifactContract,inputMessages:a,toolName:i.function.name,rawArguments:i.function.arguments});d?st.push({call:i,...d}):bn.push(i)}for(let i of st){let d=i.call;N.push({name:d.function.name,reason:"artifact-root-contract"}),en(u.artifactContract,{path:i.path,artifactRoot:i.artifactRoot,toolName:d.function.name}),m.push(H(d.id,{ok:!1,error:i.error})),q.push(d.id),S.add(d.function.name),E++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:i.error},pn()&&(yield dn()),o.warn(`artifact root contract blocked: ${d.function.name}`)}st.length>0&&m.push({role:"user",content:"A write was blocked by the artifactRoot contract. Continue inside the declared artifactRoot, or stop with an honest final status that lists the root drift as Not done."});let Rn=[],it=[];for(let i of bn){let d=Oo({inputMessages:a,messages:m,toolCall:i});d?it.push({call:i,error:d}):Rn.push(i)}for(let i of it){let d=i.call;N.push({name:d.function.name,reason:"premature-completion-artifact"}),m.push(H(d.id,{ok:!1,error:i.error})),q.push(d.id),S.add(d.function.name),E++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:i.error},o.info(`premature completion artifact blocked: ${d.function.name}`)}it.length>0&&m.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 Tr=new Set(F.map(i=>i.function.name)),at=[],kn=[];for(let i of Rn)Tr.has(i.function.name)?at.push(i):kn.push(i);for(let i of kn){let d=`Tool "${i.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;N.push({name:i.function.name,reason:"not-offered"}),m.push(H(i.id,{ok:!1,error:d})),q.push(i.id),S.add(i.function.name),o.warn(`unoffered tool call suppressed: ${i.function.name}`)}let lt=[],Ne=[];for(let i of at){let d=F.find(y=>y.function.name===i.function.name),p=Ui(d,i.function.arguments);p?Ne.push({call:i,error:p}):lt.push(i)}for(let i of Ne){let d=i.call;N.push({name:d.function.name,reason:"invalid-arguments"}),Uo(u.toolFailureCounts,d.function.name),m.push(H(d.id,{ok:!1,error:i.error})),q.push(d.id),S.add(d.function.name),E++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:i.error,details:{type:d.function.name,error:"invalid_arguments"}},o.info(`invalid tool arguments blocked: ${d.function.name}`)}if(Ne.length>0&&m.push({role:"user",content:"Some tool calls were blocked before execution because they did not match the tool schema. Do not retry the same tool with substituted fields. Use the required field names exactly, switch to the correct tool, or stop and report the invalid tool input."}),Ne.length>0&<.length===0&&at.length>0){let i=tr(jt(m,1),{availableToolNames:de(l??c),enabledToolNames:de(F),toolCallNames:[...S].sort(),blockedToolCalls:on(N)});yield*B(i);return}let Fe=[],Be=[];for(let i of lt){if(i.function.name!=="read"){Fe.push(i);continue}let d=nr(i.function.arguments);if(!d){Fe.push(i);continue}let p=sn(d);(u.fileReadCounts.get(p)??0)>=ve?Be.push({call:i,filePath:p}):Fe.push(i)}for(let i of Be){let d=i.call,p=`Read cycle policy blocked another read of "${i.filePath}" after ${ve} successful reads in this turn. Stop rereading the same large document. Use the maintained document index, decision table, and existing evidence; only ask for a specific missing section if necessary.`;N.push({name:d.function.name,reason:"read-cycle-policy"}),m.push(H(d.id,{ok:!1,error:p})),q.push(d.id),S.add(d.function.name),E++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:p},o.info(`read cycle blocked: ${i.filePath}`)}if(Be.length>0){let i=[...new Set(Be.map(d=>d.filePath))].join(", ");m.push({role:"user",content:`Further reads were blocked because these large/context documents were already read ${ve}+ times this turn: ${i}. Do not retry the read with a different path spelling. Continue from the maintained requirements/defects/decisions/acceptance index and report any truly missing evidence explicitly.`})}let ct=Bo(Fe,u.toolFailureCounts),ut=ct.allowed;if(an&&ut.length>Math.max(0,G-E)){let i=Ht({currentToolBudget:G,currentRoundBudget:O,toolHardCap:100,roundHardCap:100,continuationCount:fe,successfulSinceLastCheck:pe-Se,fileReadCounts:u.fileReadCounts,windowTools:oe,windowRounds:25});i&&(G=i.nextToolBudget,O=i.nextRoundBudget,fe=i.continuationCount,Se=pe,o.info(`tool budget continuation #${i.continuationCount}: tools\u2192${G}, rounds\u2192${O} (progress detected)`))}let xn=Math.max(0,G-E),Te=xn>0?ut.slice(0,xn):[],dt=ut.slice(Te.length),Cr=dt.length>0;if(ct.blocked.length>0){for(let i of ct.blocked){let d=i.call;N.push({name:d.function.name,reason:"variant-failure-policy"});let p=H(d.id,{ok:!1,error:i.error});m.push(p),q.push(d.id),S.add(d.function.name),E++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:i.error},o.info(`variant tool blocked: ${d.function.name} failed ${i.failCount}x with different args`)}m.push(Do())}if(dt.length>0){let i=`Tool call budget exhausted (${G}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of dt){N.push({name:d.function.name,reason:"tool-call-budget"});let p=H(d.id,{ok:!1,error:i});m.push(p),q.push(d.id),S.add(d.function.name),E++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:i}}m.push({role:"user",content:`${i} You reached this turn's tool budget after ${fe} 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 i of Te){let d=i.function.arguments,p=F.find(y=>y.function.name===i.function.name);if(p?.backfillObservableInput)try{let y=JSON.parse(i.function.arguments),U={...y};p.backfillObservableInput(U),Object.keys(U).some(A=>!(A in y))&&(d=JSON.stringify(U))}catch{}yield{type:"tool_call",turnId:r,callId:i.id,name:i.function.name,arguments:d,inputSummary:qt(d)}}let br=new Map(u.toolFailureCounts),De=null;try{let i=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:T,sessionId:s,turnId:r,log:o,signal:_,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:On});for(let p of Te)i.addTool(p);let d=!1;for await(let p of i.getRemainingResults()){p.blocked&&(yield{type:"tool_blocked",turnId:r,callId:p.callId,name:p.toolName,reason:p.blockReason??"blocked"}),m.push(p.message),q.push(p.callId),S.add(p.toolName),E++;let y=p.ok&&co(p);if(p.ok&&!y&&(pe+=1),$o({toolFailureCounts:u.toolFailureCounts,toolName:p.toolName,ok:p.ok,softEmpty:y}),p.ok&&ji.has(p.toolName)&&ea(u),p.ok&&!y&&rn.has(p.toolName)){let A=Te.find(ae=>ae.id===p.callId),W=typeof p.message?.content=="string"?p.message.content:"";if(A&&W){let ae=Array.isArray(p.message.imageUrls)?p.message.imageUrls.filter(Ce=>typeof Ce=="string"):void 0,ft=Array.isArray(p.message.toolReferences)?p.message.toolReferences.filter(Ce=>typeof Ce=="string"):void 0;u.identicalSuccessfulToolResults.set(`${A.function.name}::${A.function.arguments}`,{content:W,imageUrls:ae,toolReferences:ft})}}if(p.ok&&p.toolName==="read"){let A=Te.find(W=>W.id===p.callId);if(A){let W=nr(A.function.arguments);if(W){let ae=sn(W),ft=u.fileReadCounts.get(ae)??0;u.fileReadCounts.set(ae,ft+1);let Ce=typeof p.message?.content=="string"?p.message.content:"";d=Qi(u,W,Ce,u.turnCount)||d}}}yield io(r,p);for(let A of ao(r,p))yield A;for(let A of lo({turnId:r,result:p,toolCalls:j}))yield A;let U=j.find(A=>A.id===p.callId),v=typeof p.message?.content=="string"?p.message.content:"";U&&(Vo({state:u.artifactContract,inputMessages:a,toolName:p.toolName,rawArguments:U.function.arguments,ok:p.ok,content:v}),pn()&&(yield dn())),!De&&pr&&p.toolName==="stt"&&p.ok&&(De=Ni(a,p))}if(d){let p=Yi(r,u.maintainedDocuments,u.fileReadCounts,u.turnCount);p&&(yield p);for(let y of Ji(r,u.maintainedDocuments))yield y}}catch(i){let d=i instanceof Error?i.message:String(i);yield{type:"error",turnId:r,error:d,code:"TOOL_EXECUTION_ERROR",usage:u.totalUsage};return}if(De){yield*B(De);return}if(m.push(...jo({toolFailureCounts:u.toolFailureCounts,snapshot:br})),Cr){let i=se({inputMessages:a,messages:m,reason:`tool call budget exhausted (${G}) before completing all required files`});if(i){yield*B(i);return}}D=je(D,{replayMessages:m,completedToolCallIds:[...D.completedToolCallIds,...q],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&j.length>0&&(Qe=!0);let Rr=j.length>0&&j.every(i=>{let d=m.find(y=>y?.role==="tool"&&y?.tool_call_id===i.id);if(!d)return!0;let p=d.content;return typeof p=="string"&&p.startsWith("Error: ")}),Q=u.consecutiveFailedRounds;if(Rr){if(Q+=1,Q>=Nn){if(dr>=3&&u.repeatedToolFailureRecoveryCount<1){let y=Jt({inputMessages:a,messages:m,finalText:u.finalText,thinkingBlocks:[],stopHookActive:u.stopHookActive,totalToolCallCount:E,distinctToolNames:S,log:o});if(y?.reason==="explicit_required_file_verification"||y?.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"),u={...u,messages:y.messages,stopHookActive:y.stopHookActive,transition:y.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:u.repeatedToolFailureRecoveryCount+1};continue}}if(u.repeatedToolFailureRecoveryCount<1){let y=yo(m);if(y){yield I("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),u={...u,messages:[...m,y],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:u.repeatedToolFailureRecoveryCount+1};continue}}let i=`repeated tool failures (${Q} rounds in a row)`,d=se({inputMessages:a,messages:m,reason:`${i} before all required files were produced`})??(u.finalText.trim()?u.finalText:jt(m,Q)),p=tr(d,{availableToolNames:de(l??c),enabledToolNames:de(F),toolCallNames:[...S].sort(),blockedToolCalls:on(N)});o.info(`early exit: ${Q} consecutive failed rounds, returning ${u.finalText?"partial":"fallback"} response`),yield*B(p);return}}else Q=0;let pt=[...u.fileReadCounts.entries()].filter(([i,d])=>d>=ve&&!u.fileReadCycleNudgedPaths.has(i));if(pt.length>0){let i=pt.map(([p])=>p).join(", ");o.info(`AP5: file read cycle detected on ${i}, injecting nudge`);let d={role:"user",content:`You are reading the same files repeatedly (${i}). This indicates a circular dependency or cycle. Stop reading files, summarize your findings so far, and explain the circular structure to the user.`};m.push(d);for(let[p]of pt)u.fileReadCycleNudgedPaths.add(p)}let $e=Z+1;if(C>0&&$e>C){if(o.info(`max turns reached (${C}), completing`),T){let p=await T.invoke("stop",{sessionId:s,reason:"max_turns"});if(p.action==="abort"){let y=p.reason??"Stop hook requested continuation after max_turns",U={role:"assistant",content:u.finalText,...Y.length>0&&{thinkingBlocks:[...Y]}};u={...u,messages:[...m,U,{role:"user",content:y}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let i=se({inputMessages:a,messages:m,reason:`tool loop max turns reached (${C}) before completing all required files`});if(i){yield*B(i);return}let d=Ee(m,`tool loop max turns reached (${C}) before completing the final status contract`);yield*B(d);return}if(an&&$e>O){let i=Ht({currentToolBudget:G,currentRoundBudget:O,toolHardCap:100,roundHardCap:100,continuationCount:fe,successfulSinceLastCheck:pe-Se,fileReadCounts:u.fileReadCounts,windowTools:oe,windowRounds:25});i&&(O=i.nextRoundBudget,G=i.nextToolBudget,fe=i.continuationCount,Se=pe,o.info(`round budget continuation #${i.continuationCount}: rounds\u2192${O}, tools\u2192${G} (progress detected)`))}if($e>O){o.info(`tool loop budget exhausted (${O} rounds), returning`);let i=Qt({totalToolCallCount:E,distinctToolNames:S,projectRoot:e.projectRoot});i&&(yield{type:"skill_instruction",turnId:r,instruction:i});let d=se({inputMessages:a,messages:m,reason:`tool budget exhausted (${O} rounds) before completing all required files`});if(d){yield*B(d);return}let p=Ee(m,`tool budget exhausted (${O} rounds) before completing the final status contract`);yield*B(p);return}u={messages:m,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:$e,transition:{reason:"next_turn"},guardState:w,reactiveCompactState:X,toolLoopState:D,consecutiveFailedRounds:Q,finalText:u.finalText,totalUsage:u.totalUsage,collapseStore:nt,currentModel:u.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:u.stopHookActive,lastResponseId:u.lastResponseId,snipRemovedIds:u.snipRemovedIds,contentReplacementState:u.contentReplacementState,budgetContinuationCount:u.budgetContinuationCount,repeatedToolFailureRecoveryCount:u.repeatedToolFailureRecoveryCount,lastBudgetDeltaTokens:u.lastBudgetDeltaTokens,lastBudgetGlobalTokens:u.lastBudgetGlobalTokens,identicalCallCounts:Le,identicalSuccessfulToolResults:u.identicalSuccessfulToolResults,artifactContract:u.artifactContract,toolFailureCounts:u.toolFailureCounts,fileReadCounts:u.fileReadCounts,fileReadCycleNudgedPaths:u.fileReadCycleNudgedPaths,maintainedDocuments:u.maintainedDocuments,recoveryTrace:u.recoveryTrace}}}var ta=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function lr(e){let t=na(e),n=["[Recalled memories]","- L1 project MD is project-scoped working memory.","- L2 long-term memory is cross-project canonical memory.","- If L1 and L2 conflict on the same entity/fact, do not silently merge or choose. Surface the conflict and ask the user to confirm. For current-project operational tasks, use L1 only as a project-scoped clue until confirmed into L2."];if(t.length>0){n.push("[Memory conflict detected]");for(let o of t)n.push(`- entity: ${o.entity}; fact: ${o.predicate}; L1 project MD says: ${ar(o.l1Amount)}; L2 long-term says: ${ar(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=sa(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
|
|
38
|
+
`)}function na(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>ir(r.text)),n=e.filter(r=>r.source==="l2-long-term").flatMap(r=>ir(r.text)),o=[];for(let r of t)for(let s of n)r.entity===s.entity&&r.predicate===s.predicate&&r.amount!==s.amount&&o.push({entity:r.entity,predicate:r.predicate,l1Amount:r.amount,l2Amount:s.amount,l1Text:r.text,l2Text:s.text});return ia(o)}function ir(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim();if(o)for(let r of ta){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let s=new RegExp(`${aa(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let a of o.matchAll(s)){let l=ra(a[1]);l!==null&&t.push({entity:oa(o,r),predicate:r,amount:l,text:o})}}}return t}function oa(e,t){if(/Galaxy\s+Tech/i.test(e))return"Galaxy Tech";if(e.includes("\u7528\u6237"))return"\u7528\u6237";let n=e.toLowerCase().indexOf(t.toLowerCase()),r=(n>=0?e.slice(0,n):"").replace(/[#*`:\-,。;;,.]/g," ").trim().split(/\s+/).filter(Boolean);return r[r.length-1]??"unknown"}function ra(e){let t=e.replace(/,/g,"").replace(/\s+/g,"").trim(),n=t.endsWith("\u4E07")?1e4:/k$/i.test(t)?1e3:1,o=Number(t.replace(/[万kK]$/u,""));return Number.isFinite(o)?o*n:null}function sa(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 ar(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function ia(e){let t=new Set;return e.filter(n=>{let o=`${n.entity}\0${n.predicate}\0${n.l1Amount}\0${n.l2Amount}`;return t.has(o)?!1:(t.add(o),!0)})}function aa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var la=8192;async function cr(e){let{hooks:t,detectRecallCategories:n,log:o,sessionId:r,turnId:s,query:a}=e;try{let l=n(a),f=(await t.invoke("memory.before_recall",{sessionId:r,turnId:s,query:a,preferredCategories:l.preferred.length>0?l.preferred:void 0,deprioritizedCategories:l.deprioritized.length>0?l.deprioritized:void 0}))?.context?.recalledMemories,g=null;if(f&&f.length>0){let h=0,T=[];for(let _ of f){let x=(_.text?.length??0)*2;if(h+x>la)break;T.push(_),h+=x}T.length>0&&(g=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
|
|
39
|
+
${lr(T)}`)}return M(t,"memory.after_recall",{sessionId:r,turnId:s,blockCount:f?.length??0},o),g}catch{return null}}var ur=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,n){let{turnId:o,messages:r,availableTools:s,tools:a,systemPrompt:l,config:c}=t,f={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},M(this.hooks,"turn.submitted",{...f,prompt:r[r.length-1]?.content??void 0},this.log);let g=Et(r),h=[];if(l&&h.push({role:"system",content:l}),h.push(...g),this.hooks){let C=g.filter(b=>b.role==="user").pop(),k=typeof C?.content=="string"?C.content.slice(0,500):void 0;if(k){let b=await cr({hooks:this.hooks,detectRecallCategories:P=>this.runtimePorts.detectRecallCategories(P),log:this.log,sessionId:t.sessionId,turnId:o,query:k});b&&h.splice(l?1:0,0,{role:"system",content:b})}}let T=c?.model??"",_=typeof c?.maxRounds=="number"&&Number.isFinite(c.maxRounds)?c.maxRounds:this.configuredMaxRounds,x=_===void 0?void 0:Math.min(_,100);try{let C=c?.reasoning;c?.reasoning?.effort==="auto"&&(C={...c?.reasoning,effort:"medium"});let k={turnId:o,sessionId:t.sessionId,messages:h,availableTools:s,tools:a,model:T,apiKey:c?.apiKey??this.apiKey,temperature:c?.temperature,maxRounds:x,contextWindowTokens:c?.contextWindowTokens,maxOutputTokens:c?.maxOutputTokens,modelMaxOutputTokens:c?.modelMaxOutputTokens,toolChoice:c?.toolChoice,parentDepth:c?.parentDepth,hooks:this.hooks,fallbackModel:c?.fallbackModel,maxTurns:c?.maxTurns,tokenBudget:c?.tokenBudget,maxConcurrentTools:c?.maxConcurrentTools,streamRequired:c?.streamRequired,reasoning:C,promptCacheKey:c?.promptCacheKey,promptCacheRetention:c?.promptCacheRetention,serviceTier:c?.serviceTier,openaiBuiltinTools:c?.openaiBuiltinTools,maxToolCalls:c?.maxToolCalls,parallelToolCalls:c?.parallelToolCalls,textVerbosity:c?.textVerbosity,projectRoot:this.projectRoot,runtimePorts:this.runtimePorts.toolLoop,signal:n},b;for await(let P of sr(k,this.transport,this.toolInvoker,this.log))b=P,yield P;b?.type==="end"?M(this.hooks,"turn.completed",{...f},this.log):b?.type==="error"&&M(this.hooks,"turn.failed",{...f,code:b.code,error:b.error},this.log)}catch(C){if(n?.aborted)M(this.hooks,"turn.failed",{...f,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let k=C instanceof Error?C.message:String(C),b=typeof C?.status=="number"?C.status:void 0,P=le(b,k);this.log.error(`turn ${o} error [${P}, retryable=${ht(P)}]: ${k}`),M(this.hooks,"turn.failed",{...f,code:P,error:k},this.log),yield{type:"error",turnId:o,error:k,code:P}}}}};export{ur as Agent};
|