qlogicagent 2.14.9 → 2.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.js +1 -1
- package/dist/cli.js +349 -337
- package/dist/index.js +348 -336
- package/dist/types/cli/handlers/pinned-skill-context.d.ts +1 -0
- package/dist/types/protocol/wire/acp-protocol.d.ts +3 -0
- package/dist/types/runtime/infra/agent-paths.d.ts +17 -6
- package/dist/types/runtime/infra/checkpoint-backend.d.ts +3 -2
- package/dist/types/runtime/infra/default-path-service.d.ts +1 -1
- package/dist/types/runtime/infra/project-data-gc.d.ts +9 -0
- package/dist/types/runtime/infra/project-data-paths.d.ts +22 -0
- package/dist/types/runtime/infra/project-store.d.ts +6 -8
- package/dist/types/runtime/session/inbound-upload-persistence.d.ts +24 -0
- package/dist/types/runtime/session/session-paths.d.ts +0 -1
- package/package.json +2 -2
- package/dist/types/cli/mcp-plugin-bootstrap.d.ts +0 -2
- package/dist/types/cli/tool-bootstrap-providers.d.ts +0 -3
- package/dist/types/skills/memory/categories.d.ts +0 -1
- package/dist/types/skills/memory/find-relevant-memories.d.ts +0 -1
- package/dist/types/skills/memory/implicit-extraction.d.ts +0 -1
- package/dist/types/skills/memory/recall-category-filter.d.ts +0 -1
package/dist/agent.js
CHANGED
|
@@ -3,7 +3,7 @@ function nt(e,t,o,n){return{role:"assistant",content:t||null,tool_calls:e,...o&&
|
|
|
3
3
|
|
|
4
4
|
`)):""}function Qn(e){try{let t=JSON.parse(e),n=[t.description,t.command,t.query,t.url,t.path,t.file_path,t.filePath,t.pattern,t.model].find(s=>typeof s=="string"&&s.trim().length>0);if(typeof n=="string")return n.trim().slice(0,240);let r=Object.keys(t);return r.length>0?r.slice(0,5).join(" / "):void 0}catch{return}}function wt(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 It(e){let t=e.message.toLowerCase();return e.status===413||t.includes("prompt_too_long")||t.includes("context_length_exceeded")||t.includes("maximum context length")}function eo(e){return e==="length"||e==="max_tokens"}function Pt(e){let t=e.message.toLowerCase();return(t.includes("image")||t.includes("media")||t.includes("file too large")||t.includes("payload too large"))&&(e.status===413||t.includes("too large")||t.includes("size"))}function to(e){let t=e.headers;if(!t)return null;let o=t["retry-after"]??t["Retry-After"];if(!o)return null;let n=parseInt(o,10);return!isNaN(n)&&n>0?n*1e3:null}function no(e){if(e.status!==400)return null;let t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!t?.[1]||!t?.[3])return null;let o=parseInt(t[1],10),n=parseInt(t[3],10);if(isNaN(o)||isNaN(n))return null;let r=n-o-1e3;return r>=3e3?r:null}async function*oo(e){let{messages:t,contentReplacementState:o,snipRemovedIds:n,collapseStore:r,guardConfig:s,runtimePorts:i,hooks:a,hookCtx:u,sessionId:p,currentModel:f,log:m,recovery:C,onAutocompact:M}=e,g;{let T=await i.enforceToolResultBudget(t,o,p);g=T.messages,T.newlyReplacedCount>0&&(m.info(`tool-result-budget: persisted ${T.newlyReplacedCount} oversized tool results`),yield C("tool_result_budget",`${T.newlyReplacedCount} persisted`))}{let T=st(g,n);g=T.messages,T.removedCount>0&&(m.info(`snip: removed ${T.removedCount} messages, freed ~${T.tokensFreed} tokens`),yield C("snip",`${T.removedCount} messages`))}{let b=new Ce().compress(g,0);b.droppedCount>0&&(g=b.messages,m.info(`microcompact: cleared ${b.droppedCount} old tool results`))}if(g=at(g,r).messages,s.contextWindowTokens>0){let T=s.contextWindowTokens*.75,b=i.getActiveContextCompressionEngine(),R;b?R=await b.compressAsync(g,T,{model:f,sessionId:p}):R=i.compressMessages(g,{budget:T,model:f}),R.droppedCount>0&&(g=R.messages,m.info(`autocompact: ${R.strategy}, dropped ${R.droppedCount}`),yield C("autocompact",`${R.strategy}: ${R.droppedCount} dropped`),M(),E(a,"context.after_compact",{...u,removedCount:R.droppedCount},m))}return g=Jn(g),g}async function*ro(e,t){let{state:o,guardState:n,fallbackModel:r,signal:s,querySource:i,turnId:a,log:u,emitRecovery:p}=t;if(e instanceof ke&&r)return u.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield p("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let f=e instanceof Error?e.message:String(e),m=typeof e?.status=="number"?e.status:void 0;if(!m&&f&&(f.includes("ECONNRESET")||f.includes("EPIPE"))){let M=(o.consecutiveApiRetries??0)+1;return M>se?(u.info(`stale connection retry limit reached (${se}), aborting`),yield{type:"error",turnId:a,error:f,code:"RETRIES_EXHAUSTED",usage:o.totalUsage},{kind:"return"}):(u.info(`stale connection (${f.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield p("stale_connection_retry",f.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:M,transition:void 0}})}let C=no({status:m,message:f});if(C!==null)return u.info(`max_tokens overflow: adjusting to ${C}`),n.currentMaxOutputTokens=C,{kind:"continue",patch:{maxOutputTokensOverride:C,transition:void 0}};if(kt(m)){o.consecutive529Errors++;let M=2,g=r&&o.currentModel!==r;if(o.consecutive529Errors>M&&!g&&!$e())return u.info(`transient ${m} \u8133 ${o.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:a,error:`API unavailable after ${o.consecutive529Errors} consecutive ${m} errors`,code:"API_ERROR",usage:o.totalUsage},{kind:"return"};if(o.consecutive529Errors>=Sn&&r&&o.currentModel!==r)return u.info(`529 \u8133 ${o.consecutive529Errors}: triggering fallback to ${r}`),yield p("model_fallback",`529 \u8133 ${o.consecutive529Errors}`),{kind:"continue",patch:{currentModel:r,consecutive529Errors:0,transition:void 0}};if($e()){let T=De(o.consecutive529Errors);u.info(`persistent retry: waiting ${T}ms (attempt ${o.consecutive529Errors})`);let b=T;for(;b>0;){if(s?.aborted)return yield{type:"error",turnId:a,error:"Aborted during retry wait",code:"ABORTED",usage:o.totalUsage},{kind:"return"};yield{type:"heartbeat",turnId:a,message:`Retrying in ${Math.ceil(b/1e3)}s (${m})`};let R=Math.min(b,vn);await new Promise(A=>setTimeout(A,R)),b-=R}return{kind:"continue",patch:{transition:void 0}}}if(Ct(i)){let b=to({status:m,message:f})??De(o.consecutive529Errors);return u.info(`transient ${m}: retry in ${b}ms`),yield p("retry",`${m} retry in ${b}ms`),await new Promise(R=>setTimeout(R,b)),{kind:"continue",patch:{transition:void 0}}}u.info(`background source ${i}: not retrying ${m}`)}return{kind:"streamError",streamError:{status:m,message:f}}}import{readdirSync as co,statSync as qe}from"node:fs";var is=/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,as=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,so=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,ls=/\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,cs=/(?:^|[\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,us=/(?:^|[\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,ds=/(?:^|[\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,ps=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i,ms=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i;function $(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase()}function uo(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function io(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function ao(e,t,o){let n=Math.max(e.lastIndexOf(".",t),e.lastIndexOf(`
|
|
5
5
|
`,t),e.lastIndexOf(";",t),e.lastIndexOf("\u3002",t),e.lastIndexOf("\uFF1B",t))+1,r=e.slice(n,t).toLowerCase();if(/\b(?:do\s+not|don't|never)\s+(?:leave|create|write|include|keep|produce|add|generate)\b/i.test(r)||/\b(?:remove|delete|exclude)\b/i.test(r))return!0;let s=e.slice(Math.max(0,t-16),t+o.length);return new RegExp(`\\bno\\s+${Re(o)}\\b`,"i").test(s)}function lo(e){return e.replace(/https?:\/\/\S+/gu," ")}function He(e){let t=new Set,o=[],n=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B]+$/u,""),i=$(s);t.has(i)||(t.add(i),o.push(s))};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=lo(r.content);for(let i of s.matchAll(as)){let a=i[0];n(a);let u=(i.index??0)+a.length,p=a.replace(/\\/g,"/"),f=p.lastIndexOf("/");if(f>=0){let m=p.slice(0,f+1);so.lastIndex=u;let C;for(;(C=so.exec(s))!==null;)n(`${m}${C[1]}`)}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=lo(r.content);if(!ps.test(s))continue;let i=Array.from(s.matchAll(ls)).map(u=>uo(u[1]??"")).filter(u=>u&&!io(u));if(i.length===0)continue;let a=i[i.length-1];for(let u of s.matchAll(cs)){let p=u[1];p&&(ao(s,u.index??0,p)||n(`${a}/${p}`))}for(let u of s.matchAll(us)){let p=u[1];p&&(ao(s,u.index??0,p)||n(`${a}/${p}`))}for(let u of s.matchAll(ds)){let p=u[1];p&&(io(p)||/(?:assets[\\/]generated|screenshots(?:[\\/]|$)|previews(?:[\\/]|$))/i.test(p)&&/\b(?:generated|bitmap|png|screenshots?|preview|previews|evidence|assets?|containing)\b/i.test(s)&&n(`${a}/${p}/*`))}ms.test(s)&&n(`${a}/previews/*`)}return o}function Ot(e){if(e.role!=="tool")return!1;let t=typeof e.content=="string"?e.content:"";return e.is_error!==!0&&!t.startsWith("Error:")}function po(e){let t=new Set,o=new Map,n=[];for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let u=a,p=u.id,f=u.function;typeof p=="string"&&typeof f?.name=="string"&&o.set(p,f.name)}}for(let r of e){let s=r;if(Ot(s)){let i=s.tool_call_id;typeof i=="string"&&t.add(i),(typeof i=="string"?o.get(i):void 0)==="exec"&&typeof s.content=="string"&&n.push(s.content)}}for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let u=a,p=u.id;if(typeof p=="string"&&t.size>0&&!t.has(p))continue;let f=u.function;if(!(typeof f?.name!="string"||typeof f.arguments!="string"))try{let m=JSON.parse(f.arguments);if(f.name==="write"||f.name==="edit"){for(let C of["path","filePath","file_path"]){let M=m[C];typeof M=="string"&&n.push(M)}continue}if(f.name==="exec"){let C=m.command;typeof C=="string"&&n.push(C)}}catch{f.name==="exec"&&n.push(f.arguments)}}}return n.join(`
|
|
6
|
-
`).replace(/\\/g,"/").toLowerCase()}function Ft(e){try{if(e.endsWith("/*")){let o=e.slice(0,-2);return co(o,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return qe(`${o}/${r.name}`).size>0}catch{return!1}})}let t=qe(e);return t.isFile()&&t.size>0}catch{return!1}}function fs(e,t){let o=$(t);if(!o.endsWith("/*"))return e.includes(o);let n=o.slice(0,-1);return e.includes(n)}function gs(e){let t=ue(e);return/\b(?:exactly|only)\b[^.\n]*(?:artifacts?|files?|outputs?|deliverables?)/i.test(t)||/(?:artifacts?|files?|outputs?|deliverables?)[^.\n]*\b(?:exactly|only)\b/i.test(t)}function ys(e){let t=uo(e),o=t.lastIndexOf("/");return o>=0?t.slice(0,o):""}function hs(e){if(e.length===0)return"";let t=e.map(n=>ys(n).split("/")),o=[];for(let n=0;n<t[0].length;n++){let r=t[0][n];if(t.every(s=>s[n]?.toLowerCase()===r.toLowerCase()))o.push(r);else break}return o.join("/")}function Ts(e,t){let o=$(e);return t.some(n=>{let r=$(n);return r.endsWith("/*")?o.startsWith(r.slice(0,-1)):o===r})}function Cs(e){let t=new Set,o=new Map;for(let n of e){let r=n,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,u=a.id,p=a.function;if(typeof u!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let f=Ut(p.arguments);if(!f)continue;let m=jt(f);m&&o.set(u,m)}}for(let n of e){let r=n;if(!Ot(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...o.entries()].filter(([n])=>t.has(n)).map(([,n])=>n)}function mo(e){return/\bartifact[-_\s]?index\b/i.test(e)&&(/\b(?:evidence|status|failed|partial|passed|verified)\b/i.test(e)||/\bGoal\s+\d+\b/i.test(e))}function ks(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function fo(e){let t=new Set,o=new Map;for(let n of e){let r=n,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,u=a.id,p=a.function;if(typeof u!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let f=Ut(p.arguments);if(!f)continue;let m=jt(f)??"",C=ho(f);(/\bartifact[-_\s]?index\b/i.test(m)||/\bartifact[-_\s]?index\b/i.test(C))&&o.set(u,C)}}for(let n of e){let r=n;if(!Ot(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...o.entries()].filter(([n])=>t.has(n)).map(([,n])=>n).filter(n=>n.trim().length>0)}function go(e){let t=ue(e.inputMessages);if(!mo(t))return[];let o=fo(e.messages).at(-1);if(!o)return[];let n=[],r=ks(t).filter(u=>!new RegExp(`\\b${Re(u)}\\b`,"i").test(o));r.length>0&&n.push({type:"missing_goal_labels",detail:`Missing requested row labels in the generated index: ${r.join(", ")}`});let s=/\b(?:failed|partial|missing|not\s+found|no\s+[^.\n|]*evidence)\b/i.test(o),i=/\b(?:all\s+checks\s+pass|confirmed\s*:\s*all|everything\s+(?:passes|passed)|fully\s+verified)\b/i.test(e.finalText);s&&i&&n.push({type:"overconfident_final",detail:"Final response claimed all checks pass while the generated index contains failed, partial, missing, or no-evidence rows."});let a=o.split(/\r?\n/u).filter(u=>/\bno\s+[^|\n]*(?:found|evidence|files?)\b/i.test(u)&&!/\b(?:not\s+verified|unverified|unknown|not\s+checked|search\s+scope|checked\s+path)\b/i.test(u));return a.length>0&&n.push({type:"unsupported_absence",detail:`Absence claims need scoped evidence or must be marked unverified: ${a.slice(0,3).join(" ; ")}`}),n}function Rs(e){let t=[],o=n=>{let r;try{r=co(n,{withFileTypes:!0})}catch{return}for(let s of r){let i=`${n}/${s.name}`;if(s.isDirectory()){o(i);continue}if(s.isFile())try{qe(i).size>0&&t.push(i)}catch{}}};try{if(!qe(e).isDirectory())return[]}catch{return[]}return o(e),t}function yo(e,t){if(!gs(e))return[];let o=He(e),n=o.filter(i=>!$(i).endsWith("/*"));if(n.length<2)return[];let r=hs(n);if(!r||r.split("/").length<3)return[];let s=$(r);return[...new Set([...Cs(t),...Rs(r)])].filter(i=>$(i).startsWith(`${s}/`)&&!Ts(i,o)&&Ft(i))}function Nt(e,t){let o=He(e);if(o.length===0)return[];let n=po(t);return o.filter(r=>!fs(n,r))}function Lt(e){return be(e).fail}function bs(e){return e.replace(/[
|
|
6
|
+
`).replace(/\\/g,"/").toLowerCase()}function Ft(e){try{if(e.endsWith("/*")){let o=e.slice(0,-2);return co(o,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return qe(`${o}/${r.name}`).size>0}catch{return!1}})}let t=qe(e);return t.isFile()&&t.size>0}catch{return!1}}function fs(e,t){let o=$(t);if(!o.endsWith("/*"))return e.includes(o);let n=o.slice(0,-1);return e.includes(n)}function gs(e){let t=ue(e);return/\b(?:exactly|only)\b[^.\n]*(?:artifacts?|files?|outputs?|deliverables?)/i.test(t)||/(?:artifacts?|files?|outputs?|deliverables?)[^.\n]*\b(?:exactly|only)\b/i.test(t)}function ys(e){let t=uo(e),o=t.lastIndexOf("/");return o>=0?t.slice(0,o):""}function hs(e){if(e.length===0)return"";let t=e.map(n=>ys(n).split("/")),o=[];for(let n=0;n<t[0].length;n++){let r=t[0][n];if(t.every(s=>s[n]?.toLowerCase()===r.toLowerCase()))o.push(r);else break}return o.join("/")}function Ts(e,t){let o=$(e);return t.some(n=>{let r=$(n);return r.endsWith("/*")?o.startsWith(r.slice(0,-1)):o===r})}function Cs(e){let t=new Set,o=new Map;for(let n of e){let r=n,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,u=a.id,p=a.function;if(typeof u!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let f=Ut(p.arguments);if(!f)continue;let m=jt(f);m&&o.set(u,m)}}for(let n of e){let r=n;if(!Ot(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...o.entries()].filter(([n])=>t.has(n)).map(([,n])=>n)}function mo(e){return/\bartifact[-_\s]?index\b/i.test(e)&&(/\b(?:evidence|status|failed|partial|passed|verified)\b/i.test(e)||/\bGoal\s+\d+\b/i.test(e))}function ks(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function fo(e){let t=new Set,o=new Map;for(let n of e){let r=n,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,u=a.id,p=a.function;if(typeof u!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let f=Ut(p.arguments);if(!f)continue;let m=jt(f)??"",C=ho(f);(/\bartifact[-_\s]?index\b/i.test(m)||/\bartifact[-_\s]?index\b/i.test(C))&&o.set(u,C)}}for(let n of e){let r=n;if(!Ot(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...o.entries()].filter(([n])=>t.has(n)).map(([,n])=>n).filter(n=>n.trim().length>0)}function go(e){let t=ue(e.inputMessages);if(!mo(t))return[];let o=fo(e.messages).at(-1);if(!o)return[];let n=[],r=ks(t).filter(u=>!new RegExp(`\\b${Re(u)}\\b`,"i").test(o));r.length>0&&n.push({type:"missing_goal_labels",detail:`Missing requested row labels in the generated index: ${r.join(", ")}`});let s=/\b(?:failed|partial|missing|not\s+found|no\s+[^.\n|]*evidence)\b/i.test(o),i=/\b(?:all\s+checks\s+pass|confirmed\s*:\s*all|everything\s+(?:passes|passed)|fully\s+verified)\b/i.test(e.finalText);s&&i&&n.push({type:"overconfident_final",detail:"Final response claimed all checks pass while the generated index contains failed, partial, missing, or no-evidence rows."});let a=o.split(/\r?\n/u).filter(u=>/\bno\s+[^|\n]*(?:found|evidence|files?)\b/i.test(u)&&!/\b(?:not\s+verified|unverified|unknown|not\s+checked|search\s+scope|checked\s+path)\b/i.test(u));return a.length>0&&n.push({type:"unsupported_absence",detail:`Absence claims need scoped evidence or must be marked unverified: ${a.slice(0,3).join(" ; ")}`}),n}function Rs(e){let t=[],o=n=>{let r;try{r=co(n,{withFileTypes:!0})}catch{return}for(let s of r){let i=`${n}/${s.name}`;if(s.isDirectory()){o(i);continue}if(s.isFile())try{qe(i).size>0&&t.push(i)}catch{}}};try{if(!qe(e).isDirectory())return[]}catch{return[]}return o(e),t}function yo(e,t){if(!gs(e))return[];let o=He(e),n=o.filter(i=>!$(i).endsWith("/*"));if(n.length<2)return[];let r=hs(n);if(!r||r.split("/").length<3)return[];let s=$(r);return[...new Set([...Cs(t),...Rs(r)])].filter(i=>$(i).startsWith(`${s}/`)&&!Ts(i,o)&&Ft(i))}function Nt(e,t){let o=He(e);if(o.length===0)return[];let n=po(t);return o.filter(r=>!fs(n,r))}function Lt(e){return be(e).fail}function bs(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function je(e){if(!e)return!1;let t=bs(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function be(e){let t=r=>r.replace(/[.,;:]+$/u,""),o,n;for(let r of e)if(!(r.role!=="user"||typeof r.content!="string")){for(let s of r.content.matchAll(/\b(DONE|PASS)\s+([A-Za-z0-9_.:-]+)/gi))je(s[2])&&(o=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))je(s[1])&&(n=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))je(s[1])&&(o=`${t(s[1])} ${s[2].toUpperCase()}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+FAIL\b/gi))je(s[1])&&(n=`${t(s[1])} FAIL`)}return{done:o,fail:n}}function Bt(e){let t=n=>n.replace(/[.,;:]+$/u,""),o;for(let n of e){if(n.role!=="user"||typeof n.content!="string")continue;let r=n.content;for(let s of r.matchAll(/\bMarker\s*:\s*([A-Za-z0-9_.:-]+)/gi))o=t(s[1]);for(let s of r.matchAll(/\b(?:include|with|contains?)\s+marker\s+([A-Za-z0-9_.:-]+)/gi))o=t(s[1])}return o}function ue(e){for(let t=e.length-1;t>=0;t--){let o=e[t];if(o.role==="user"&&typeof o.content=="string")return o.content}return""}function Re(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xs(e,t){let o=ue(e);for(let n of[t.done,t.fail]){if(!n)continue;let s=new RegExp(`\\bfinal\\s+(?:answer|response|reply)\\s+exactly\\s*:?\\s*${Re(n)}([^\\n]*)`,"i").exec(o);if(s){let p=(s[1]??"").trimStart();if(p===""||/^[.!?]/u.test(p))return n}let a=new RegExp(`\\b(?:reply|respond)\\s+exactly(?:\\s+with)?\\s*:?\\s*${Re(n)}([^\\n]*)`,"i").exec(o);if(!a)continue;let u=(a[1]??"").trimStart();if(u===""||/^[.!?。!?]/u.test(u))return n}}function Dt(e,t){let o=xs(e,t);if(o)return o;let n=ue(e),r=Bt(e);if(r){let a=/\breply\s+with\s+(?:the\s+)?marker\s+plus\s+suffix\s+([A-Za-z0-9_.:-]+)\s+as\s+one\s+token\b/i.exec(n)?.[1]?.replace(/[.,;:]+$/u,"");if(a)return`${r}${a}`}return/\b(?:reply|respond)\s+exactly(?:\s+with)?\s*:?\s*([A-Za-z0-9_.:-]+)(?:\s*$|[.!?\u3002\uFF01\uFF1F])/i.exec(n)?.[1]?.replace(/[.,;:]+$/u,"")}function _s(e,t,o){let n=ue(e),r=[t.done,t.fail,o].filter(s=>typeof s=="string"&&s.length>0);return[...new Set(r)].filter(s=>new RegExp(`\\bstarts?\\s+with\\s+${Re(s)}\\b`,"i").test(n))}function ie(e){let t=Nt(e.inputMessages,e.messages).filter(n=>!Ft(n));return t.length===0?void 0:`${Lt(e.inputMessages)??"FAIL"} ${e.reason}. Missing required output file evidence: ${t.join(", ")}`}function ze(e){let t=be(e.inputMessages);if(!t.done){let n=Bt(e.inputMessages)??Dt(e.inputMessages,t);return n?`FAIL ${n} ${e.reason}. The model did not produce the requested final marker ${n}.`:void 0}return`${t.fail??"FAIL"} ${e.reason}. The model did not produce the requested final marker ${t.done}.`}function $t(e){let t=be(e.inputMessages),o=Dt(e.inputMessages,t);if(!o)return;if(He(e.inputMessages).length===0){let i=ue(e.inputMessages);return!mo(i)||!fo(e.messages).some(p=>p.includes(o))?void 0:go({inputMessages:e.inputMessages,messages:e.messages,finalText:""}).length===0?o:void 0}if(!(Nt(e.inputMessages,e.messages).filter(i=>!Ft(i)).length>0||yo(e.inputMessages,e.messages).length>0))return o}function Ut(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function jt(e){for(let t of["path","filePath","file_path"]){let o=e[t];if(typeof o=="string"&&o.trim())return o}}function ho(e){for(let t of["content","newContent","replacement","text"]){let o=e[t];if(typeof o=="string")return o}return""}function To(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let o=be(e.inputMessages);if(!o.done)return;let n=Ut(e.toolCall.function.arguments);if(!n)return;let r=jt(n),s=ho(n);if(!r||!s.includes(o.done))return;let i=He(e.inputMessages);if(i.length<2)return;let a=$(r);if(!i.some(m=>$(m)===a))return;let p=po(e.messages),f=i.filter(m=>$(m)!==a).filter(m=>!p.includes($(m)));if(f.length!==0)return`Premature completion artifact blocked: this write/edit attempted to store the requested DONE marker in ${r} before evidence existed for sibling required output files: ${f.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function J(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Ms(e){let t=e,o=t.is_error===!0||typeof t.content=="string"&&t.content.startsWith("Error:");return t.role==="tool"&&typeof t.content=="string"&&!o}function As(e){let t=[...e].reverse().find(o=>o.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
|
|
7
7
|
|
|
8
8
|
\u923F\u72C5\u7B0D NOTE: You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail silently or produce incorrect results on this platform. Please use the 'write' tool directly to create the requested file with the correct content.`)}function Q(e,t,o,n){return{reason:e,messages:[...t,o,n],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function qt(e){let t=e.inputMessages.find(g=>g.role==="user"),o=typeof t?.content=="string"?t.content:"",n=is.test(o),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=be(e.inputMessages),i=Bt(e.inputMessages),a=_s(e.inputMessages,s,i),u=s.done!==void 0&&e.finalText.includes(s.done)||s.fail!==void 0&&e.finalText.includes(s.fail)||i!==void 0&&e.finalText.includes(i),p=a.length===0||a.some(g=>e.finalText.trimStart().startsWith(g)),f=Dt(e.inputMessages,s),m=Nt(e.inputMessages,e.messages);if(m.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${m.length} file(s) missing`);let g=Lt(e.inputMessages),T={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${m.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${g??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return Q("explicit_required_file_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}let C=yo(e.inputMessages,e.messages);if(C.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${C.length} unexpected file(s)`);let g=Lt(e.inputMessages),T={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${C.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${g??"FAIL"} and the real reason. Do not claim completion while extra deliverables remain.`};return Q("explicit_extra_file_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}let M=go({inputMessages:e.inputMessages,messages:e.messages,finalText:e.finalText});if(M.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`artifact index evidence verification: ${M.length} issue(s)`);let g=f??s.done??i??"the requested marker",T={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+M.map(b=>b.detail).join(" ")+` Use the exact requested Goal row labels, cite concrete evidence names/paths for status claims, and mark a row as not verified/unknown instead of claiming exhaustive absence without scoped evidence. Do not claim all checks pass while any row is failed, partial, missing, or unverified. After correcting and verifying the file, reply exactly with ${g}.`};return Q("artifact_index_evidence_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}if(a.length>0&&e.totalToolCallCount>0&&!p){e.log.info("final marker verification: explicit final marker was not at the start of the response");let g={role:"user",content:`The requested output file evidence is present, but your final response did not start with the explicit completion marker. Your final response must start with one of the requested final markers: ${a.join(" or ")}. No preface, heading, markdown emphasis, or summary may appear before the marker.`};return Q("final_marker_verification",e.messages,J(e.finalText,e.thinkingBlocks),g)}if((s.done!==void 0||i!==void 0)&&e.totalToolCallCount>0&&!u){e.log.info("final marker verification: explicit final DONE/FAIL marker missing");let g=s.done??i,T={role:"user",content:"The requested output file evidence is present, but your final response omitted the explicit completion marker. "+(s.done?`If you have verified the artifacts, Reply exactly with ${s.done}. `:`Your final response must include marker ${g} and clearly say whether the run passed or failed. `)+(s.fail?`If verification failed, reply with ${s.fail} and the real reason. `:`If verification failed, reply with FAIL ${g??""} and the real reason. `)+"Do not end the turn without one of the requested final markers."};return Q("final_marker_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}if(f!==void 0&&e.finalText.trim()!==f){e.log.info("final marker verification: exact-only final marker response had extra text");let g={role:"user",content:`Reply exactly with ${f} and no other text.`};return Q("final_marker_verification",e.messages,J(e.finalText,e.thinkingBlocks),g)}if(u&&r||e.stopHookActive)return null;if(n&&!r){e.log.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),e.totalToolCallCount>0&&As(e.messages);let g={role:"user",content:e.totalToolCallCount===0?"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes - actually make them.":"You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail on this platform. Please use the write tool directly to create the requested file with the correct content."};return Q("file_action_verification",e.messages,J(e.finalText,e.thinkingBlocks),g)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(Ms).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let T={role:"user",content:"You created multiple files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. If everything is correct, confirm completion. If not, fix the issues now."};return Q("multi_file_skeleton_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}return null}function vs(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function Co(e){if(!e.hooks)return null;let t=await e.hooks.invoke("stop",{sessionId:e.sessionId,reason:"completed"});if(t.action==="prevent")return e.log.info(`stop hook prevented continuation: ${t.reason??"no reason"}`),{action:"end",content:e.finalText};if(t.action==="abort"){let o=t.reason??"Stop hook requested continuation";e.log.info(`stop hook blocking: ${o}`);let n={role:"user",content:o};return{action:"continue",messages:[...e.messages,vs(e.finalText,e.thinkingBlocks),n],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var Ss=5;function Es(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function ws(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function ko(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=Ss)return null;let t=Es(e.totalUsage),o=t/e.tokenBudget*100,n=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=An&&n<ct&&e.lastBudgetDeltaTokens<ct)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(o)}% (delta=${n})`),null;if(o>=90)return null;let s=e.budgetContinuationCount+1,i={role:"user",content:e.getBudgetContinuationMessage(o,t,e.tokenBudget)};return e.log.info(`token budget continuation #${s}: ${Math.round(o)}% used`),{messages:[...e.messages,ws(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:n,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(o)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function Ht(e){if(e.totalToolCallCount<=0)return null;let t={ok:!0,toolCallCount:e.totalToolCallCount,distinctToolCount:e.distinctToolNames.size,multiStep:e.totalToolCallCount>=2,hasSubAgent:!1,feedback:null,existingSkillName:null};return pt(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function Ro(e,t){let o=[],n=[];for(let r of e){let s=t.get(r.function.name)??0;s>=Oe?n.push({call:r,failCount:s,error:`Tool "${r.function.name}" has failed ${s} times this turn with different arguments. The target likely does not exist. Stop trying variations and report the issue to the user.`}):o.push(r)}return{allowed:o,blocked:n}}function bo(){return{role:"user",content:"Tool calls were blocked because the tool has failed too many times with different arguments. The resource you are looking for does not exist. Stop trying variations and tell the user what happened."}}function xo(e){if(e.ok&&!e.softEmpty)return;let t=e.toolFailureCounts.get(e.toolName)??0;e.toolFailureCounts.set(e.toolName,t+1)}function _o(e){let t=[];for(let[o,n]of e.toolFailureCounts)n>=Oe&&(e.snapshot.get(o)??0)<Oe&&t.push({role:"user",content:`Tool "${o}" has now failed/returned empty results ${n} times with different arguments. The target clearly does not exist. Do NOT call "${o}" again. Report the result to the user immediately.`});return t}function Ps(e,t){if(e.length!==1||e[0]?.function.name!=="stt")return!1;let o=[...t].reverse().find(i=>i.role==="user");if(!o)return!1;let n=Array.isArray(o.audioUrls)&&o.audioUrls.some(i=>typeof i=="string"&&i.trim()),r=typeof o.content=="string"?o.content:"",s=/\b(?:stt|speech[-\s]?to[-\s]?text|transcribe|transcription|audio[-\s]?to[-\s]?text)\b|转写|转录|语音转文字|音频转文字|听写/i.test(r);return n&&s}function Ls(e,t){let o=Os(t);if(!o)return null;let n=Fs(o);if(!n)return null;let r=[...e].reverse().find(a=>a.role==="user"),s=typeof r?.content=="string"?r.content:"",i=/\bAUDIO_STT_RESULT\s+([^\s<]+)\s+<transcription\b/i.exec(s);return i?.[1]?`AUDIO_STT_RESULT ${i[1]} ${n}`:n}function Os(e){let t=[e.details?.transcription,e.details?.text,e.details?.preview];for(let n of t)if(typeof n=="string"&&n.trim())return n.trim();let o=e.message?.content;return typeof o=="string"?o.trim():""}function Fs(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}var zt=new Set(["read","search"]),Ns=new Set(["write","edit","patch","image_generate"]);function Bs(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let o=t.slice(0,t.indexOf("::"));zt.has(o)&&e.identicalCallCounts.delete(t)}}async function*Mo(e,t,o,n){let{turnId:r,sessionId:s,messages:i,tools:a,model:u,apiKey:p,temperature:f=0,hooks:m,signal:C}=e,M={sessionId:s,turnId:r},g=e.maxTurns??0,T=e.querySource,b=e.runtimePorts.resolveToolEligibility(a,e.toolEligibilityContext),R=b.eligibleTools;for(let y of b.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:y.toolName,reason:"blocked-by-policy"};let A=Vn(e.maxRounds,i),O=Zn(e.maxToolCalls,i),xe=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),Ge=Ue(i),H={contextWindowTokens:e.contextWindowTokens??kn,responseBufferTokens:Rn,maxOutputTokens:e.maxOutputTokens??bn,abortSignal:C,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},w=new Set,F=0,de=0,pe=0,_e=0,W=R,Io=Ps(R,i),Me,We=!1,Gt=0,Wt=0,Ke=!1,Ae=!1,c={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Rt(H),reactiveCompactState:At(),toolLoopState:Be({maxRounds:A,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:it(),currentModel:u,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,finalMarkerEmptyRecoveryCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,fileReadCounts:new Map,recoveryTrace:new Map},Xe=Math.max(g*5,200),Kt=0,I=(y,N)=>(c.recoveryTrace.set(y,(c.recoveryTrace.get(y)??0)+1),{type:"recovery",turnId:r,action:y,detail:N}),L=y=>({type:"end",turnId:r,content:y,usage:c.totalUsage,model:c.currentModel,...c.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(c.recoveryTrace)}:{}}),me=(y,N)=>{let K=$t({inputMessages:i,messages:y});if(K)return K;if(c.finalText.trim()===""){let U=ze({inputMessages:i,reason:N});if(U)return U}return c.finalText||Et(y,n)},Po=(y,N,K)=>{let U=ie({inputMessages:i,messages:N,reason:K});if(U)return U;if(y.trim()===""){let v=ze({inputMessages:i,reason:K});if(v)return v}return y||Et(N,n)};for(;;){if(Kt++,Kt>Xe){n.info(`hard iteration cap reached (${Xe}), forcing completion`);let l=me(c.messages,`hard iteration cap reached (${Xe}) before producing the requested final marker`);yield L(l);return}let{messages:y,maxOutputTokensRecoveryCount:N,maxOutputTokensOverride:K,turnCount:U,guardState:v,reactiveCompactState:z,collapseStore:Ye}=c,{toolLoopState:B}=c;if(Me){try{let l=await Me;l&&(yield{type:"tool_use_summary",turnId:r,summary:l})}catch{}Me=void 0}if(e.refreshTools&&U>1){let l=e.refreshTools();l!==W&&(W=l,n.debug(`tools refreshed: ${l.length} tools`))}if(Mt(v,H)){n.info(`turn aborted by guard at turn ${U}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:c.totalUsage};return}let ee=bt(v,H);if(ee.level==="blocking"){ee.reason==="prompt_too_long"&&le(z)&&(z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${ee.reason}), reactive compact needed`),yield I("reactive_compact","token budget pre-check")),n.info(`token budget blocking (${ee.reason}), ending tool loop`);break}ee.level==="warning"&&n.info(`token budget warning: ${ee.usagePercent}% used, ${ee.remainingTokens} remaining`);let ve=yield*oo({messages:y,contentReplacementState:c.contentReplacementState,snipRemovedIds:c.snipRemovedIds,collapseStore:Ye,guardState:v,guardConfig:H,runtimePorts:e.runtimePorts,hooks:m,hookCtx:M,sessionId:s,currentModel:c.currentModel,log:n,recovery:I,onAutocompact:()=>{c.hasAttemptedReactiveCompact=!1}}),Lo=Ke?"required":e.toolChoice==="required"&&We?"auto":e.toolChoice??"auto";Ke=!1;let fe=mt({tools:W,toolChoice:Lo}),ge=Be({maxRounds:A,replayMessages:ve,lastStopReason:B.lastStopReason,options:{stopReason:B.lastStopReason}}),Xt=fe.extraSystemPrompt?[{role:"system",content:fe.extraSystemPrompt},...ge.state.replayMessages]:ge.state.replayMessages;B=ge.state,ge.recoveryActions.length>0&&n.debug(`tool loop recovery: ${ge.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),n.debug(`turn ${U}, messages: ${Xt.length}`),E(m,"turn.before_inference",{...M,model:c.currentModel},n);let Ve=!1,Ze=[],Yt=new Map,Vt="stop",D,x=null,Se=!1,Zt=!1,ye=[],G=[];try{for await(let l of t.stream({model:c.currentModel,messages:Xt,...fe.tools.length>0?{tools:fe.tools,toolChoice:fe.normalizedToolChoice??"auto"}:{},temperature:f,maxTokens:(K??v.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:Ae?void 0:c.lastResponseId,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},p,C))switch(l.type){case"delta":Ze.push(l.text);break;case"tool_call_delta":Ve=!0,vt(Yt,l);break;case"reasoning_delta":ye.push(l.text);break;case"reasoning_block_complete":l.signature&&G.push({thinking:ye.join(""),signature:l.signature}),ye.length=0;break;case"usage":D={inputTokens:l.promptTokens,outputTokens:l.completionTokens,reasoningTokens:l.reasoningTokens,cacheRead:l.cacheReadTokens,cacheWrite:l.cacheCreationTokens};break;case"response_id":Ae||(c.lastResponseId=l.id);break;case"annotations":yield{type:"annotations",turnId:r,annotations:l.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${l.toolType}: ${l.event}`};break;case"done":Zt=!0,Vt=l.finishReason;break}if(Ve||E(m,"turn.after_inference",{...M,model:c.currentModel},n),e.postSamplingHooks&&e.postSamplingHooks.length>0){let l=c.currentModel;for(let d of e.postSamplingHooks)try{d({messages:[...ve],model:l,sessionId:s})}catch{}}}catch(l){let d=yield*ro(l,{state:c,guardState:v,fallbackModel:e.fallbackModel,signal:C,querySource:T,turnId:r,log:n,emitRecovery:I});if(d.kind==="return")return;if(d.kind==="continue"){c={...c,...d.patch};continue}x=d.streamError}if(!x&&!Zt){let l="LLM stream closed before a terminal event; the response was likely truncated upstream.";E(m,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:l},n),yield{type:"error",turnId:r,error:l,code:"RETRYABLE_TRANSIENT",usage:c.totalUsage};return}if(x&&E(m,"turn.after_inference",{...M,model:c.currentModel,response:{error:x.message}},n),x){if(!Ae&&c.lastResponseId&&/previous_response_id not found/i.test(x.message)){let l=(c.consecutiveApiRetries??0)+1;if(l<=se){n.info("previous_response_id not found \u2014 disabling response-id chaining, retrying statelessly"),yield I("stateless_retry","previous_response_id not found; replaying full history"),Ae=!0,c={...c,lastResponseId:void 0,consecutiveApiRetries:l,transition:void 0};continue}}if(It(x))Se=!0,n.info(`withheld prompt_too_long error (status=${x.status})`);else if(Pt(x))Se=!0,n.info(`withheld media_size error (status=${x.status})`);else{let l=xt({status:x.status??500,message:x.message},v,H);if(l.action==="reactive_compact"&&le(z)&&(z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,yield I("reactive_compact",`API ${x.status??500}: ${x.message}`)),l.action==="retry"){let h=(c.consecutiveApiRetries??0)+1;if(h>se){n.info(`API retry limit reached (${se}), aborting`);let k=ae(x.status,x.message);yield{type:"error",turnId:r,error:x.message,code:k,usage:c.totalUsage};return}yield I("retry",l.reason),c={...c,consecutiveApiRetries:h,transition:void 0};continue}let d=ae(x.status,x.message);E(m,"stop.failure",{sessionId:s,reason:d,error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:d,usage:c.totalUsage};return}}D&&(c.totalUsage.inputTokens+=D.inputTokens,c.totalUsage.outputTokens+=D.outputTokens,D.reasoningTokens&&(c.totalUsage.reasoningTokens=(c.totalUsage.reasoningTokens??0)+D.reasoningTokens),D.cacheRead&&(c.totalUsage.cacheRead=(c.totalUsage.cacheRead??0)+D.cacheRead),D.cacheWrite&&(c.totalUsage.cacheWrite=(c.totalUsage.cacheWrite??0)+D.cacheWrite)),D?.inputTokens&&(v.promptTokens=D.inputTokens);let Ee=Ze.join(""),j=[...Yt.values()].map((l,d)=>({id:l.id||`tc_${r}_${d}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(j.length===0&&!Ve){if(Ee&&(c.finalText=Ee),e.toolChoice==="required"&&!We&&W.length>0&&Gt<2){Gt++;let _=W.map(P=>P.function.name).filter(Boolean).slice(0,8).join(", ");c={...c,messages:[...y,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${_}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(Se&&x&&It(x)){if(c.transition?.reason!=="collapse_drain_retry"){let _=lt(ve,Ye);if(_.committed>0){n.info(`collapse drain: committed ${_.committed} stages`),yield I("collapse_drain",`${_.committed} stages committed`),c={...c,messages:_.messages,transition:{reason:"collapse_drain_retry",committed:_.committed}};continue}}if(le(z)){z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info("withheld 413: reactive compact attempt"),yield I("reactive_compact","withheld prompt_too_long"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld 413: recovery exhausted, surfacing error"),E(m,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:"PROMPT_TOO_LONG",usage:c.totalUsage};return}if(Se&&x&&Pt(x)){if(le(z)){z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info("withheld media error: reactive compact strip-retry"),yield I("reactive_compact","media error strip-retry"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld media error: recovery exhausted"),E(m,"stop.failure",{sessionId:s,reason:"media_error",error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:"IMAGE_ERROR",usage:c.totalUsage};return}if(eo(Vt)){v.consecutiveTruncations+=1;let _=e.modelMaxOutputTokens??xn,P=_t(v,H,_);if(P.shouldEscalate&&K===void 0){v.currentMaxOutputTokens=P.newMax,n.info(`max_output_tokens escalate: ${P.newMax} tokens`),yield I("output_escalation",`${P.newMax} tokens`),c={...c,maxOutputTokensOverride:Mn,transition:{reason:"max_output_tokens_escalate"}};continue}if(N<_n){let Y={role:"user",content:"Output token limit hit. Resume directly - no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};n.info(`max_output_tokens recovery #${N+1}`),yield I("max_output_tokens_recovery",`attempt ${N+1}`),c={...c,messages:[...ve,Y],maxOutputTokensRecoveryCount:N+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:N+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else v.consecutiveTruncations=0;B=Ne(B,{replayMessages:y,lastStopReason:"completed"});let l=await Co({hooks:m,sessionId:s,messages:y,finalText:c.finalText,thinkingBlocks:G,log:n});if(l?.action==="end"){let _=Po(l.content,y,"stop hook prevented continuation before producing the requested final marker");yield L(_);return}if(l?.action==="continue"){c={...c,messages:l.messages,stopHookActive:l.stopHookActive,transition:l.transition};continue}let d=ko({tokenBudget:e.tokenBudget,totalUsage:c.totalUsage,budgetContinuationCount:c.budgetContinuationCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,messages:y,finalText:c.finalText,thinkingBlocks:G,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:n});if(d){yield I("budget_continuation",d.recoveryDetail),c={...c,messages:d.messages,budgetContinuationCount:d.budgetContinuationCount,lastBudgetDeltaTokens:d.lastBudgetDeltaTokens,lastBudgetGlobalTokens:d.lastBudgetGlobalTokens,transition:d.transition};continue}let h=qt({inputMessages:i,messages:y,finalText:c.finalText,thinkingBlocks:G,stopHookActive:c.stopHookActive,totalToolCallCount:F,distinctToolNames:w,log:n});if(h){if(c.stopHookActive&&(h.reason==="final_marker_verification"||c.finalText.trim()==="")){let _=ie({inputMessages:i,messages:h.messages,reason:"final marker verification produced an empty response after tool use"});if(_){yield L(_);return}if(h.reason==="final_marker_verification"&&c.finalText.trim()===""&&c.finalMarkerEmptyRecoveryCount<1){yield I("final_marker_empty_retry","one extra retry after empty marker nudge"),c={...c,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition,finalMarkerEmptyRecoveryCount:c.finalMarkerEmptyRecoveryCount+1};continue}let P=$t({inputMessages:i,messages:h.messages});if(P){yield L(P);return}let Y=ze({inputMessages:i,reason:"final marker verification produced an empty response after tool use"});if(Y){yield L(Y);return}}c={...c,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition};continue}if(F===0&&W.length>0&&e.toolChoice!=="none"&&Wt<1&&Yn(Ee)){Wt++,Ke=!0,yield I("intent_without_action","announced but did not act; forcing a tool call"),c={...c,messages:[...y,{role:"assistant",content:Ee},{role:"user",content:"You announced an action but did not take it. Carry it out NOW, in this response: call the appropriate tool to actually do what you just said you would do. Do not restate your intention or describe a plan \u2014 perform it."}],finalText:"",transition:{reason:"next_turn"}};continue}let k=Ht({totalToolCallCount:F,distinctToolNames:w,projectRoot:e.projectRoot});k&&(yield{type:"skill_instruction",turnId:r,instruction:k});let S=me(y,"the model ended with an empty response after tool use before producing the requested final marker");for(let _ of Ze)yield{type:"delta",turnId:r,text:_};yield L(S);return}let Oo=G.length===0&&ye.length>0?ye.join(""):void 0;y.push(nt(j,void 0,G.length>0?G:void 0,Oo)),B=Tt(B,{replayMessages:y,pendingToolCallIds:j.map(l=>l.id),completedToolCallIds:B.completedToolCallIds,lastStopReason:"tool_calls"});let we=c.identicalCallCounts,Jt=[],Ie=[],Qt=[],en=!1;for(let l of j){let d=`${l.function.name}::${l.function.arguments}`,h=we.get(d)??0;if(we.set(d,h+1),h+1>Cn){let k=zt.has(l.function.name)?c.identicalSuccessfulToolResults.get(d):void 0;if(k){Qt.push({call:l,result:k,repeatCount:h+1});continue}Ie.push(l),en||(en=!0,n.info(`AP4 blocked: ${l.function.name} repeated ${h+1}x`))}else Jt.push(l)}let X=[];for(let l of Qt){let d=l.call,h=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${l.repeatCount}); no additional tool execution was performed.
|
|
9
9
|
|