qlogicagent 2.22.3 → 2.22.4
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 +2 -2
- package/dist/cli.js +1 -1
- package/dist/index.js +293 -293
- package/dist/types/runtime/execution/streaming-tool-executor.d.ts +2 -0
- package/dist/types/runtime/execution/tool-result-storage.d.ts +2 -0
- package/dist/types/runtime/ports/agent-runtime-ports.d.ts +1 -0
- package/package.json +1 -1
package/dist/agent.js
CHANGED
|
@@ -26,7 +26,7 @@ ${n}
|
|
|
26
26
|
`),s=!1,a=null;for(let l of r){let i=l.trimEnd();if(i.startsWith("*** Add File: "))s=!0,o(i.slice(14));else if(i.startsWith("*** Update File: "))s=!0,o(i.slice(17));else if(i.startsWith("*** Delete File: ")){s=!0;let f=i.slice(17).trim();f&&(t.push(f),n.push(f))}else if(i.startsWith("*** Move to: "))s=!0,o(i.slice(13));else if(i.startsWith("*** Move File: ")){s=!0;let f=i.slice(15).trim(),[m,y]=f.split(" -> ");o(m),o(y)}else if(i.startsWith("--- ")){s=!0;let f=sr(i.slice(4).trim());a=f||null,f&&f!=="/dev/null"&&t.push(f)}else if(i.startsWith("+++ ")){s=!0;let f=sr(i.slice(4).trim());f&&f!=="/dev/null"&&t.push(f),f==="/dev/null"&&a&&a!=="/dev/null"&&n.push(a),a=null}}if(!s&&e.includes("<<<< SEARCH")){let i=(e.split(/^(<<<< SEARCH)$/m)[0]??"").trim().split(`
|
|
27
27
|
`).pop()?.trim();o(i)}return{paths:t,deletes:n}}function sr(e){let t=e.trim();if(!t||t==="/dev/null")return t;let n=t.indexOf(" ");n!==-1&&(t=t.slice(0,n));let o=t.search(/\s+\d{4}-\d{2}-\d{2}/);return o!==-1&&(t=t.slice(0,o)),t.startsWith('"')&&t.endsWith('"')&&(t=t.slice(1,-1)),t.startsWith("a/")||t.startsWith("b/")?t.slice(2):t}var bu=/create\s+(?:a\s+)?file|write\s+(?:a\s+)?file|make\s+(?:a\s+)?file|generate\s+(?:a\s+)?file|new\s+file/i,Tu=/\bfix\b|implement|modify|update|repair/i,Et=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,Oi=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,ku=/\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,Cu=/(?:^|[\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,Ru=/(?:^|[\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,xu=/(?:^|[\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,_u=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i,ir=/(?:do\s*not|don'?t|never|不要|不能|别|勿|禁止|不准|不得)[^.。;;\n]{0,14}(?:create|write|make|produce|generate|生成|创建|写入|写出|建立|新建)/i;function H(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase()}function Bi(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function Ni(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function Li(e,t,n){let o=Math.max(e.lastIndexOf(".",t),e.lastIndexOf(`
|
|
28
28
|
`,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+${qi(n)}\\b`,"i").test(s)}function gn(e){return e.replace(/https?:\/\/\S+/gu," ")}var vu=/\b(?:read|analy[sz]e|inspect|review|open|load|parse|consume|input|source)\b|读取|阅读|分析|检查|查看|打开|载入|输入|源文件/gi,wu=/\b(?:write|create|generate|save|output|produce|deliver|export|update|modify|edit)\b|写入|创建|生成|保存|输出|交付|导出|更新|修改|编辑/gi;function Fi(e,t){let n=-1;for(let o of e.matchAll(t))n=o.index??n;return n}function Su(e){let t=new Set;for(let n of e){if(n.role!=="user"||typeof n.content!="string")continue;let o=gn(n.content);for(let r of o.matchAll(Et)){let s=r[0],a=o.slice(0,r.index??0),l=Fi(a,vu),i=Fi(a,wu);l>i&&t.add(H(s))}}return t}function mn(e){let t=new Set,n=[],o=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B]+$/u,""),a=H(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=gn(r.content);for(let a of s.matchAll(Et)){let l=a[0],i=(a.index??0)+l.length;if(s[i]==="/"||s[i]==="\\")continue;o(l);let f=l.replace(/\\/g,"/"),m=f.lastIndexOf("/");if(m>=0){let y=f.slice(0,m+1);Oi.lastIndex=i;let T;for(;(T=Oi.exec(s))!==null;)o(`${y}${T[1]}`)}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=gn(r.content);if(!Jo.test(s))continue;let a=Array.from(s.matchAll(ku)).map(m=>Bi(m[1]??"")).filter(m=>m&&!Ni(m));if(a.length===0)continue;let l=a[a.length-1],i=Array.from(s.matchAll(Et)).map(m=>({start:m.index??0,end:(m.index??0)+m[0].length})),f=m=>i.some(y=>m>=y.start&&m<y.end);for(let m of s.matchAll(Cu)){let y=m[1];if(!y)continue;let T=(m.index??0)+m[0].indexOf(y);f(T)||Li(s,m.index??0,y)||o(`${l}/${y}`)}for(let m of s.matchAll(Ru)){let y=m[1];if(!y)continue;let T=(m.index??0)+m[0].indexOf(y);f(T)||Li(s,m.index??0,y)||o(`${l}/${y}`)}for(let m of s.matchAll(xu)){let y=m[1];y&&(Ni(y)||/(?:assets[\\/]generated|screenshots(?:[\\/]|$)|previews(?:[\\/]|$))/i.test(y)&&/\b(?:generated|bitmap|png|screenshots?|preview|previews|evidence|assets?|containing)\b/i.test(s)&&o(`${l}/${y}/*`))}_u.test(s)&&o(`${l}/previews/*`)}return n}function Ue(e){if(e.role!=="tool")return!1;let t=typeof e.content=="string"?e.content:"";return e.is_error!==!0&&!t.startsWith("Error:")}function Au(e){if(!Ue(e))return!1;let t=typeof e.content=="string"?e.content:"";return!/^\s*Error:/i.test(t)&&!/(?:^|\n)\s*Errors:\s*(?:\n|$)/i.test(t)&&!/^\s*No changes applied\.\s*$/i.test(t)}function ji(e){let t=new Set;for(let o of e){let r=o;Au(r)&&typeof r.tool_call_id=="string"&&t.add(r.tool_call_id)}let n=[];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,i=l.function;if(i?.name!=="patch"||typeof l.id!="string"||!t.has(l.id)||typeof i.arguments!="string")continue;let f=He(i.arguments);typeof f?.input=="string"&&n.push(...Ii(f.input).paths)}}return n}function ar(e){let t=new Set,n=new Map,o=[...ji(e)];for(let r of e){let s=r,a=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let l of a){let i=l,f=i.id,m=i.function;typeof f=="string"&&typeof m?.name=="string"&&n.set(f,m.name)}}for(let r of e){let s=r;if(Ue(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 i=l,f=i.id;if(typeof f!="string"||!t.has(f))continue;let m=i.function;if(!(typeof m?.name!="string"||typeof m.arguments!="string"))try{let y=JSON.parse(m.arguments);if(m.name==="write"||m.name==="edit"){for(let T of["path","filePath","file_path"]){let v=y[T];typeof v=="string"&&o.push(v)}continue}if(m.name==="exec"){let T=y.command;typeof T=="string"&&o.push(T)}}catch{m.name==="exec"&&o.push(m.arguments)}}}return o.join(`
|
|
29
|
-
`).replace(/\\/g,"/").toLowerCase()}function hn(e){try{if(e.endsWith("/*")){let n=e.slice(0,-2);return Di(n,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return At(`${n}/${r.name}`).size>0}catch{return!1}})}let t=At(e);return t.isFile()&&t.size>0}catch{return!1}}function Eu(e,t){let n=H(t);if(!n.endsWith("/*"))return e.includes(n);let o=n.slice(0,-1);return e.includes(o)}function Ui(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,i=a.function;typeof l=="string"&&i?.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)&&Ue(o))return!0}return!1}function Mu(e){let t=Hi(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 Pu(e){let t=Bi(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function Iu(e){if(e.length===0)return"";let t=e.map(o=>Pu(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 Ou(e,t){let n=H(e);return t.some(o=>{let r=H(o);return r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r})}function lr(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,i=l.id,f=l.function;if(typeof i!="string"||f?.name!=="write"&&f?.name!=="edit"||typeof f.arguments!="string")continue;let m=He(f.arguments);if(!m)continue;let y=Mt(m);y&&n.set(i,y)}}for(let o of e){let r=o;if(!Ue(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 Nu(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 Lu(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function Fu(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,i=l.id,f=l.function;if(typeof i!="string"||f?.name!=="write"&&f?.name!=="edit"||typeof f.arguments!="string")continue;let m=He(f.arguments);if(!m)continue;let y=Mt(m)??"",T=Gi(m);(/\bartifact[-_\s]?index\b/i.test(y)||/\bartifact[-_\s]?index\b/i.test(T))&&n.set(i,T)}}for(let o of e){let r=o;if(!Ue(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 $u(e){let t=Hi(e.inputMessages);if(!Nu(t))return[];let n=Fu(we(e.inputMessages,e.messages)).at(-1);if(!n)return[];let o=[],r=Lu(t).filter(a=>!new RegExp(`\\b${qi(a)}\\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=n.split(/\r?\n/u).filter(a=>/\bno\s+[^|\n]*(?:found|evidence|files?)\b/i.test(a)&&!/\b(?:not\s+verified|unverified|unknown|not\s+checked|search\s+scope|checked\s+path)\b/i.test(a));return s.length>0&&o.push({type:"unsupported_absence",detail:`Absence claims need scoped evidence or must be marked unverified: ${s.slice(0,3).join(" ; ")}`}),o}function Du(e){let t=[],n=o=>{let r;try{r=Di(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{At(a).size>0&&t.push(a)}catch{}}};try{if(!At(e).isDirectory())return[]}catch{return[]}return n(e),t}function we(e,t){if(t.length<e.length)return t;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return t;return t.slice(e.length)}function Bu(e,t){if(!Mu(e))return[];let n=mn(e),o=n.filter(a=>!H(a).endsWith("/*"));if(o.length<2)return[];let r=Iu(o);if(!r||r.split("/").length<3)return[];let s=H(r);return[...new Set([...lr(we(e,t)),...Du(r)])].filter(a=>H(a).startsWith(`${s}/`)&&!Ou(a,n)&&hn(a))}function zi(e,t){let n=mn(e);if(n.length===0)return[];let o=Su(e),r=we(e,t),s=ar(r),a=ju(r),l=Uu(r);return n.filter(i=>{if(o.has(H(i))||Eu(s,i))return!1;let f=H(i);return!((a.has(f)||l.has(f))&&hn(i))})}function ju(e){let t=new Set;for(let o of e){let r=o;Ue(r)&&typeof r.tool_call_id=="string"&&t.add(r.tool_call_id)}let n=new Set;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,i=l.function;if(i?.name!=="read"||typeof l.id!="string"||typeof i.arguments!="string"||!t.has(l.id))continue;let f=He(i.arguments),m=f?Mt(f):void 0;m&&n.add(H(m))}}return n}function Uu(e){let t=new Set;for(let o of e){let r=o;Ue(r)&&typeof r.tool_call_id=="string"&&t.add(r.tool_call_id)}let n=new Set;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,i=l.function,f=typeof i?.name=="string"?Ce(i.name):"";if(f!=="image_understand"&&f!=="video_understand"||typeof l.id!="string"||typeof i?.arguments!="string"||!t.has(l.id))continue;let m=He(i.arguments);if(!m)continue;let y=f==="image_understand"?m.image_url:m.video_url;typeof y=="string"&&y.trim()&&n.add(H(y))}}return n}function fn(e){return cr(e).fail}function zu(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function pn(e){if(!e)return!1;let t=zu(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function cr(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))pn(s[2])&&(n=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))pn(s[1])&&(o=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))pn(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))pn(s[1])&&(o=`${t(s[1])} FAIL`)}return{done:n,fail:o}}function Hi(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 qi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ze(e){let t=zi(e.inputMessages,e.messages).filter(n=>!hn(n));if(t.length!==0)return`[Engine notice] ${e.reason}; explicitly requested output files still missing: ${t.join(", ")}.`}function He(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Mt(e){for(let t of["path","filePath","file_path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n}}function Gi(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function Wi(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let n=cr(e.inputMessages);if(!n.done)return;let o=He(e.toolCall.function.arguments);if(!o)return;let r=Mt(o),s=Gi(o);if(!r||!s.includes(n.done))return;let a=mn(e.inputMessages);if(a.length<2)return;let l=H(r);if(!a.some(y=>H(y)===l))return;let f=ar(e.messages),m=a.filter(y=>H(y)!==l).filter(y=>!f.includes(H(y)));if(m.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: ${m.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function Be(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function je(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function Vi(e){try{return At(e).isFile()}catch{return!1}}function Hu(e,t,n){let o=/[,.,。;;!?!?\n]/u,r=t;for(;r>0&&!o.test(e[r-1]);)r--;let s=t+n;for(;s<e.length&&!o.test(e[s]);)s++;if(ir.test(e.slice(r,s)))return!0;let a=s<e.length?s+1:s,l=a;for(;l<e.length&&!o.test(e[l]);)l++;let i=e.slice(a,l);return ir.test(i)&&/(?:这个|该|此)文件|\b(?:this|that|the)\s+file\b/i.test(i)}function qu(e,t){let n=new Map;for(let a of e){if(a.role!=="user"||typeof a.content!="string")continue;let l=gn(a.content);if(ir.test(l))for(let i of l.matchAll(Et)){if(!Hu(l,i.index??0,i[0].length))continue;let f=i[0].replace(/[),.;:,。;]+$/u,""),m=H(f);m&&n.set(m,f)}}if(n.size===0)return[];let o=ar(we(e,t)),r=Ui(we(e,t)),s=[];for(let[a,l]of n)(o.includes(a)||r&&Vi(l))&&s.push(a);return s}var Gu="File not found:",$i=/\b(?:create|write|make|generate|produce|save|output|deliver|initialize|init|ensure|touch|scaffold|build|set\s+up)\b|生成|创建|写入|写出|新建|建立|保存|输出|交付|初始化|确保/i,Wu=/\b(?:if|when|unless)\b[^.。;;\n]{0,40}(?:missing|not\s+exist|does\s*n['o]?t\s+exist|absent|no\s+such)|(?:如果|若|要是|倘若)[^.。;;\n]{0,24}(?:不存在|没有|缺失|不在|未创建)/i;function Vu(e,t){let n=t.slice(t.lastIndexOf("/")+1),o=/[.。;;!?!?\n]/u;for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase(),l=s.includes(t)||n.length<=3||n===t?[t]:[n];for(let i of l){let f=0;for(;;){let m=s.indexOf(i,f);if(m===-1)break;f=m+1;let y=m;for(;y>0&&!o.test(s[y-1]);)y--;let T=m+i.length;for(;T<s.length&&!o.test(s[T]);)T++;let v=r.content.slice(y,T);if($i.test(v))return!0}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase(),l=Array.from(r.content.matchAll(Et)).map(f=>H(f[0])).some(f=>f!==t),i=s.includes(t)||!l&&n.length>3&&n!==t&&s.includes(n);if(!l&&i&&$i.test(r.content)&&Wu.test(r.content))return!0}return!1}function Xu(e){let t=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,i=l.id,f=l.function;if(typeof i!="string"||f?.name!=="read"||typeof f.arguments!="string")continue;let m=He(f.arguments),y=m?Mt(m):void 0;y&&t.set(i,y)}}let n=new Map;for(let o of e){let r=o;if(r.role!=="tool")continue;let s=r.tool_call_id;if(typeof s!="string")continue;let a=t.get(s);if(!a)continue;let l=typeof r.content=="string"?r.content:"";(r.is_error===!0||l.startsWith("Error:"))&&l.includes(Gu)&&n.set(H(a),a)}return n}function Ku(e,t){let n=we(e,t),o=Xu(n);if(o.size===0)return[];let r=new Set(lr(n).map(H)),s=[];for(let[a,l]of o)Vu(e,a)||(r.has(a)||Vi(l))&&s.push(a);return s}function ur(e){let t=[...e.inputMessages].reverse().find(v=>v.role==="user"),n=typeof t?.content=="string"?t.content:"",o=bu.test(n)||Tu.test(n)&&mn(e.inputMessages).length>0,r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit")||ji(we(e.inputMessages,e.messages)).length>0,s=cr(e.inputMessages),a=s.fail!==void 0&&e.finalText.includes(s.fail)||/\bFAILED\b/.test(e.finalText),l=qu(e.inputMessages,e.messages);if(l.length>0&&!a){e.log.info(`forbidden-file-creation guard: agent wrote ${l.length} file(s) the user forbade creating`);let v=fn(e.inputMessages),S={role:"user",content:`You created a file the request explicitly forbade creating: ${l.join(", ")}. That is a constraint violation, not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${v??"FAILED"} with the real reason: the task could not be done without violating the stated constraint. Do not fabricate a successful outcome.`};return je("forbidden_file_creation",e.messages,Be(e.finalText,e.thinkingBlocks),S)}let i=Ku(e.inputMessages,e.messages);if(i.length>0&&!a){e.log.info(`self-created-read-target guard: agent created ${i.length} file(s) it had read as not-found`);let v=fn(e.inputMessages),S={role:"user",content:"You were asked to read "+i.join(", ")+`, but your read showed the file did not exist; you then created it yourself. Manufacturing an input you were told to read is not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${v??"FAILED"} with the real reason: the file does not exist and the task cannot be done without fabricating it.`};return je("self_created_read_target",e.messages,Be(e.finalText,e.thinkingBlocks),S)}let f=Ui(e.messages),m=zi(e.inputMessages,e.messages).filter(v=>!(f&&hn(v)));if(m.length>0&&e.totalToolCallCount>0){if(a)return null;e.log.info(`explicit required file verification: ${m.length} file(s) missing`);let v=fn(e.inputMessages),S={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 ${v??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return je("explicit_required_file_verification",e.messages,Be(e.finalText,e.thinkingBlocks),S)}let y=Bu(e.inputMessages,e.messages);if(y.length>0&&e.totalToolCallCount>0){if(a)return null;e.log.info(`explicit extra file verification: ${y.length} unexpected file(s)`);let v=fn(e.inputMessages),S={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${y.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${v??"FAILED"} and the real reason. Do not claim completion while extra deliverables remain.`};return je("explicit_extra_file_verification",e.messages,Be(e.finalText,e.thinkingBlocks),S)}let T=$u({inputMessages:e.inputMessages,messages:e.messages});if(T.length>0&&e.totalToolCallCount>0){if(a)return null;e.log.info(`artifact index evidence verification: ${T.length} issue(s)`);let v={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+T.map(S=>S.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 je("artifact_index_evidence_verification",e.messages,Be(e.finalText,e.thinkingBlocks),v)}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");let v={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 je("file_action_verification",e.messages,Be(e.finalText,e.thinkingBlocks),v)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")){let v=[...new Set(lr(we(e.inputMessages,e.messages)).map(H))].filter(S=>Yu.test(S)&&!Ju(S));if(v.length>=3){e.log.info(`AP3 verification nudge: ${v.length} code files created, injecting completeness check`);let S={role:"user",content:"You created multiple code 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. Fix anything that fails these checks. Either way, your FINAL message must answer the user's actual request \u2014 do not end on this checklist confirmation."};return je("multi_file_skeleton_verification",e.messages,Be(e.finalText,e.thinkingBlocks),S)}}return null}var Yu=/\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|kts|cs|cpp|cc|c|h|hpp|vue|svelte)$/i;function Ju(e){let t=H(yu());return t.length>0&&e.startsWith(`${t}/`)}function Zu(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function Xi(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,Zu(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var dr="```final-status",Qu=/\r?\n[ \t]*```/;function ed(e,t){let n=Math.min(e.length,t.length-1);for(let o=n;o>0;o--)if(e.endsWith(t.slice(0,o)))return o;return 0}function Ki(){let e="",t=!1;function n(){let o="";for(;;){if(t){let s=Qu.exec(e);if(!s)return o;e=e.slice(s.index+s[0].length),t=!1;continue}let r=e.indexOf(dr);if(r===-1){let s=ed(e,dr);return o+=e.slice(0,e.length-s),e=e.slice(e.length-s),o}o+=e.slice(0,r),e=e.slice(r+dr.length),t=!0}}return{push(o){return o?(e+=o,n()):""},flush(){if(t)return e="","";let o=e;return e="",o},isSuppressing:()=>t}}var Yi=5;function td(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function nd(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function fr(e,t){let n=e.recoveryTrace;if(!n)return;let o=`budget_continuation_stop:${t}`;n.set(o,(n.get(o)??0)+1)}function Ji(e){if(!e.tokenBudget||e.tokenBudget<=0)return null;let t=td(e.totalUsage),n=t/e.tokenBudget*100;if(e.budgetContinuationCount>=Yi)return e.log.info(`token budget continuation stop: continuation cap reached (${e.budgetContinuationCount}/${Yi}) at ${Math.round(n)}% used`),fr(e,"cap"),null;let o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=Bs&&o<Eo&&e.lastBudgetDeltaTokens<Eo)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(n)}% (delta=${o})`),fr(e,"diminishing_returns"),null;if(n>=90)return e.log.info(`token budget continuation stop: ${Math.round(n)}% of ${e.tokenBudget} tokens used (>=90% headroom floor), not nudging further work`),fr(e,"headroom_floor"),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,nd(e.finalText,e.thinkingBlocks),a],budgetContinuationCount:s,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}var at="*";function Zi(e,t,n){let o=[],r=[];for(let s of e){let a=pr(s.function.name,s.function.arguments),l=na(s.function.name,at),i=Math.max(t.get(a)??0,t.get(l)??0);if(i>=on){let f=od(s);if(n.has(f)){n.delete(f),o.push(s);continue}n.add(f),r.push({call:s,failCount:i,error:`Tool "${s.function.name}" has failed ${i} times this turn for this target. The target likely does not exist. Stop trying variations of the same target and switch to a verified target or report the issue to the user. If you are certain this specific call is a DIFFERENT task (not another variation of what failed), re-issue exactly the same call once more and it will run.`})}else o.push(s)}return{allowed:o,blocked:r}}function od(e){return`${e.function.name}::${e.function.arguments}`}function Qi(){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 ea(e){if(e.ok){e.toolFailureCounts.delete(pr(e.toolName,e.toolArguments));return}let t=pr(e.toolName,e.toolArguments),n=e.toolFailureCounts.get(t)??0;e.toolFailureCounts.set(t,n+1)}function ta(e){let t=[];for(let[n,o]of e.toolFailureCounts)if(o>=on&&(e.snapshot.get(n)??0)<on){let{toolName:r,target:s}=ld(n);t.push({role:"user",content:`Tool "${r}" has now failed/returned empty results ${o} times for target "${s}". That target clearly does not exist or is not useful. Do NOT retry variations of the same target. If a further call in this family is genuinely a DIFFERENT task (not another variation), re-issue that exact call after it is blocked and it will run once. Otherwise report the result to the user immediately.`})}return t}function pr(e,t){return na(e,rd(e,t))}function rd(e,t){let n=ad(t);if(e==="read"||e==="write"||e==="edit"||e==="patch")return yn(n?.path??n?.file_path??n?.filePath);if(e==="search")return yn([n?.mode,n?.path,n?.fileGlob,n?.pattern].filter(Boolean).join("|"));if(e==="exec"){let o=typeof n?.command=="string"?n.command:void 0;return yn(o?St(o):void 0)}return id(n)}var sd=["runtime_id","runtimeId","operation","action","method","resource_type","resourceType"];function id(e){if(!e)return at;let t=sd.flatMap(o=>typeof e[o]=="string"&&e[o].trim()?[`${o}=${yn(e[o])}`]:[]),n=Array.isArray(e.args)?e.args.filter(o=>typeof o=="string").filter(o=>o.startsWith("-")).map(o=>o.toLowerCase()).join(","):"";return n&&t.push(`argv=${n}`),t.length>0?t.join("|"):at}function ad(e){if(e)try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function yn(e){return typeof e=="string"&&e.trim()?e.trim().replaceAll("\\","/").toLowerCase():at}function na(e,t){return`${e}::${t}`}function ld(e){let t=e.indexOf("::");return t<0?{toolName:e,target:at}:{toolName:e.slice(0,t),target:e.slice(t+2)||at}}var cd=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),ud=new Set(["cat","head","tail","less","more","wc","stat","file","sed","strings","jq","awk","cut","sort","uniq","tr"]),dd=new Set(["ls","tree","du","dir","gci","get-childitem"]),fd=new Set(["grep","rg","ag","ack","find"]);var pd=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function gd(e){let n=e.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!n)return null;let o=n.split(/\s+/),r=0;for(;r<o.length&&/^[A-Za-z_]\w*=/.test(o[r]);)r++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;r<o.length;){let f=o[r];if(s.test(f)){for(r++;r<o.length&&/^[-+]/.test(o[r]);)r++;r<o.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(o[r])&&r++;continue}break}if(r>=o.length)return null;let a=o[r],l=a.lastIndexOf("/");return(l>=0?a.slice(l+1):a).toLowerCase()}function md(e){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(e)}function oa(e){let t=gd(e),n=t!==null&&cd.has(t),o=t!==null&&ud.has(t),r=t!==null&&dd.has(t),s=t!==null&&pd.has(t),a=/(?:[^2]>|^>|\|>)/.test(e),l=md(e),i=(n||o||r)&&!a&&!l;return{firstCommand:t,isSearch:n,isRead:o,isList:r,isSilent:s,isConcurrencySafe:i,isReadOnly:i}}function ra(e){return e.isRead?!0:e.firstCommand!==null&&fd.has(e.firstCommand)}function sa(e){return e.isRead?"Command blocked: read local file contents with the read tool, not exec (cat/head/tail/sed/etc.). Reserve exec for system/build/test commands.":'Command blocked: search local file contents with the search tool (mode "content"), not exec (grep/find/rg/etc.). Reserve exec for system/build/test commands.'}var hd=/\.(?:pdf|docx?|xlsx?|pptx?|zip|tar|gz|7z|rar|exe|dll|so|dylib|wasm|class|png|jpe?g|gif|webp|bmp|mp[34]|mov|avi|mkv|wav|m4a|flac|ogg)\b(?:["'\s]|$)/i;function ia(e){return e!==null&&hd.test(e)}import{createHash as xh}from"node:crypto";import{mkdir as vh,readFile as wh,writeFile as Sh}from"fs/promises";import{join as Eh}from"path";import{tmpdir as Ph}from"os";import*as Md from"node:fs";import*as Pd from"node:path";import{resolve as Ed}from"node:path";import{join as wd}from"node:path";import{homedir as Td}from"node:os";import{join as oe}from"node:path";import{existsSync as Zm}from"node:fs";import{createHash as yd}from"node:crypto";import{resolve as bd}from"node:path";function gr(e){return yd("sha256").update(bd(e).toLowerCase()).digest("hex").slice(0,16)}var aa=".qlogicagent";function qe(){return process.env.QLOGICAGENT_HOME||oe(Td(),aa)}function bn(){let e=process.env.QLOGIC_LLMROUTER_USER_ID?.trim();if(e)return e;let t=process.env.QLOGIC_IMPLICIT_OWNER_ID?.trim();if(t)return t;let n=process.env.QLOGIC_DEVICE_ID?.trim();return n?`oc_${n}`:"oc_local"}function kd(e){let t=e.trim();if(!t)throw new Error("ownerUserId is required for profile-scoped storage");return encodeURIComponent(t).replace(/\./g,"%2E")}function Tn(e=bn()){return oe(qe(),"profiles",kd(e))}function la(e=bn()){return oe(Tn(e),"memory")}var Cd="projectData";function ca(){return oe(qe(),Cd)}function mr(e){if(!e)throw new Error("getProjectDataDirById: projectId is required");return oe(ca(),e)}function ua(){return oe(qe(),"plugins")}function da(){return oe(Tn(),"settings.json")}function fa(){return oe(qe(),"plugin-cache")}function pa(){return oe(qe(),"marketplace.json")}function lt(e){if(!e)throw new Error("getProjectAgentDir: cwd is required (must not fall back to process.cwd())");return oe(e,aa)}function ga(e){return oe(lt(e),"plugins")}function ma(e){return oe(lt(e),"settings.json")}function ha(e){return oe(lt(e),"INSTRUCTIONS.md")}function ya(e){return oe(lt(e),"rules")}import{resolve as oh}from"node:path";var Rd=()=>{},hr;function ba(){if(xd(),!hr)throw new Error("host project authority negotiated but snapshot is not hydrated");return{activeProjectId:hr.activeProjectId,projects:hr.projects.map(e=>({...e}))}}function xd(){let e=Rd();if(!e)throw new Error("gateway project authority is not available");return e}function _d(){let e=ba();return{activeProjectId:e.activeProjectId,projects:e.projects.map(t=>({...t}))}}function Ta(e){return _d().projects.find(t=>t.id===e)??null}function Sd(e){return Ta(e)?e:gr(e)}function Ad(e){return mr(Sd(e))}function ka(e){return wd(Ad(e),"sessions")}var yr=class{constructor(t={}){this.options=t}options;lastActiveWorkdir=null;getActiveProjectRoot(){return this.options.getActiveProjectRoot?.()??process.cwd()}setActiveWorkdir(t){let n=Ed(t);this.lastActiveWorkdir=n,this.options.setActiveWorkdir?.(n)}getActiveWorkdir(){return this.lastActiveWorkdir??this.getActiveProjectRoot()}resolveProjectDir(t){return this.options.resolveProjectDir?.(t)}resolveActiveOwnerUserId(){return bn()}getUserAgentHome(){return qe()}getOwnerProfileDir(t){return Tn(t)}getProfileMemoryDir(t){return la(t)}getUserSettingsPath(){return da()}getUserPluginsDir(){return ua()}getUserPluginCacheDir(){return fa()}getUserMarketplaceConfigPath(){return pa()}getProjectAgentDir(t=this.getActiveProjectRoot()){return lt(t)}getProjectSettingsPath(t=this.getActiveProjectRoot()){return ma(t)}getProjectInstructionsPath(t=this.getActiveProjectRoot()){return ha(t)}getProjectPluginsDir(t=this.getActiveProjectRoot()){return ga(t)}getProjectRulesDir(t=this.getActiveProjectRoot()){return ya(t)}getProjectSessionDataRoot(t=this.getActiveProjectRoot()){return ka(t)}},ph=new yr;function br(e,t){if(!e||t==="astraclaw__skill_read")return;Id(e);let n=[];for(let o of e.skillReadiness.values())for(let r of o.pendingSets){let s=r.readPaths.size;if(s>=r.minReads)continue;let a=r.resources.filter(l=>!r.readPaths.has(Od(l.path))).map(l=>`${l.path} (${l.label})`).join(", ");n.push(`${o.skillName}/${r.id}: read ${r.minReads-s} of [${a}]`)}if(n.length!==0)return`Required Host Skill resources have not been read. Call astraclaw__skill_read with the exact skill name and filePath before using ${t}: ${n.join("; ")}`}function Id(e){if(!(e.contextPolicies instanceof Map)||!(e.contextSizes instanceof Map)||!(e.skillReadiness instanceof Map))throw new Error("ContentReplacementState must be created by createContentReplacementState().")}function Od(e){return e.replace(/\\/gu,"/").replace(/^\.\//u,"").toLowerCase()}function $d(e,t){if(e.length!==1||!Do(e[0]?.function.name??"","stt"))return!1;let n=[...t].reverse().find(r=>r.role==="user");return n?Array.isArray(n.audioUrls)&&n.audioUrls.some(r=>typeof r=="string"&&r.trim()):!1}function Dd(e,t){let n=Bd(t);if(!n)return null;let o=jd(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]?`[transcription]
|
|
29
|
+
`).replace(/\\/g,"/").toLowerCase()}function hn(e){try{if(e.endsWith("/*")){let n=e.slice(0,-2);return Di(n,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return At(`${n}/${r.name}`).size>0}catch{return!1}})}let t=At(e);return t.isFile()&&t.size>0}catch{return!1}}function Eu(e,t){let n=H(t);if(!n.endsWith("/*"))return e.includes(n);let o=n.slice(0,-1);return e.includes(o)}function Ui(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,i=a.function;typeof l=="string"&&i?.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)&&Ue(o))return!0}return!1}function Mu(e){let t=Hi(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 Pu(e){let t=Bi(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function Iu(e){if(e.length===0)return"";let t=e.map(o=>Pu(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 Ou(e,t){let n=H(e);return t.some(o=>{let r=H(o);return r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r})}function lr(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,i=l.id,f=l.function;if(typeof i!="string"||f?.name!=="write"&&f?.name!=="edit"||typeof f.arguments!="string")continue;let m=He(f.arguments);if(!m)continue;let y=Mt(m);y&&n.set(i,y)}}for(let o of e){let r=o;if(!Ue(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 Nu(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 Lu(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function Fu(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,i=l.id,f=l.function;if(typeof i!="string"||f?.name!=="write"&&f?.name!=="edit"||typeof f.arguments!="string")continue;let m=He(f.arguments);if(!m)continue;let y=Mt(m)??"",T=Gi(m);(/\bartifact[-_\s]?index\b/i.test(y)||/\bartifact[-_\s]?index\b/i.test(T))&&n.set(i,T)}}for(let o of e){let r=o;if(!Ue(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 $u(e){let t=Hi(e.inputMessages);if(!Nu(t))return[];let n=Fu(we(e.inputMessages,e.messages)).at(-1);if(!n)return[];let o=[],r=Lu(t).filter(a=>!new RegExp(`\\b${qi(a)}\\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=n.split(/\r?\n/u).filter(a=>/\bno\s+[^|\n]*(?:found|evidence|files?)\b/i.test(a)&&!/\b(?:not\s+verified|unverified|unknown|not\s+checked|search\s+scope|checked\s+path)\b/i.test(a));return s.length>0&&o.push({type:"unsupported_absence",detail:`Absence claims need scoped evidence or must be marked unverified: ${s.slice(0,3).join(" ; ")}`}),o}function Du(e){let t=[],n=o=>{let r;try{r=Di(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{At(a).size>0&&t.push(a)}catch{}}};try{if(!At(e).isDirectory())return[]}catch{return[]}return n(e),t}function we(e,t){if(t.length<e.length)return t;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return t;return t.slice(e.length)}function Bu(e,t){if(!Mu(e))return[];let n=mn(e),o=n.filter(a=>!H(a).endsWith("/*"));if(o.length<2)return[];let r=Iu(o);if(!r||r.split("/").length<3)return[];let s=H(r);return[...new Set([...lr(we(e,t)),...Du(r)])].filter(a=>H(a).startsWith(`${s}/`)&&!Ou(a,n)&&hn(a))}function zi(e,t){let n=mn(e);if(n.length===0)return[];let o=Su(e),r=we(e,t),s=ar(r),a=ju(r),l=Uu(r);return n.filter(i=>{if(o.has(H(i))||Eu(s,i))return!1;let f=H(i);return!((a.has(f)||l.has(f))&&hn(i))})}function ju(e){let t=new Set;for(let o of e){let r=o;Ue(r)&&typeof r.tool_call_id=="string"&&t.add(r.tool_call_id)}let n=new Set;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,i=l.function;if(i?.name!=="read"||typeof l.id!="string"||typeof i.arguments!="string"||!t.has(l.id))continue;let f=He(i.arguments),m=f?Mt(f):void 0;m&&n.add(H(m))}}return n}function Uu(e){let t=new Set;for(let o of e){let r=o;Ue(r)&&typeof r.tool_call_id=="string"&&t.add(r.tool_call_id)}let n=new Set;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,i=l.function,f=typeof i?.name=="string"?Ce(i.name):"";if(f!=="image_understand"&&f!=="video_understand"||typeof l.id!="string"||typeof i?.arguments!="string"||!t.has(l.id))continue;let m=He(i.arguments);if(!m)continue;let y=f==="image_understand"?m.image_url:m.video_url;typeof y=="string"&&y.trim()&&n.add(H(y))}}return n}function fn(e){return cr(e).fail}function zu(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function pn(e){if(!e)return!1;let t=zu(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function cr(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))pn(s[2])&&(n=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))pn(s[1])&&(o=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))pn(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))pn(s[1])&&(o=`${t(s[1])} FAIL`)}return{done:n,fail:o}}function Hi(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 qi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ze(e){let t=zi(e.inputMessages,e.messages).filter(n=>!hn(n));if(t.length!==0)return`[Engine notice] ${e.reason}; explicitly requested output files still missing: ${t.join(", ")}.`}function He(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Mt(e){for(let t of["path","filePath","file_path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n}}function Gi(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function Wi(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let n=cr(e.inputMessages);if(!n.done)return;let o=He(e.toolCall.function.arguments);if(!o)return;let r=Mt(o),s=Gi(o);if(!r||!s.includes(n.done))return;let a=mn(e.inputMessages);if(a.length<2)return;let l=H(r);if(!a.some(y=>H(y)===l))return;let f=ar(e.messages),m=a.filter(y=>H(y)!==l).filter(y=>!f.includes(H(y)));if(m.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: ${m.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function Be(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function je(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function Vi(e){try{return At(e).isFile()}catch{return!1}}function Hu(e,t,n){let o=/[,.,。;;!?!?\n]/u,r=t;for(;r>0&&!o.test(e[r-1]);)r--;let s=t+n;for(;s<e.length&&!o.test(e[s]);)s++;if(ir.test(e.slice(r,s)))return!0;let a=s<e.length?s+1:s,l=a;for(;l<e.length&&!o.test(e[l]);)l++;let i=e.slice(a,l);return ir.test(i)&&/(?:这个|该|此)文件|\b(?:this|that|the)\s+file\b/i.test(i)}function qu(e,t){let n=new Map;for(let a of e){if(a.role!=="user"||typeof a.content!="string")continue;let l=gn(a.content);if(ir.test(l))for(let i of l.matchAll(Et)){if(!Hu(l,i.index??0,i[0].length))continue;let f=i[0].replace(/[),.;:,。;]+$/u,""),m=H(f);m&&n.set(m,f)}}if(n.size===0)return[];let o=ar(we(e,t)),r=Ui(we(e,t)),s=[];for(let[a,l]of n)(o.includes(a)||r&&Vi(l))&&s.push(a);return s}var Gu="File not found:",$i=/\b(?:create|write|make|generate|produce|save|output|deliver|initialize|init|ensure|touch|scaffold|build|set\s+up)\b|生成|创建|写入|写出|新建|建立|保存|输出|交付|初始化|确保/i,Wu=/\b(?:if|when|unless)\b[^.。;;\n]{0,40}(?:missing|not\s+exist|does\s*n['o]?t\s+exist|absent|no\s+such)|(?:如果|若|要是|倘若)[^.。;;\n]{0,24}(?:不存在|没有|缺失|不在|未创建)/i;function Vu(e,t){let n=t.slice(t.lastIndexOf("/")+1),o=/[.。;;!?!?\n]/u;for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase(),l=s.includes(t)||n.length<=3||n===t?[t]:[n];for(let i of l){let f=0;for(;;){let m=s.indexOf(i,f);if(m===-1)break;f=m+1;let y=m;for(;y>0&&!o.test(s[y-1]);)y--;let T=m+i.length;for(;T<s.length&&!o.test(s[T]);)T++;let v=r.content.slice(y,T);if($i.test(v))return!0}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase(),l=Array.from(r.content.matchAll(Et)).map(f=>H(f[0])).some(f=>f!==t),i=s.includes(t)||!l&&n.length>3&&n!==t&&s.includes(n);if(!l&&i&&$i.test(r.content)&&Wu.test(r.content))return!0}return!1}function Xu(e){let t=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,i=l.id,f=l.function;if(typeof i!="string"||f?.name!=="read"||typeof f.arguments!="string")continue;let m=He(f.arguments),y=m?Mt(m):void 0;y&&t.set(i,y)}}let n=new Map;for(let o of e){let r=o;if(r.role!=="tool")continue;let s=r.tool_call_id;if(typeof s!="string")continue;let a=t.get(s);if(!a)continue;let l=typeof r.content=="string"?r.content:"";(r.is_error===!0||l.startsWith("Error:"))&&l.includes(Gu)&&n.set(H(a),a)}return n}function Ku(e,t){let n=we(e,t),o=Xu(n);if(o.size===0)return[];let r=new Set(lr(n).map(H)),s=[];for(let[a,l]of o)Vu(e,a)||(r.has(a)||Vi(l))&&s.push(a);return s}function ur(e){let t=[...e.inputMessages].reverse().find(v=>v.role==="user"),n=typeof t?.content=="string"?t.content:"",o=bu.test(n)||Tu.test(n)&&mn(e.inputMessages).length>0,r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit")||ji(we(e.inputMessages,e.messages)).length>0,s=cr(e.inputMessages),a=s.fail!==void 0&&e.finalText.includes(s.fail)||/\bFAILED\b/.test(e.finalText),l=qu(e.inputMessages,e.messages);if(l.length>0&&!a){e.log.info(`forbidden-file-creation guard: agent wrote ${l.length} file(s) the user forbade creating`);let v=fn(e.inputMessages),S={role:"user",content:`You created a file the request explicitly forbade creating: ${l.join(", ")}. That is a constraint violation, not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${v??"FAILED"} with the real reason: the task could not be done without violating the stated constraint. Do not fabricate a successful outcome.`};return je("forbidden_file_creation",e.messages,Be(e.finalText,e.thinkingBlocks),S)}let i=Ku(e.inputMessages,e.messages);if(i.length>0&&!a){e.log.info(`self-created-read-target guard: agent created ${i.length} file(s) it had read as not-found`);let v=fn(e.inputMessages),S={role:"user",content:"You were asked to read "+i.join(", ")+`, but your read showed the file did not exist; you then created it yourself. Manufacturing an input you were told to read is not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${v??"FAILED"} with the real reason: the file does not exist and the task cannot be done without fabricating it.`};return je("self_created_read_target",e.messages,Be(e.finalText,e.thinkingBlocks),S)}let f=Ui(e.messages),m=zi(e.inputMessages,e.messages).filter(v=>!(f&&hn(v)));if(m.length>0&&e.totalToolCallCount>0){if(a)return null;e.log.info(`explicit required file verification: ${m.length} file(s) missing`);let v=fn(e.inputMessages),S={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 ${v??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return je("explicit_required_file_verification",e.messages,Be(e.finalText,e.thinkingBlocks),S)}let y=Bu(e.inputMessages,e.messages);if(y.length>0&&e.totalToolCallCount>0){if(a)return null;e.log.info(`explicit extra file verification: ${y.length} unexpected file(s)`);let v=fn(e.inputMessages),S={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${y.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${v??"FAILED"} and the real reason. Do not claim completion while extra deliverables remain.`};return je("explicit_extra_file_verification",e.messages,Be(e.finalText,e.thinkingBlocks),S)}let T=$u({inputMessages:e.inputMessages,messages:e.messages});if(T.length>0&&e.totalToolCallCount>0){if(a)return null;e.log.info(`artifact index evidence verification: ${T.length} issue(s)`);let v={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+T.map(S=>S.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 je("artifact_index_evidence_verification",e.messages,Be(e.finalText,e.thinkingBlocks),v)}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");let v={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 je("file_action_verification",e.messages,Be(e.finalText,e.thinkingBlocks),v)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")){let v=[...new Set(lr(we(e.inputMessages,e.messages)).map(H))].filter(S=>Yu.test(S)&&!Ju(S));if(v.length>=3){e.log.info(`AP3 verification nudge: ${v.length} code files created, injecting completeness check`);let S={role:"user",content:"You created multiple code 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. Fix anything that fails these checks. Either way, your FINAL message must answer the user's actual request \u2014 do not end on this checklist confirmation."};return je("multi_file_skeleton_verification",e.messages,Be(e.finalText,e.thinkingBlocks),S)}}return null}var Yu=/\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|kts|cs|cpp|cc|c|h|hpp|vue|svelte)$/i;function Ju(e){let t=H(yu());return t.length>0&&e.startsWith(`${t}/`)}function Zu(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function Xi(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,Zu(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var dr="```final-status",Qu=/\r?\n[ \t]*```/;function ed(e,t){let n=Math.min(e.length,t.length-1);for(let o=n;o>0;o--)if(e.endsWith(t.slice(0,o)))return o;return 0}function Ki(){let e="",t=!1;function n(){let o="";for(;;){if(t){let s=Qu.exec(e);if(!s)return o;e=e.slice(s.index+s[0].length),t=!1;continue}let r=e.indexOf(dr);if(r===-1){let s=ed(e,dr);return o+=e.slice(0,e.length-s),e=e.slice(e.length-s),o}o+=e.slice(0,r),e=e.slice(r+dr.length),t=!0}}return{push(o){return o?(e+=o,n()):""},flush(){if(t)return e="","";let o=e;return e="",o},isSuppressing:()=>t}}var Yi=5;function td(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function nd(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function fr(e,t){let n=e.recoveryTrace;if(!n)return;let o=`budget_continuation_stop:${t}`;n.set(o,(n.get(o)??0)+1)}function Ji(e){if(!e.tokenBudget||e.tokenBudget<=0)return null;let t=td(e.totalUsage),n=t/e.tokenBudget*100;if(e.budgetContinuationCount>=Yi)return e.log.info(`token budget continuation stop: continuation cap reached (${e.budgetContinuationCount}/${Yi}) at ${Math.round(n)}% used`),fr(e,"cap"),null;let o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=Bs&&o<Eo&&e.lastBudgetDeltaTokens<Eo)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(n)}% (delta=${o})`),fr(e,"diminishing_returns"),null;if(n>=90)return e.log.info(`token budget continuation stop: ${Math.round(n)}% of ${e.tokenBudget} tokens used (>=90% headroom floor), not nudging further work`),fr(e,"headroom_floor"),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,nd(e.finalText,e.thinkingBlocks),a],budgetContinuationCount:s,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}var at="*";function Zi(e,t,n){let o=[],r=[];for(let s of e){let a=pr(s.function.name,s.function.arguments),l=na(s.function.name,at),i=Math.max(t.get(a)??0,t.get(l)??0);if(i>=on){let f=od(s);if(n.has(f)){n.delete(f),o.push(s);continue}n.add(f),r.push({call:s,failCount:i,error:`Tool "${s.function.name}" has failed ${i} times this turn for this target. The target likely does not exist. Stop trying variations of the same target and switch to a verified target or report the issue to the user. If you are certain this specific call is a DIFFERENT task (not another variation of what failed), re-issue exactly the same call once more and it will run.`})}else o.push(s)}return{allowed:o,blocked:r}}function od(e){return`${e.function.name}::${e.function.arguments}`}function Qi(){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 ea(e){if(e.ok){e.toolFailureCounts.delete(pr(e.toolName,e.toolArguments));return}let t=pr(e.toolName,e.toolArguments),n=e.toolFailureCounts.get(t)??0;e.toolFailureCounts.set(t,n+1)}function ta(e){let t=[];for(let[n,o]of e.toolFailureCounts)if(o>=on&&(e.snapshot.get(n)??0)<on){let{toolName:r,target:s}=ld(n);t.push({role:"user",content:`Tool "${r}" has now failed/returned empty results ${o} times for target "${s}". That target clearly does not exist or is not useful. Do NOT retry variations of the same target. If a further call in this family is genuinely a DIFFERENT task (not another variation), re-issue that exact call after it is blocked and it will run once. Otherwise report the result to the user immediately.`})}return t}function pr(e,t){return na(e,rd(e,t))}function rd(e,t){let n=ad(t);if(e==="read"||e==="write"||e==="edit"||e==="patch")return yn(n?.path??n?.file_path??n?.filePath);if(e==="search")return yn([n?.mode,n?.path,n?.fileGlob,n?.pattern].filter(Boolean).join("|"));if(e==="exec"){let o=typeof n?.command=="string"?n.command:void 0;return yn(o?St(o):void 0)}return id(n)}var sd=["runtime_id","runtimeId","operation","action","method","resource_type","resourceType"];function id(e){if(!e)return at;let t=sd.flatMap(o=>typeof e[o]=="string"&&e[o].trim()?[`${o}=${yn(e[o])}`]:[]),n=Array.isArray(e.args)?e.args.filter(o=>typeof o=="string").filter(o=>o.startsWith("-")).map(o=>o.toLowerCase()).join(","):"";return n&&t.push(`argv=${n}`),t.length>0?t.join("|"):at}function ad(e){if(e)try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function yn(e){return typeof e=="string"&&e.trim()?e.trim().replaceAll("\\","/").toLowerCase():at}function na(e,t){return`${e}::${t}`}function ld(e){let t=e.indexOf("::");return t<0?{toolName:e,target:at}:{toolName:e.slice(0,t),target:e.slice(t+2)||at}}var cd=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),ud=new Set(["cat","head","tail","less","more","wc","stat","file","sed","strings","jq","awk","cut","sort","uniq","tr"]),dd=new Set(["ls","tree","du","dir","gci","get-childitem"]),fd=new Set(["grep","rg","ag","ack","find"]);var pd=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function gd(e){let n=e.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!n)return null;let o=n.split(/\s+/),r=0;for(;r<o.length&&/^[A-Za-z_]\w*=/.test(o[r]);)r++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;r<o.length;){let f=o[r];if(s.test(f)){for(r++;r<o.length&&/^[-+]/.test(o[r]);)r++;r<o.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(o[r])&&r++;continue}break}if(r>=o.length)return null;let a=o[r],l=a.lastIndexOf("/");return(l>=0?a.slice(l+1):a).toLowerCase()}function md(e){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(e)}function oa(e){let t=gd(e),n=t!==null&&cd.has(t),o=t!==null&&ud.has(t),r=t!==null&&dd.has(t),s=t!==null&&pd.has(t),a=/(?:[^2]>|^>|\|>)/.test(e),l=md(e),i=(n||o||r)&&!a&&!l;return{firstCommand:t,isSearch:n,isRead:o,isList:r,isSilent:s,isConcurrencySafe:i,isReadOnly:i}}function ra(e){return e.isRead?!0:e.firstCommand!==null&&fd.has(e.firstCommand)}function sa(e){return e.isRead?"Command blocked: read local file contents with the read tool, not exec (cat/head/tail/sed/etc.). Reserve exec for system/build/test commands.":'Command blocked: search local file contents with the search tool (mode "content"), not exec (grep/find/rg/etc.). Reserve exec for system/build/test commands.'}var hd=/\.(?:pdf|docx?|xlsx?|pptx?|zip|tar|gz|7z|rar|exe|dll|so|dylib|wasm|class|png|jpe?g|gif|webp|bmp|mp[34]|mov|avi|mkv|wav|m4a|flac|ogg)\b(?:["'\s]|$)/i;function ia(e){return e!==null&&hd.test(e)}import{createHash as xh}from"node:crypto";import{mkdir as vh,readFile as wh,writeFile as Sh}from"fs/promises";import{join as Eh}from"path";import{tmpdir as Ph}from"os";import*as Md from"node:fs";import*as Pd from"node:path";import{resolve as Ed}from"node:path";import{join as wd}from"node:path";import{homedir as Td}from"node:os";import{join as oe}from"node:path";import{existsSync as Zm}from"node:fs";import{createHash as yd}from"node:crypto";import{resolve as bd}from"node:path";function gr(e){return yd("sha256").update(bd(e).toLowerCase()).digest("hex").slice(0,16)}var aa=".qlogicagent";function qe(){return process.env.QLOGICAGENT_HOME||oe(Td(),aa)}function bn(){let e=process.env.QLOGIC_LLMROUTER_USER_ID?.trim();if(e)return e;let t=process.env.QLOGIC_IMPLICIT_OWNER_ID?.trim();if(t)return t;let n=process.env.QLOGIC_DEVICE_ID?.trim();return n?`oc_${n}`:"oc_local"}function kd(e){let t=e.trim();if(!t)throw new Error("ownerUserId is required for profile-scoped storage");return encodeURIComponent(t).replace(/\./g,"%2E")}function Tn(e=bn()){return oe(qe(),"profiles",kd(e))}function la(e=bn()){return oe(Tn(e),"memory")}var Cd="projectData";function ca(){return oe(qe(),Cd)}function mr(e){if(!e)throw new Error("getProjectDataDirById: projectId is required");return oe(ca(),e)}function ua(){return oe(qe(),"plugins")}function da(){return oe(Tn(),"settings.json")}function fa(){return oe(qe(),"plugin-cache")}function pa(){return oe(qe(),"marketplace.json")}function lt(e){if(!e)throw new Error("getProjectAgentDir: cwd is required (must not fall back to process.cwd())");return oe(e,aa)}function ga(e){return oe(lt(e),"plugins")}function ma(e){return oe(lt(e),"settings.json")}function ha(e){return oe(lt(e),"INSTRUCTIONS.md")}function ya(e){return oe(lt(e),"rules")}import{resolve as oh}from"node:path";var Rd=()=>{},hr;function ba(){if(xd(),!hr)throw new Error("host project authority negotiated but snapshot is not hydrated");return{activeProjectId:hr.activeProjectId,projects:hr.projects.map(e=>({...e}))}}function xd(){let e=Rd();if(!e)throw new Error("gateway project authority is not available");return e}function _d(){let e=ba();return{activeProjectId:e.activeProjectId,projects:e.projects.map(t=>({...t}))}}function Ta(e){return _d().projects.find(t=>t.id===e)??null}function Sd(e){return Ta(e)?e:gr(e)}function Ad(e){return mr(Sd(e))}function ka(e){return wd(Ad(e),"sessions")}var yr=class{constructor(t={}){this.options=t}options;lastActiveWorkdir=null;getActiveProjectRoot(){return this.options.getActiveProjectRoot?.()??process.cwd()}setActiveWorkdir(t){let n=Ed(t);this.lastActiveWorkdir=n,this.options.setActiveWorkdir?.(n)}getActiveWorkdir(){return this.lastActiveWorkdir??this.getActiveProjectRoot()}resolveProjectDir(t){return this.options.resolveProjectDir?.(t)}resolveActiveOwnerUserId(){return bn()}getUserAgentHome(){return qe()}getOwnerProfileDir(t){return Tn(t)}getProfileMemoryDir(t){return la(t)}getUserSettingsPath(){return da()}getUserPluginsDir(){return ua()}getUserPluginCacheDir(){return fa()}getUserMarketplaceConfigPath(){return pa()}getProjectAgentDir(t=this.getActiveProjectRoot()){return lt(t)}getProjectSettingsPath(t=this.getActiveProjectRoot()){return ma(t)}getProjectInstructionsPath(t=this.getActiveProjectRoot()){return ha(t)}getProjectPluginsDir(t=this.getActiveProjectRoot()){return ga(t)}getProjectRulesDir(t=this.getActiveProjectRoot()){return ya(t)}getProjectSessionDataRoot(t=this.getActiveProjectRoot()){return ka(t)}},ph=new yr;function br(e,t){if(!e||t==="astraclaw__skill_read")return;Id(e);let n=[];for(let o of e.skillReadiness.values())for(let r of o.pendingSets){let s=r.readPaths.size;if(s>=r.minReads)continue;let a=r.resources.filter(l=>!r.readPaths.has(Od(l.path))).map(l=>`${l.path} (${l.label})`).join(", ");n.push(`${o.skillName}/${r.id}: read ${r.minReads-s} of [${a}]`)}if(n.length!==0)return`Required Host Skill resources have not been read. Call astraclaw__skill_read with the exact skill name and filePath before using ${t}: ${n.join("; ")}`}function Id(e){if(!(e.contextPolicies instanceof Map)||!(e.contextSizes instanceof Map)||!(e.loadedSkillNames instanceof Set)||!(e.skillReadiness instanceof Map))throw new Error("ContentReplacementState must be created by createContentReplacementState().")}function Od(e){return e.replace(/\\/gu,"/").replace(/^\.\//u,"").toLowerCase()}function $d(e,t){if(e.length!==1||!Do(e[0]?.function.name??"","stt"))return!1;let n=[...t].reverse().find(r=>r.role==="user");return n?Array.isArray(n.audioUrls)&&n.audioUrls.some(r=>typeof r=="string"&&r.trim()):!1}function Dd(e,t){let n=Bd(t);if(!n)return null;let o=jd(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]?`[transcription]
|
|
30
30
|
AUDIO_STT_RESULT ${a[1]} ${o}`:`[transcription]
|
|
31
31
|
${o}`}function Bd(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 jd(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}function x(e){return[...new Set(e.map(t=>t.function.name))].sort()}function xn(e){return[...e].sort((t,n)=>t.function.name.localeCompare(n.function.name))}function kn(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 Ud(e,t,n,o,r){let s=r.filter(a=>a.name===e).sort((a,l)=>Ca(a.reason)-Ca(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 Ca(e){return e==="invalid-arguments"?0:e==="blocked-by-policy"||e.startsWith("policy-suppressed:")?1:e==="confirmation-timeout"?2:e==="dedicated-tool-required"?3:e==="read-only-context-pack"?4:e==="not-offered"?5:e==="read-cycle-policy"?6:e==="identical-repeat-policy"?7:e==="variant-failure-policy"?8:10}function zd(e){let t=typeof e.blockReason=="string"?e.blockReason:void 0;if(e.blocked&&/confirmation timed out/i.test(t??""))return"confirmation-timeout";if(e.blocked)return"blocked-by-policy";let n=typeof e.details?.error=="string"?e.details.error:void 0;if(n==="dedicated_tool_required")return"dedicated-tool-required";if(n==="existing_file_update_tool_required")return"existing-file-update-tool-required";if(n==="invalid_arguments")return"invalid-arguments";if(n==="blocked_global_process_kill")return"global-process-kill-blocked";if(n==="blocked_by_guard")return"blocked-by-policy";if(n==="semantic_quality_failed")return"semantic-quality-failed"}function Hd(e,t){let n=e.failedCallIds.length+e.blockedCallIds.length;return t==="zh"?n>0?`\u26A0\uFE0F \u65E0\u6CD5\u63D0\u4F9B\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7B54\u6848\uFF1A\u672C\u8F6E\u8981\u6C42\u4F7F\u7528\u6700\u65B0\u5DE5\u5177\u8BC1\u636E\uFF0C\u4F46 ${n} \u6B21\u5B9E\u9645\u8C03\u7528\u5747\u5931\u8D25\u6216\u88AB\u963B\u6B62\u3002\u4E3A\u907F\u514D\u8F93\u51FA\u672A\u7ECF\u9A8C\u8BC1\u7684\u4E8B\u5B9E\uFF0C\u672C\u8F6E\u5DF2\u505C\u6B62\u4F5C\u7B54\u3002`:"\u26A0\uFE0F \u65E0\u6CD5\u63D0\u4F9B\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7B54\u6848\uFF1A\u672C\u8F6E\u8981\u6C42\u4F7F\u7528\u6700\u65B0\u5DE5\u5177\u8BC1\u636E\uFF0C\u4F46\u6CA1\u6709\u6210\u529F\u5B8C\u6210\u4EFB\u4F55\u5DE5\u5177\u8C03\u7528\u3002\u4E3A\u907F\u514D\u8F93\u51FA\u672A\u7ECF\u9A8C\u8BC1\u7684\u4E8B\u5B9E\uFF0C\u672C\u8F6E\u5DF2\u505C\u6B62\u4F5C\u7B54\u3002":n>0?`\u26A0\uFE0F I could not produce a verified answer: this turn required fresh tool evidence, but all ${n} attempted calls failed or were blocked. I stopped instead of returning unverified facts.`:"\u26A0\uFE0F I could not produce a verified answer: this turn required fresh tool evidence, but no tool call completed successfully. I stopped instead of returning unverified facts."}function Ra(e){let t=new Set(e.map(n=>n.function.name));return t.has("read")||t.has("search")||t.has("write")||t.has("edit")||t.has("patch")}function fe(e,t){return t.size===0?[...e]:e.filter(n=>!t.has(n.function.name))}var qd=new Set(["edit","patch","read"]);function xa(e,t){let n=e.filter(o=>qd.has(o.function.name)&&!t.has(o.function.name));return n.length>0?xn(n):e.filter(o=>o.function.name!=="write"&&!t.has(o.function.name))}function Cn(e,t){let n=new Set(t);return e.filter(o=>!n.has(o))}function Gd(e){if(!e)return;let t=e.trim();return(t.match(/Last error:\s*(.+?)\.\s*Do not retry\./s)?.[1]?.trim()??t).slice(0,600).trim()||void 0}function _a(e){let n=Te(e)?.command;return typeof n=="string"&&n.trim()?n:void 0}var vn=5174;function va(e,t){let n=String(t);return[new RegExp(`(?:^|\\s)--port(?:=|\\s+)${n}(?:\\s|$)`),new RegExp(`(?:^|\\s)-p(?:=|\\s+)${n}(?:\\s|$)`),new RegExp(`(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|\\[?::1\\]?):${n}\\b`,"i")].some(r=>r.test(e))}function Wd(e){return/\b(vite|npx\s+vite|pnpm\s+(?:run\s+)?dev|npm\s+(?:run\s+)?dev|yarn\s+(?:run\s+)?dev)\b/i.test(e)}function za(e){return/(?:^|\s)--strictPort(?:\s|$)/.test(e)}function Vd(e){if(za(e))return e;let t=/\s+(?:\d?>&\d|\d?>\s*\S+|>\s*\S+|<\s*\S+).*$/.exec(e);return!t||t.index===void 0?`${e.trim()} --strictPort`:`${e.slice(0,t.index).trim()} --strictPort${e.slice(t.index)}`}function wa(e,t){let n=Te(e)??{};return JSON.stringify({...n,command:t})}function Xd(e){let t=e.replace(/^(?:\s*sleep\s+\d+(?:\.\d+)?\s*(?:&&|;)\s*)+/i,"").trim();return t&&t!==e.trim()?t:null}function Kd(e){return va(e,vn)?{action:"block",error:"Command blocked: port 5174 is reserved for the Xiaozhi Claw frontend. Start generated apps on an explicit non-5174 port and include --strictPort when using Vite."}:Wd(e)&&va(e,vn-1)&&!za(e)?{action:"rewrite",command:Vd(e)}:null}function Yd(e){let t=e.buildFailureEvidence[0];return"The test/build you ran is still FAILING, so the task is not complete. "+(t?`Last failing output:
|
|
32
32
|
${t.slice(0,600)}
|
|
@@ -53,7 +53,7 @@ ${N}`:N:X},mt=0,Bt=0;function*il(g){mt<=Bt||(yield{type:"text_rollback",turnId:r
|
|
|
53
53
|
${C}`:C);return}let ul=he.length===0&&et.length>0?et.join(""):void 0;Bt=mt,S(g,go(Z,J||void 0,he.length>0?he:void 0,ul)),ce=vo(ce,{replayMessages:g,pendingToolCallIds:Z.map(c=>c.id),completedToolCallIds:ce.completedToolCallIds,lastStopReason:"tool_calls"});let Yn=u.identicalCallCounts,Ht=u.identicalFailureCounts,yt=[],ke=[],bt=[],as=!1;for(let c of Z){if(Fa(c,u)){yt.push(c);continue}let d=`${c.function.name}::${c.function.arguments}`,h=Yn.get(d)??0;Yn.set(d,h+1);let C=Ht.get(d)??0;Ht.set(d,C+1);let p=kr.has(c.function.name)||c.function.name==="exec"?u.identicalSuccessfulToolResults.get(d):void 0;C+1>Ao?(ke.push(c),as||(as=!0,o.info(`AP4 blocked: ${c.function.name} failed ${C+1}x with identical arguments`))):h+1>Ao&&p?bt.push({call:c,result:p,repeatCount:h+1}):yt.push(c)}let ee=[],dl=new Set(k.map(c=>c.function.name)),ls=new Set(ke.filter(c=>jf(c,dl)).map(c=>c.id));for(let c of bt){let d=c.call;Ht.delete(`${d.function.name}::${d.function.arguments}`);let h=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${c.repeatCount}); no additional tool execution was performed.
|
|
54
54
|
|
|
55
55
|
${c.result.content}`,C=te(d.id,{ok:!0,payload:h,imageUrls:c.result.imageUrls,toolReferences:c.result.toolReferences});S(g,C),ee.push(d.id),G.add(d.function.name),q++,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:c.repeatCount}}}if(bt.some(c=>c.call.function.name==="exec"&&Aa(c.call.function.arguments))){let c=x(k);g.push({role:"user",content:Zd()}),yield{type:"tool_selection_policy",turnId:r,policyId:"ui_acceptance_after_preparation_guidance",intent:"verification",reason:"repeated-browser-preparation-command",availableToolNames:x(l??i),enabledToolNamesBefore:c,enabledToolNamesAfter:c,suppressedToolNames:[],nextAction:"reuse-or-collect-reliable-ui-evidence"},yield O("ui_acceptance_after_preparation_guidance","reused successful browser preparation command")}for(let c of ke){E.push({name:c.function.name,reason:"identical-repeat-policy"});let d=Ht.get(`${c.function.name}::${c.function.arguments}`),h=ln(g,c.function.name,c.function.arguments),C=Gd(h),p=ls.has(c.id)?Uf(d,c):C?`This exact tool call has been attempted ${d} times. Last error: ${C}. 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.`,b=te(c.id,{ok:!1,error:p});S(g,b),ee.push(c.id),G.add(c.function.name),q++,yield{type:"tool_result",turnId:r,callId:c.id,name:c.function.name,ok:!1,error:p}}if(ke.length>0&&yt.length===0&&bt.length===0&&ke.every(c=>ls.has(c.id))&&u.existingFileUpdateRecoveryCount<2){let c=x(k);k=xa(M,j);let d=x(k);gt=!0,W=!0;let h=[...new Set(ke.map(C=>Sn(C.function.arguments)).filter(C=>!!C))];g.push({role:"user",content:`Existing-file maintenance recovery: the same write call was repeatedly attempted for an existing file. Do not use write for these existing path(s): ${h.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"repeated-existing-file-write",availableToolNames:x(l??i),enabledToolNamesBefore:c,enabledToolNamesAfter:d,suppressedToolNames:Cn(c,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield O("existing_file_update_recovery",h.join(",")||"unknown"),u={...u,messages:g,existingFileUpdateRecoveryCount:u.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}if(ke.length>0){let c=ke[0],d=ln(g,c.function.name,c.function.arguments),h={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(d?`The error was: "${d}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};g.push(h)}let fl=Fr>=3&&u.repeatedToolFailureRecoveryCount<1;if(ke.length>0&&yt.length===0&&bt.length===0&&!fl){let c=Ea(Qo(g,1),{availableToolNames:x(l??i),enabledToolNames:Fn(),toolCallNames:[...G].sort(),blockedToolCalls:kn(E)});yield*ne(c);return}let cs=[],Jn=[];for(let c of yt){let d=li({toolName:c.function.name,rawArguments:c.function.arguments});d?Jn.push({call:c,...d}):cs.push(c)}for(let c of Jn){let d=c.call;E.push({name:d.function.name,reason:"read-only-context-pack"}),S(g,te(d.id,{ok:!1,error:c.error})),ee.push(d.id),G.add(d.function.name),q++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:c.error},o.warn(`read-only context-pack blocked: ${d.function.name} ${c.path}`)}Jn.length>0&&g.push({role:"user",content:"A write was blocked because context-pack is read-only evidence. Continue by writing compact indexes, checkpoints, and maintenance updates under benchmark-state; do not retry writes into context-pack."});let pl=new Set(k.map(c=>c.function.name)),Zn=[],qt=[];for(let c of cs){let d=Xa(c.function.name,c.function.arguments,pl);if(d){let h=`${c.function.name}::${c.function.arguments}`;if(In.has(h)){In.delete(h),o.info(`existing-file-update guard: verbatim re-issue admitted once for ${d.path}`),Zn.push(c);continue}In.add(h),qt.push({call:c,...d})}else Zn.push(c)}for(let c of qt){let d=c.call;E.push({name:d.function.name,reason:"existing-file-update-tool-required"}),S(g,te(d.id,{ok:!1,error:c.error})),ee.push(d.id),G.add(d.function.name),q++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:c.error},o.info(`existing file update blocked: ${d.function.name} ${c.path}`)}if(qt.length>0){let c=x(k);k=xa(M,j);let d=x(k);gt=!0,W=!0;let h=[...new Set(qt.map(C=>C.path))];g.push({role:"user",content:`Existing-file maintenance recovery: a write was blocked because the target file already exists and edit/patch are enabled. Do not use write for these existing path(s): ${h.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"existing-file-write-blocked",availableToolNames:x(l??i),enabledToolNamesBefore:c,enabledToolNamesAfter:d,suppressedToolNames:Cn(c,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield O("existing_file_update_recovery",h.join(",")||"unknown"),u={...u,messages:g,existingFileUpdateRecoveryCount:u.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}let us=[],Qn=[];for(let c of Zn){let d=ai({state:u.artifactContract,inputMessages:a,toolName:c.function.name,rawArguments:c.function.arguments});d?Qn.push({call:c,...d}):us.push(c)}for(let c of Qn){let d=c.call;E.push({name:d.function.name,reason:"artifact-root-contract"}),Go(u.artifactContract,{path:c.path,artifactRoot:c.artifactRoot,toolName:d.function.name}),S(g,te(d.id,{ok:!1,error:c.error})),ee.push(d.id),G.add(d.function.name),q++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:c.error},Gn()&&(yield qn()),o.warn(`artifact root contract blocked: ${d.function.name}`)}Qn.length>0&&g.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 ds=[],eo=[];for(let c of us){let d=Wi({inputMessages:a,messages:g,toolCall:c});d?eo.push({call:c,error:d}):ds.push(c)}for(let c of eo){let d=c.call;E.push({name:d.function.name,reason:"premature-completion-artifact"}),S(g,te(d.id,{ok:!1,error:c.error})),ee.push(d.id),G.add(d.function.name),q++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:c.error},o.info(`premature completion artifact blocked: ${d.function.name}`)}eo.length>0&&g.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 gl=new Set(k.map(c=>c.function.name)),fs=[],Gt=[];for(let c of ds)gl.has(c.function.name)?fs.push(c):Gt.push(c);for(let c of Gt){let d=`Tool "${c.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;E.push({name:c.function.name,reason:"not-offered"}),S(g,te(c.id,{ok:!1,error:d})),ee.push(c.id),G.add(c.function.name),o.warn(`unoffered tool call suppressed: ${c.function.name}`)}if(Gt.length>0&&u.notOfferedToolRecoveryCount<1){let c=[...new Set(Gt.map(b=>b.function.name))].sort(),d=gt&&c.includes("write"),h=c.filter(b=>j.has(b)),p=(l??i).filter(b=>c.includes(b.function.name));if(h.length>0)u.notOfferedToolRecoveryCount+=1,W=!0,g.push({role:"user",content:`You retried ${h.map(b=>`\`${b}\``).join(", ")} after it was disabled by this turn's tool-selection policy. Do not retry policy-suppressed tools in this turn. Continue using only the currently enabled tools, or stop with a clear blocker.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"policy_suppressed_tool_retry_blocked",intent:"tool_recovery",reason:"requested-tool-disabled-by-turn-policy",availableToolNames:x(l??i),enabledToolNamesBefore:x(k),enabledToolNamesAfter:x(k),suppressedToolNames:h,nextAction:"continue-with-currently-enabled-tools-or-report-blocker"},yield O("policy_suppressed_tool_retry_blocked",h.join(","));else if(!d&&p.length>0){let b=x(k),L=new Map(k.map(U=>[U.function.name,U]));for(let U of p)L.set(U.function.name,U);k=xn([...L.values()]),u.notOfferedToolRecoveryCount+=1,W=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"available_tool_reenabled_after_not_offered_call",intent:"tool_recovery",reason:"requested-tool-available-but-disabled",availableToolNames:x(l??i),enabledToolNamesBefore:b,enabledToolNamesAfter:x(k),suppressedToolNames:[],nextAction:"retry-with-reenabled-requested-tool"},g.push({role:"user",content:`You called ${c.map(U=>`\`${U}\``).join(", ")} but it was not enabled for that round even though it is available. The requested available tool has now been re-enabled. Use the re-enabled tool once with valid arguments; do not repeat a disabled-tool call.`}),yield O("available_tool_reenabled_after_not_offered_call",c.join(","))}}let ps=[],to=[];for(let c of fs){let d=Qe.tools.find(C=>C.function.name===c.function.name),h=of(d,c.function.arguments);h?to.push({call:c,error:h}):ps.push(c)}for(let c of to){let d=c.call;E.push({name:d.function.name,reason:"invalid-arguments"}),S(g,te(d.id,{ok:!1,error:c.error})),ee.push(d.id),G.add(d.function.name),q++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:c.error,details:{type:d.function.name,error:"invalid_arguments"}},o.info(`invalid tool arguments blocked: ${d.function.name}`)}to.length>0&&g.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."});let Tt=[],no=[];for(let c of ps){if(c.function.name!=="exec"){Tt.push(c);continue}let d=_a(c.function.arguments);if(!d){Tt.push(c);continue}let h=oa(d);if(ra(h)&&!ia(d)&&Ra(M)){let C=`${c.function.name}::${c.function.arguments}`;if(Pn.has(C)){Pn.delete(C),o.info(`dedicated-tool guard: verbatim re-issue admitted once for exec: ${d}`),Tt.push(c);continue}Pn.add(C),no.push({call:c,error:tf(h)})}else Tt.push(c)}for(let c of no){let d=c.call;E.push({name:d.function.name,reason:"dedicated-tool-required"});let h=x(k),C=k.filter(p=>["read","search"].includes(p.function.name));C.length>0&&(k=C,Nn=!0,W=!0),S(g,te(d.id,{ok:!1,error:c.error})),ee.push(d.id),G.add(d.function.name),q++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:c.error,details:{type:d.function.name,error:"dedicated_tool_required",dedicatedTool:"read/search"}},o.info(`dedicated file tool preflight blocked: ${d.function.name}`),yield{type:"tool_selection_policy",turnId:r,policyId:"dedicated_file_tool_required",intent:"fresh_evidence",reason:"exec-file-read-search-list-blocked",availableToolNames:x(l??i),enabledToolNamesBefore:h,enabledToolNamesAfter:x(k),suppressedToolNames:h.filter(p=>!["read","search"].includes(p)),nextAction:"use-read-search-for-file-inspection-then-resume-build-run-verify-tools"}}no.length>0&&g.push({role:"user",content:"Exec was blocked because it attempted local file reading/searching/listing. Use read/search for the next local file inspection step. After that, resume exec only for non-inspection commands such as installs, builds, dev servers, and verification scripts."});let Wt=[],oo=[],gs=[],ms=[],ro=new Map,hs=(c,d)=>{let h=ro.get(c);ro.set(c,h?`${h}
|
|
56
|
-
${d}`:d)};for(let c of Tt){if(c.function.name!=="exec"){Wt.push(c);continue}let d=c,h=_a(d.function.arguments),C=h?Xd(h):null;C&&(d={...d,function:{...d.function,arguments:wa(d.function.arguments,C)}},ms.push({originalCommand:h??"",rewrittenCommand:C}),hs(c.id,`[Engine notice] Adjusted this command before execution: removed the blocking sleep prefix (a foreground sleep stalls the turn). Executed: ${C}`),h=C);let p=h?Kd(h):null;if(p?.action==="block")oo.push({call:d,error:p.error});else if(p?.action==="rewrite"){let b={...d,function:{...d.function,arguments:wa(d.function.arguments,p.command)}};gs.push({call:b,originalCommand:h??"",rewrittenCommand:p.command}),hs(c.id,`[Engine notice] Adjusted this command before execution: appended --strictPort so a busy port cannot fall back onto reserved frontend port ${vn}. Executed: ${p.command}`),Wt.push(b)}else Wt.push(d)}for(let c of ms)yield{type:"tool_selection_policy",turnId:r,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:x(l??i),enabledToolNamesBefore:x(k),enabledToolNamesAfter:x(k),suppressedToolNames:[],nextAction:"execute-command-without-blocking-sleep-prefix"},o.info(`blocking sleep prefix removed before exec: ${c.originalCommand} -> ${c.rewrittenCommand}`);for(let c of gs){let d=x(k);yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"vite-strict-port-normalized",availableToolNames:x(l??i),enabledToolNamesBefore:d,enabledToolNamesAfter:x(k),suppressedToolNames:[],nextAction:"execute-normalized-vite-dev-server-command-with-strict-port"},o.info(`vite strict port normalized before exec: ${c.originalCommand} -> ${c.rewrittenCommand}`)}for(let c of oo){let d=c.call;E.push({name:d.function.name,reason:"reserved-frontend-port"});let h=x(k);S(g,te(d.id,{ok:!1,error:c.error})),ee.push(d.id),G.add(d.function.name),q++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:c.error,details:{type:d.function.name,error:"reserved_frontend_port",reservedPort:vn}},o.info(`reserved frontend port preflight blocked: ${d.function.name}`),yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"reserved-frontend-port",availableToolNames:x(l??i),enabledToolNamesBefore:h,enabledToolNamesAfter:x(k),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}oo.length>0&&g.push({role:"user",content:"A dev server command was blocked because it could occupy or fallback onto port 5174, which is reserved for the Xiaozhi Claw frontend. Retry with an explicit generated-app port other than 5174 and use --strictPort for Vite so browser evidence cannot be polluted."});let kt=[],tt=[];for(let c of Wt){if(c.function.name!=="read"){kt.push(c);continue}let d=Rr(c.function.arguments);if(!d){kt.push(c);continue}let h=Q(d),C=qa(h);if((u.fileReadCounts.get(h)??0)>=C){let p=u.fileReadSignatures.get(h),b=Da(d);if(p&&b&&(b.mtimeMs!==p.mtimeMs||b.sizeBytes!==p.sizeBytes)){o.info(`read cycle exemption: ${h} changed since last counted read, cap reset`),u.fileReadCounts.set(h,0),kt.push(c);continue}tt.push({call:c,filePath:h,maxReads:C})}else kt.push(c)}for(let c of tt){let d=c.call,h=`Read cycle policy blocked another read of "${c.filePath}" after ${c.maxReads} successful reads in this turn. Stop rereading the same large document. ${Tr(c.filePath)}`;E.push({name:d.function.name,reason:"read-cycle-policy"}),u.fileReadCycleBlockedPaths.add(c.filePath),S(g,te(d.id,{ok:!1,error:h})),ee.push(d.id),G.add(d.function.name),q++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:h},o.info(`read cycle blocked: ${c.filePath}`)}if(tt.length>0){let c=[...new Set(tt.map(C=>`${C.filePath} (max ${C.maxReads})`))].join(", "),d=[...new Set(tt.map(C=>Tr(C.filePath)))].join(" ");if(g.push({role:"user",content:`Further reads were blocked because these large/context documents already reached their per-turn read limit: ${c}. Do not retry the read with a different path spelling. ${d} Continue from maintained requirements/defects/decisions/acceptance evidence and report any truly missing section explicitly.`}),k.some(C=>Ba(C.function.name))&&(u.persistedLongHorizonStateRecovered||tt.some(C=>Ar(C.filePath)))){let C=x(k),p=C.filter(b=>Rf.has(b)).sort();yield{type:"tool_selection_policy",turnId:r,policyId:"long_horizon_benchmark_state_maintenance",intent:"benchmark_state_maintenance",reason:"read-cycle-guard-retains-evidence-tools",availableToolNames:x(l??i),enabledToolNamesBefore:C,enabledToolNamesAfter:x(k),suppressedToolNames:[],nextAction:"maintenance-or-final-answer"},g.push({role:"user",content:`Do not reread the blocked large/context document paths again. Evidence tools still enabled: ${p.join(", ")||"none"}. Use read/search only for targeted verification of generated artifacts, file names, and missing sections; use edit/patch/write only if benchmark-state maintenance needs an update; otherwise stop tool use and answer from the maintained benchmark-state evidence. Classify any unused edit/patch/write tools as not needed, not missing.`}),yield O("benchmark_state_maintenance_tool_bias","retaining targeted evidence tools after long-horizon read-cycle guard")}if(Af(E,u.fileReadCycleBlockedPaths,u.persistedLongHorizonStateRecovered,u.maintainedDocuments)){yield*ne("Stopped repeated long-horizon context-pack rereads after the read-cycle guard blocked every maintained source document. Continue from benchmark-state/document-index.json, decision-state-table.json, and context-pack-evidence.json; do not reread or rewrite context-pack source documents.",{forcedStop:!0});return}}let so=Zi(kt,u.toolFailureCounts,u.variantReassertedSignatures),io=so.allowed;if(Lr&&io.length>Math.max(0,pe-q)){let c=nr({currentToolBudget:pe,currentRoundBudget:Y,toolHardCap:100,roundHardCap:100,continuationCount:ft,successfulSinceLastCheck:dt-Ot,fileReadCounts:u.fileReadCounts,windowTools:ve,windowRounds:25});c&&(pe=c.nextToolBudget,Y=c.nextRoundBudget,ft=c.continuationCount,Ot=dt,o.info(`tool budget continuation #${c.continuationCount}: tools\u2192${pe}, rounds\u2192${Y} (progress detected)`))}let ys=Math.max(0,pe-q),de=ys>0?io.slice(0,ys):[];for(let c of de){if(!Fa(c,u))continue;let d=Te(c.function.arguments),h=typeof d?.taskId=="string"?d.taskId:void 0;!d||!h||typeof d.waitMs=="number"||(c.function.arguments=JSON.stringify({...d,waitMs:df(u.backgroundAgentPollCounts.get(h)??0)}))}let ao=io.slice(de.length),ml=ao.length>0;if(so.blocked.length>0){for(let c of so.blocked){let d=c.call;E.push({name:d.function.name,reason:"variant-failure-policy"});let h=te(d.id,{ok:!1,error:c.error});S(g,h),ee.push(d.id),G.add(d.function.name),q++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:c.error},o.info(`variant tool blocked: ${d.function.name} failed ${c.failCount}x with different args`)}g.push(Qi())}if(ao.length>0){let c=`Tool call budget exhausted (${pe}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of ao){E.push({name:d.function.name,reason:"tool-call-budget"});let h=te(d.id,{ok:!1,error:c});S(g,h),ee.push(d.id),G.add(d.function.name),q++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:c}}g.push({role:"user",content:`${c} You reached this turn's tool budget after ${ft} 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 c of de){let d=c.function.arguments,h=k.find(p=>p.function.name===c.function.name);if(h?.backfillObservableInput)try{let p=JSON.parse(c.function.arguments),b={...p};h.backfillObservableInput(b),Object.keys(b).some(U=>!(U in p))&&(d=JSON.stringify(b))}catch{}let C={sequence:Ae.length,callId:c.id,name:c.function.name,identity:Oa(h,c.function.name),status:"running",arguments:d};Ae.push(C),Mn.set(c.id,C),yield{type:"tool_call",turnId:r,callId:c.id,name:c.function.name,...h?.meta?.displayName?.fallback?.trim()?{displayName:h.meta.displayName.fallback.trim()}:{},arguments:d,inputSummary:tr(d)},$r.add(c.function.name),Dr++}let hl=new Map(u.toolFailureCounts),Vt=null;try{let c=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:T,sessionId:s,turnId:r,log:o,signal:v,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:Is,executionTimeoutMsByTool:new Map(k.flatMap(p=>{let b=p.meta?.executionTimeoutMs;return typeof b=="number"&&Number.isFinite(b)&&b>0?[[p.function.name,b]]:[]})),projectRoot:e.projectRoot,contextState:u.contentReplacementState});for(let p of de)c.addTool(p);let d=!1;for await(let p of c.getRemainingResults()){let b=Mn.get(p.callId);b&&(b.status=p.blocked?"blocked":p.ok?"succeeded":"failed",!p.ok&&typeof p.error=="string"&&p.error.trim()&&(b.error=p.error),p.ok||(b.failureKind=Hs(p)));let L=zd(p);if(L){if(E.push({name:p.toolName,reason:L}),p.toolName==="exec"&&L==="dedicated-tool-required"&&Ra(M)){let R=x(k);g.push({role:"user",content:"Exec was blocked because it attempted local file reading/searching/listing. Use read/search for local file inspection. Exec remains available only for non-inspection commands such as installs, builds, dev servers, and verification scripts."}),yield{type:"tool_selection_policy",turnId:r,policyId:"dedicated_file_tool_required",intent:"fresh_evidence",reason:"exec-file-read-search-list-blocked",availableToolNames:x(l??i),enabledToolNamesBefore:R,enabledToolNamesAfter:x(k),suppressedToolNames:[],nextAction:"use-read-search-for-file-inspection-or-exec-for-build-run-verify"}}if(p.toolName==="exec"&&L==="confirmation-timeout"){let R=x(k);j.add("exec");let A=fe(M,j);A.length>0&&(k=xn(A),W=!0),g.push({role:"user",content:"Exec confirmation timed out, so exec is disabled for the rest of this turn. Do not retry exec. Use read/search for inspection, edit/patch/write for file updates, ask_user only for missing user input, or stop with a clear blocker if no non-exec tool can complete the request."}),yield{type:"tool_selection_policy",turnId:r,policyId:"exec_confirmation_timeout_recovery",intent:"tool_recovery",reason:"exec-confirmation-timeout",availableToolNames:x(l??i),enabledToolNamesBefore:R,enabledToolNamesAfter:x(k),suppressedToolNames:Cn(R,x(k)),nextAction:"continue-with-non-exec-tools-or-report-confirmation-blocker"}}if(p.toolName==="exec"&&L==="global-process-kill-blocked"){let R=x(k);g.push({role:"user",content:"Exec was blocked because it attempted to terminate every node process. Do not retry taskkill/killall/pkill/Stop-Process by process name. If a generated app server conflicts with another process, start the generated app on a new explicit non-5174 port with strict port behavior, or stop only an owned background task by its task id. Continue by verifying the app on the reachable generated-app URL."}),yield{type:"tool_selection_policy",turnId:r,policyId:"global_process_kill_recovery",intent:"verification",reason:"global-node-process-kill-blocked",availableToolNames:x(l??i),enabledToolNamesBefore:R,enabledToolNamesAfter:x(k),suppressedToolNames:[],nextAction:"use-owned-task-cancel-or-new-explicit-port"}}}p.blocked&&(yield{type:"tool_blocked",turnId:r,callId:p.callId,name:p.toolName,reason:p.blockReason??"blocked"});let U=ro.get(p.callId);if(U){let R=p.message;typeof R.content=="string"&&(R.content=`${U}
|
|
56
|
+
${d}`:d)};for(let c of Tt){if(c.function.name!=="exec"){Wt.push(c);continue}let d=c,h=_a(d.function.arguments),C=h?Xd(h):null;C&&(d={...d,function:{...d.function,arguments:wa(d.function.arguments,C)}},ms.push({originalCommand:h??"",rewrittenCommand:C}),hs(c.id,`[Engine notice] Adjusted this command before execution: removed the blocking sleep prefix (a foreground sleep stalls the turn). Executed: ${C}`),h=C);let p=h?Kd(h):null;if(p?.action==="block")oo.push({call:d,error:p.error});else if(p?.action==="rewrite"){let b={...d,function:{...d.function,arguments:wa(d.function.arguments,p.command)}};gs.push({call:b,originalCommand:h??"",rewrittenCommand:p.command}),hs(c.id,`[Engine notice] Adjusted this command before execution: appended --strictPort so a busy port cannot fall back onto reserved frontend port ${vn}. Executed: ${p.command}`),Wt.push(b)}else Wt.push(d)}for(let c of ms)yield{type:"tool_selection_policy",turnId:r,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:x(l??i),enabledToolNamesBefore:x(k),enabledToolNamesAfter:x(k),suppressedToolNames:[],nextAction:"execute-command-without-blocking-sleep-prefix"},o.info(`blocking sleep prefix removed before exec: ${c.originalCommand} -> ${c.rewrittenCommand}`);for(let c of gs){let d=x(k);yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"vite-strict-port-normalized",availableToolNames:x(l??i),enabledToolNamesBefore:d,enabledToolNamesAfter:x(k),suppressedToolNames:[],nextAction:"execute-normalized-vite-dev-server-command-with-strict-port"},o.info(`vite strict port normalized before exec: ${c.originalCommand} -> ${c.rewrittenCommand}`)}for(let c of oo){let d=c.call;E.push({name:d.function.name,reason:"reserved-frontend-port"});let h=x(k);S(g,te(d.id,{ok:!1,error:c.error})),ee.push(d.id),G.add(d.function.name),q++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:c.error,details:{type:d.function.name,error:"reserved_frontend_port",reservedPort:vn}},o.info(`reserved frontend port preflight blocked: ${d.function.name}`),yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"reserved-frontend-port",availableToolNames:x(l??i),enabledToolNamesBefore:h,enabledToolNamesAfter:x(k),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}oo.length>0&&g.push({role:"user",content:"A dev server command was blocked because it could occupy or fallback onto port 5174, which is reserved for the Xiaozhi Claw frontend. Retry with an explicit generated-app port other than 5174 and use --strictPort for Vite so browser evidence cannot be polluted."});let kt=[],tt=[];for(let c of Wt){if(c.function.name!=="read"){kt.push(c);continue}let d=Rr(c.function.arguments);if(!d){kt.push(c);continue}let h=Q(d),C=qa(h);if((u.fileReadCounts.get(h)??0)>=C){let p=u.fileReadSignatures.get(h),b=Da(d);if(p&&b&&(b.mtimeMs!==p.mtimeMs||b.sizeBytes!==p.sizeBytes)){o.info(`read cycle exemption: ${h} changed since last counted read, cap reset`),u.fileReadCounts.set(h,0),kt.push(c);continue}tt.push({call:c,filePath:h,maxReads:C})}else kt.push(c)}for(let c of tt){let d=c.call,h=`Read cycle policy blocked another read of "${c.filePath}" after ${c.maxReads} successful reads in this turn. Stop rereading the same large document. ${Tr(c.filePath)}`;E.push({name:d.function.name,reason:"read-cycle-policy"}),u.fileReadCycleBlockedPaths.add(c.filePath),S(g,te(d.id,{ok:!1,error:h})),ee.push(d.id),G.add(d.function.name),q++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:h},o.info(`read cycle blocked: ${c.filePath}`)}if(tt.length>0){let c=[...new Set(tt.map(C=>`${C.filePath} (max ${C.maxReads})`))].join(", "),d=[...new Set(tt.map(C=>Tr(C.filePath)))].join(" ");if(g.push({role:"user",content:`Further reads were blocked because these large/context documents already reached their per-turn read limit: ${c}. Do not retry the read with a different path spelling. ${d} Continue from maintained requirements/defects/decisions/acceptance evidence and report any truly missing section explicitly.`}),k.some(C=>Ba(C.function.name))&&(u.persistedLongHorizonStateRecovered||tt.some(C=>Ar(C.filePath)))){let C=x(k),p=C.filter(b=>Rf.has(b)).sort();yield{type:"tool_selection_policy",turnId:r,policyId:"long_horizon_benchmark_state_maintenance",intent:"benchmark_state_maintenance",reason:"read-cycle-guard-retains-evidence-tools",availableToolNames:x(l??i),enabledToolNamesBefore:C,enabledToolNamesAfter:x(k),suppressedToolNames:[],nextAction:"maintenance-or-final-answer"},g.push({role:"user",content:`Do not reread the blocked large/context document paths again. Evidence tools still enabled: ${p.join(", ")||"none"}. Use read/search only for targeted verification of generated artifacts, file names, and missing sections; use edit/patch/write only if benchmark-state maintenance needs an update; otherwise stop tool use and answer from the maintained benchmark-state evidence. Classify any unused edit/patch/write tools as not needed, not missing.`}),yield O("benchmark_state_maintenance_tool_bias","retaining targeted evidence tools after long-horizon read-cycle guard")}if(Af(E,u.fileReadCycleBlockedPaths,u.persistedLongHorizonStateRecovered,u.maintainedDocuments)){yield*ne("Stopped repeated long-horizon context-pack rereads after the read-cycle guard blocked every maintained source document. Continue from benchmark-state/document-index.json, decision-state-table.json, and context-pack-evidence.json; do not reread or rewrite context-pack source documents.",{forcedStop:!0});return}}let so=Zi(kt,u.toolFailureCounts,u.variantReassertedSignatures),io=so.allowed;if(Lr&&io.length>Math.max(0,pe-q)){let c=nr({currentToolBudget:pe,currentRoundBudget:Y,toolHardCap:100,roundHardCap:100,continuationCount:ft,successfulSinceLastCheck:dt-Ot,fileReadCounts:u.fileReadCounts,windowTools:ve,windowRounds:25});c&&(pe=c.nextToolBudget,Y=c.nextRoundBudget,ft=c.continuationCount,Ot=dt,o.info(`tool budget continuation #${c.continuationCount}: tools\u2192${pe}, rounds\u2192${Y} (progress detected)`))}let ys=Math.max(0,pe-q),de=ys>0?io.slice(0,ys):[];for(let c of de){if(!Fa(c,u))continue;let d=Te(c.function.arguments),h=typeof d?.taskId=="string"?d.taskId:void 0;!d||!h||typeof d.waitMs=="number"||(c.function.arguments=JSON.stringify({...d,waitMs:df(u.backgroundAgentPollCounts.get(h)??0)}))}let ao=io.slice(de.length),ml=ao.length>0;if(so.blocked.length>0){for(let c of so.blocked){let d=c.call;E.push({name:d.function.name,reason:"variant-failure-policy"});let h=te(d.id,{ok:!1,error:c.error});S(g,h),ee.push(d.id),G.add(d.function.name),q++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:c.error},o.info(`variant tool blocked: ${d.function.name} failed ${c.failCount}x with different args`)}g.push(Qi())}if(ao.length>0){let c=`Tool call budget exhausted (${pe}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of ao){E.push({name:d.function.name,reason:"tool-call-budget"});let h=te(d.id,{ok:!1,error:c});S(g,h),ee.push(d.id),G.add(d.function.name),q++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:c}}g.push({role:"user",content:`${c} You reached this turn's tool budget after ${ft} 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 c of de){let d=c.function.arguments,h=k.find(p=>p.function.name===c.function.name);if(h?.backfillObservableInput)try{let p=JSON.parse(c.function.arguments),b={...p};h.backfillObservableInput(b),Object.keys(b).some(U=>!(U in p))&&(d=JSON.stringify(b))}catch{}let C={sequence:Ae.length,callId:c.id,name:c.function.name,identity:Oa(h,c.function.name),status:"running",arguments:d};Ae.push(C),Mn.set(c.id,C),yield{type:"tool_call",turnId:r,callId:c.id,name:c.function.name,...h?.meta?.displayName?.fallback?.trim()?{displayName:h.meta.displayName.fallback.trim()}:{},arguments:d,inputSummary:tr(d)},$r.add(c.function.name),Dr++}let hl=new Map(u.toolFailureCounts),Vt=null;try{let c=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:T,sessionId:s,turnId:r,log:o,signal:v,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:Is,executionTimeoutMsByTool:new Map(k.flatMap(p=>{let b=p.meta?.executionTimeoutMs;return typeof b=="number"&&Number.isFinite(b)&&b>0?[[p.function.name,b]]:[]})),requiredSkillsByTool:new Map(k.flatMap(p=>{let b=p.meta?.semanticCapability?.requiredSkills;return b&&b.length>0?[[p.function.name,[...b]]]:[]})),projectRoot:e.projectRoot,contextState:u.contentReplacementState});for(let p of de)c.addTool(p);let d=!1;for await(let p of c.getRemainingResults()){let b=Mn.get(p.callId);b&&(b.status=p.blocked?"blocked":p.ok?"succeeded":"failed",!p.ok&&typeof p.error=="string"&&p.error.trim()&&(b.error=p.error),p.ok||(b.failureKind=Hs(p)));let L=zd(p);if(L){if(E.push({name:p.toolName,reason:L}),p.toolName==="exec"&&L==="dedicated-tool-required"&&Ra(M)){let R=x(k);g.push({role:"user",content:"Exec was blocked because it attempted local file reading/searching/listing. Use read/search for local file inspection. Exec remains available only for non-inspection commands such as installs, builds, dev servers, and verification scripts."}),yield{type:"tool_selection_policy",turnId:r,policyId:"dedicated_file_tool_required",intent:"fresh_evidence",reason:"exec-file-read-search-list-blocked",availableToolNames:x(l??i),enabledToolNamesBefore:R,enabledToolNamesAfter:x(k),suppressedToolNames:[],nextAction:"use-read-search-for-file-inspection-or-exec-for-build-run-verify"}}if(p.toolName==="exec"&&L==="confirmation-timeout"){let R=x(k);j.add("exec");let A=fe(M,j);A.length>0&&(k=xn(A),W=!0),g.push({role:"user",content:"Exec confirmation timed out, so exec is disabled for the rest of this turn. Do not retry exec. Use read/search for inspection, edit/patch/write for file updates, ask_user only for missing user input, or stop with a clear blocker if no non-exec tool can complete the request."}),yield{type:"tool_selection_policy",turnId:r,policyId:"exec_confirmation_timeout_recovery",intent:"tool_recovery",reason:"exec-confirmation-timeout",availableToolNames:x(l??i),enabledToolNamesBefore:R,enabledToolNamesAfter:x(k),suppressedToolNames:Cn(R,x(k)),nextAction:"continue-with-non-exec-tools-or-report-confirmation-blocker"}}if(p.toolName==="exec"&&L==="global-process-kill-blocked"){let R=x(k);g.push({role:"user",content:"Exec was blocked because it attempted to terminate every node process. Do not retry taskkill/killall/pkill/Stop-Process by process name. If a generated app server conflicts with another process, start the generated app on a new explicit non-5174 port with strict port behavior, or stop only an owned background task by its task id. Continue by verifying the app on the reachable generated-app URL."}),yield{type:"tool_selection_policy",turnId:r,policyId:"global_process_kill_recovery",intent:"verification",reason:"global-node-process-kill-blocked",availableToolNames:x(l??i),enabledToolNamesBefore:R,enabledToolNamesAfter:x(k),suppressedToolNames:[],nextAction:"use-owned-task-cancel-or-new-explicit-port"}}}p.blocked&&(yield{type:"tool_blocked",turnId:r,callId:p.callId,name:p.toolName,reason:p.blockReason??"blocked"});let U=ro.get(p.callId);if(U){let R=p.message;typeof R.content=="string"&&(R.content=`${U}
|
|
57
57
|
|
|
58
58
|
${R.content}`)}{let R=p.message;e.sanitizeToolResultMedia&&(Array.isArray(R.imageUrls)||Array.isArray(R.audioUrls)||Array.isArray(R.videoUrls))&&await e.sanitizeToolResultMedia(R)}if(S(g,p.message),Lt&&p.toolName===xe&&p.ok&&(Lt=!1,On=!0,j.delete(xe),j.delete(Je),k=fe(M,j),W=!0,g.push({role:"user",content:"Use the returned Host Skill directory now. Load the single best matching Skill with astraclaw__skill_read using its exact read locator before any execution tool. If the current page has no match and returned nextCursor, request the next directory page; do not switch to exec or filesystem inspection."}),yield{type:"tool_selection_policy",turnId:r,policyId:"host_skill_directory_ready",intent:"capability_routing",reason:"host-skill-directory-page",availableToolNames:x(l??i),enabledToolNamesBefore:[xe],enabledToolNamesAfter:x(k),suppressedToolNames:[...j].sort(),nextAction:"load-matching-host-skill",routingEvidence:D}),On&&p.toolName===Je&&p.ok){for(let A of Pa(p.details,"requiredTools")??[])Ur(A);if(br(u.contentReplacementState,"__discovered_skill_route_probe__"))j.add(xe),Ye.add(xe),k=fe(M,j),W=!0;else{On=!1;for(let A of Ye)(A===xe||A===Je||[...pt].some(I=>Ia(A,I)))&&j.delete(A);k=fe(M,j),W=pt.size>0}}if(Ee&&p.toolName===Je&&p.ok){for(let I of Pa(p.details,"requiredTools")??[])Ur(I);let R=de.find(I=>I.id===p.callId),A="";try{let I=JSON.parse(R?.function.arguments??"{}");A=typeof I.name=="string"?I.name:""}catch{}if(Nt.has(A)){if(br(u.contentReplacementState,"__capability_route_probe__"))W=!0;else if(Nt.delete(A),Ee=Nt.size>0,!Ee){for(let se of Ye)(pt.size===0||[...pt].some(me=>Ia(se,me)))&&j.delete(se);Ye.clear(),k=fe(M,j)}}}ee.push(p.callId),G.add(p.toolName);let ye=lf(p,u);ye||q++;let Ct=p.ok&&Yo(p),bl=p.toolName==="exec"&&er(wr(de.find(R=>R.id===p.callId)?.function.arguments??""));p.ok&&!Ct&&!ye&&!bl&&(dt+=1),ye||ea({toolFailureCounts:u.toolFailureCounts,toolName:p.toolName,toolArguments:de.find(R=>R.id===p.callId)?.function.arguments,ok:p.ok,softEmpty:Ct});let co=Mn.get(p.callId);if(!p.ok&&co&&Ft.has(co.identity.logicalName)){let R=x(k);for(let A of Ma)j.add(A);k=fe(M,j),g.push({role:"user",content:`The selected Skill's required executor (${co.identity.logicalName}) failed. Do not switch to exec, shell, PowerShell, Python, direct file authoring, or another tool family, and do not create a substitute artifact. Do not offer any of those suppressed fallback paths to the user. Use the exact returned error to diagnose with read/skill_read or ask_user when needed. Retry only this Skill executor when the failure is retryable or the arguments can be corrected; otherwise report the blocker without claiming completion.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"skill_executor_failure_no_generic_fallback",intent:"tool_recovery",reason:"skill-required-executor-failed",availableToolNames:x(l??i),enabledToolNamesBefore:R,enabledToolNamesAfter:x(k),suppressedToolNames:[...Ma].sort(),nextAction:"retry-required-skill-executor-or-report-blocker"}}let uo=Z.find(R=>R.id===p.callId);if(p.ok&&uo&&u.identicalFailureCounts.delete(`${uo.function.name}::${uo.function.arguments}`),p.ok&&mf.has(Ce(p.toolName))&&Jf(u),p.ok&&Ba(p.toolName)){let R=de.find(I=>I.id===p.callId),A=R?Sn(R.function.arguments):void 0;if(A){let I=Q(A);if(u.longHorizonStateMaintenanceRequiredFiles.has(I)){let se=Mr(u.maintainedDocuments,I,R?.function.arguments??"");se.ok?u.longHorizonStateMaintenanceWrittenFiles.add(I):(E.push({name:p.toolName,reason:"benchmark-state-invalid-content"}),g.push({role:"user",content:`Benchmark-state maintenance write for ${I} is incomplete: ${se.reason}. Rewrite or patch the file using the document evidence already provided; do not reread context-pack source documents.`}))}}}if(p.ok&&!Ct&&(kr.has(p.toolName)||p.toolName==="exec"&&p.details?.type==="exec_background"||p.toolName==="exec"&&Aa(de.find(R=>R.id===p.callId)?.function.arguments??""))){let R=de.find(I=>I.id===p.callId),A=typeof p.message?.content=="string"?p.message.content:"";if(R&&A){let I=Array.isArray(p.message.imageUrls)?p.message.imageUrls.filter(me=>typeof me=="string"):void 0,se=Array.isArray(p.message.toolReferences)?p.message.toolReferences.filter(me=>typeof me=="string"):void 0;u.identicalSuccessfulToolResults.set(`${R.function.name}::${R.function.arguments}`,{content:A,imageUrls:I,toolReferences:se})}}if(p.toolName==="agent"){let R=Ge(p.details,"agentId"),A=Ge(p.details,"status"),I=_n(p.details,"background");p.ok&&R&&I===!0&&A==="running"&&We(u).add(R)}if(p.toolName==="task"){let R=gf(p.details);R&&(u.lastTaskList=R);let A=Ge(p.details,"taskId"),I=_n(p.details,"running"),se=Ge(p.details,"lifecycle"),me=Ge(p.details,"action");if(A&&(me==="cancel"||I===!1||se&&se!=="running"&&se!=="pending"))We(u).delete(A),u.backgroundAgentPollCounts.delete(A),u.backgroundAgentNoOutputPollCounts.delete(A),u.stalledBackgroundAgentTasks.delete(A);else if(A&&me==="output"&&I===!0&&We(u).has(A)){let nt=(u.backgroundAgentPollCounts.get(A)??0)+1;u.backgroundAgentPollCounts.set(A,nt),nt>=$a&&u.stalledBackgroundAgentTasks.set(A,`still running after ${nt} bounded poll(s)`);let bs=typeof p.message?.content=="string"?p.message.content:"",Ts=_n(p.details,"hasOutput");if(Ts!==void 0?Ts===!1:ff(bs)){let po=(u.backgroundAgentNoOutputPollCounts.get(A)??0)+1;u.backgroundAgentNoOutputPollCounts.set(A,po);let Yt=af(p.details,"elapsedSeconds")??pf(bs);(Yt!==void 0&&Yt>=cf||Yt===void 0&&po>=uf)&&u.stalledBackgroundAgentTasks.set(A,`no output after ${Yt??"unknown"}s across ${po} poll(s)`)}else u.backgroundAgentNoOutputPollCounts.delete(A),nt<$a&&u.stalledBackgroundAgentTasks.delete(A)}}if(p.ok&&p.toolName==="read"){let R=de.find(A=>A.id===p.callId);if(R){let A=Rr(R.function.arguments);if(A){let I=Q(A),se=u.fileReadCounts.get(I)??0;u.fileReadCounts.set(I,se+1);let me=Da(A);me&&u.fileReadSignatures.set(I,me);let nt=typeof p.message?.content=="string"?p.message.content:"";d=Bf(u,A,nt,u.turnCount,p.details)||d}}}yield qs(r,p);for(let R of Gs(r,p))yield R;for(let R of Ks({turnId:r,result:p,toolCalls:Z}))yield R;let fo=Z.find(R=>R.id===p.callId),Tl=typeof p.message?.content=="string"?p.message.content:"";if(fo){ci({state:u.artifactContract,inputMessages:a,toolName:p.toolName,rawArguments:fo.function.arguments,ok:p.ok,content:Tl,details:p.details}),Gn()&&(yield qn());let R=Jd(p.toolName,fo.function.arguments);if(R){let A=(Br.get(R)??0)+1;if(Br.set(R,A),A===Sa){let I=R.startsWith("exec:")?"exec":"edit";u.recoveryTrace.set(`no_progress_observed:${I}`,(u.recoveryTrace.get(`no_progress_observed:${I}`)??0)+1),jr.has(R)||(jr.add(R),g.push({role:"user",content:`You have now run ${Sa} variations of the same action (${R}) without completing the user's request. Stop this approach: summarize what you tried and why it failed, then either take a FUNDAMENTALLY different route or report the blocker honestly. Do not run another variation of the same command family.`}),yield O("no_progress_nudge",R))}}}!Vt&&tl&&Do(p.toolName,"stt")&&p.ok&&(Vt=Dd(a,p))}let h=[...new Set(de.map(p=>vr(p.function.name)).filter(p=>p!==void 0))];if(Me===void 0&&h.length===1){Me=h[0];let p=x(k);k=Ua(M,Me),W=!0,D={schemaVersion:1,owner:"mcp-capability",source:"continuation",selectedNamespaces:[Me],matchedFeatures:["model-selected-connector","connector-family-closure"],availableToolCount:(l??i).length,exposedToolCount:k.length},g.push({role:"user",content:`The turn is now committed to connector namespace ${Me}. Continue only with the supplied tools from that connector. If they fail, report the failure; do not switch to exec, shell, filesystem tools, Skills, or another connector.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"connector_family_committed",intent:"capability_routing",reason:"model-selected-connector",availableToolNames:x(l??i),enabledToolNamesBefore:p,enabledToolNamesAfter:x(k),suppressedToolNames:Cn(p,x(k)),nextAction:"continue-with-selected-connector-or-report-its-failure",routingEvidence:D}}if(Ee&&(W=!0),gt&&(k=fe(M,j),gt=!1),Nn&&(k=fe(M,j),Nn=!1),d){let p=Lf(r,u.maintainedDocuments,u.fileReadCounts,u.turnCount);p&&(yield p);for(let U of Df(r,u.maintainedDocuments))yield U;let b=_f(u.maintainedDocuments,u.turnCount),L=k.some(U=>Cr.has(U.function.name));if(b&&L){u.longHorizonStateMaintenanceRequiredFiles=new Set(Va(u.maintainedDocuments).map(Q));for(let U of k)Cr.has(U.function.name)||j.add(U.function.name);k=fe(k,j),W=!0,g.push({role:"user",content:b}),yield O("benchmark_state_maintenance_required","forcing write/edit/patch after long-horizon document index")}}let C=Sf(u.maintainedDocuments);if(C.length>0&&u.longHorizonStateIntegrityRecoveryCount<Cf){let p=C.map(b=>`${Se(b.path)}: ${b.reason}`).join("; ");u={...u,longHorizonStateIntegrityRecoveryCount:u.longHorizonStateIntegrityRecoveryCount+1,messages:[...g,{role:"user",content:"Your maintained benchmark-state hash files no longer match the tool-derived ground truth: "+p+". The context-pack inputs are read-only and immutable \u2014 the source did NOT change. Restore the exact recorded contentHash/fileSizeBytes; do NOT flip any acceptance verdict on this phantom drift."}],transition:{reason:"next_turn"}},W=!0,yield O("benchmark_state_integrity_required","on-disk benchmark-state hash file contradicts tool-derived ground truth; forcing a correction before completion");continue}if(vf(u)){yield*ne("Maintained benchmark-state files after indexing the context pack. Stopping this turn now because the required document-index.json, decision-state-table.json, and context-pack-evidence.json writes are complete; do not continue into extra writes, context-pack modifications, or repeated reads.");return}}catch(c){let d=c instanceof Error?c.message:String(c);yield*ge(d,"TOOL_EXECUTION_ERROR");return}if(Vt){yield*ne(Vt);return}if(g.push(...ta({toolFailureCounts:u.toolFailureCounts,snapshot:hl})),ml){let c=ze({inputMessages:a,messages:g,reason:`tool call budget exhausted (${pe}) before completing all required files`});if(c){let d=Ze(g,`tool call budget exhausted (${pe})`);yield*ne(`${d}
|
|
59
59
|
|