qlogicagent 2.20.9 → 2.20.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.js +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +316 -321
- package/dist/types/runtime/prompt/capability-routing-policy.d.ts +1 -3
- package/dist/types/runtime/prompt/task-domain.d.ts +8 -31
- package/package.json +6 -6
- package/dist/types/runtime/prompt/fresh-workspace-evidence.d.ts +0 -38
- package/dist/types/runtime/prompt/tool-necessity-policy.d.ts +0 -12
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,Ii=/\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 Di(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function Oi(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function Ni(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+${Hi(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 Li(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=Li(a,vu),i=Li(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);Ii.lastIndex=i;let T;for(;(T=Ii.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=>Di(m[1]??"")).filter(m=>m&&!Oi(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)||Ni(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)||Ni(s,m.index??0,y)||o(`${l}/${y}`)}for(let m of s.matchAll(xu)){let y=m[1];y&&(Oi(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 Bi(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(...Pi(f.input).paths)}}return n}function ar(e){let t=new Set,n=new Map,o=[...Bi(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 $i(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 ji(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=zi(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=Di(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=qi(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=zi(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${Hi(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=$i(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 Ui(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 zi(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 Hi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ze(e){let t=Ui(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 qi(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function Gi(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=qi(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 Wi(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=ji(we(e,t)),s=[];for(let[a,l]of n)(o.includes(a)||r&&Wi(l))&&s.push(a);return s}var Gu="File not found:",Fi=/\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(Fi.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&&Fi.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)||Wi(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")||Bi(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=ji(e.messages),m=Ui(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 Vi(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 Xi(){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 Ki=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 Yi(e){if(!e.tokenBudget||e.tokenBudget<=0)return null;let t=td(e.totalUsage),n=t/e.tokenBudget*100;if(e.budgetContinuationCount>=Ki)return e.log.info(`token budget continuation stop: continuation cap reached (${e.budgetContinuationCount}/${Ki}) at ${Math.round(n)}% used`),fr(e,"cap"),null;let o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=Ds&&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 Ji(e,t,n){let o=[],r=[];for(let s of e){let a=pr(s.function.name,s.function.arguments),l=ta(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 Zi(){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 Qi(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 ea(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 ta(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 ta(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 na(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 oa(e){return e.isRead?!0:e.firstCommand!==null&&fd.has(e.firstCommand)}function ra(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 sa(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 ia=".qlogicagent";function qe(){return process.env.QLOGICAGENT_HOME||oe(Td(),ia)}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 aa(e=bn()){return oe(Tn(e),"memory")}var Cd="projectData";function la(){return oe(qe(),Cd)}function mr(e){if(!e)throw new Error("getProjectDataDirById: projectId is required");return oe(la(),e)}function ca(){return oe(qe(),"plugins")}function ua(){return oe(Tn(),"settings.json")}function da(){return oe(qe(),"plugin-cache")}function fa(){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,ia)}function pa(e){return oe(lt(e),"plugins")}function ga(e){return oe(lt(e),"settings.json")}function ma(e){return oe(lt(e),"INSTRUCTIONS.md")}function ha(e){return oe(lt(e),"rules")}import{resolve as oh}from"node:path";var Rd=()=>{},hr;function ya(){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=ya();return{activeProjectId:e.activeProjectId,projects:e.projects.map(t=>({...t}))}}function ba(e){return _d().projects.find(t=>t.id===e)??null}function Sd(e){return ba(e)?e:gr(e)}function Ad(e){return mr(Sd(e))}function Ta(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 aa(t)}getUserSettingsPath(){return ua()}getUserPluginsDir(){return ca()}getUserPluginCacheDir(){return da()}getUserMarketplaceConfigPath(){return fa()}getProjectAgentDir(t=this.getActiveProjectRoot()){return lt(t)}getProjectSettingsPath(t=this.getActiveProjectRoot()){return ga(t)}getProjectInstructionsPath(t=this.getActiveProjectRoot()){return ma(t)}getProjectPluginsDir(t=this.getActiveProjectRoot()){return pa(t)}getProjectRulesDir(t=this.getActiveProjectRoot()){return ha(t)}getProjectSessionDataRoot(t=this.getActiveProjectRoot()){return Ta(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(a=>a.role==="user");if(!n)return!1;let o=Array.isArray(n.audioUrls)&&n.audioUrls.some(a=>typeof a=="string"&&a.trim()),r=typeof n.content=="string"?n.content:"",s=/\b(?:stt|speech[-\s]?to[-\s]?text|transcribe|transcription|audio[-\s]?to[-\s]?text)\b|转写|转录|语音转文字|音频转文字|听写/i.test(r);return o&&s}function 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 $i(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 ji(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=zi(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=Di(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=qi(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=zi(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${Hi(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=$i(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 Ui(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 zi(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 Hi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ze(e){let t=Ui(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 qi(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function Gi(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=qi(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 Wi(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=ji(we(e,t)),s=[];for(let[a,l]of n)(o.includes(a)||r&&Wi(l))&&s.push(a);return s}var Gu="File not found:",Fi=/\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(Fi.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&&Fi.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)||Wi(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")||Bi(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=ji(e.messages),m=Ui(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 Vi(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 Xi(){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 Ki=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 Yi(e){if(!e.tokenBudget||e.tokenBudget<=0)return null;let t=td(e.totalUsage),n=t/e.tokenBudget*100;if(e.budgetContinuationCount>=Ki)return e.log.info(`token budget continuation stop: continuation cap reached (${e.budgetContinuationCount}/${Ki}) at ${Math.round(n)}% used`),fr(e,"cap"),null;let o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=Ds&&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 Ji(e,t,n){let o=[],r=[];for(let s of e){let a=pr(s.function.name,s.function.arguments),l=ta(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 Zi(){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 Qi(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 ea(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 ta(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 ta(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 na(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 oa(e){return e.isRead?!0:e.firstCommand!==null&&fd.has(e.firstCommand)}function ra(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 sa(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 ia=".qlogicagent";function qe(){return process.env.QLOGICAGENT_HOME||oe(Td(),ia)}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 aa(e=bn()){return oe(Tn(e),"memory")}var Cd="projectData";function la(){return oe(qe(),Cd)}function mr(e){if(!e)throw new Error("getProjectDataDirById: projectId is required");return oe(la(),e)}function ca(){return oe(qe(),"plugins")}function ua(){return oe(Tn(),"settings.json")}function da(){return oe(qe(),"plugin-cache")}function fa(){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,ia)}function pa(e){return oe(lt(e),"plugins")}function ga(e){return oe(lt(e),"settings.json")}function ma(e){return oe(lt(e),"INSTRUCTIONS.md")}function ha(e){return oe(lt(e),"rules")}import{resolve as oh}from"node:path";var Rd=()=>{},hr;function ya(){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=ya();return{activeProjectId:e.activeProjectId,projects:e.projects.map(t=>({...t}))}}function ba(e){return _d().projects.find(t=>t.id===e)??null}function Sd(e){return ba(e)?e:gr(e)}function Ad(e){return mr(Sd(e))}function Ta(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 aa(t)}getUserSettingsPath(){return ua()}getUserPluginsDir(){return ca()}getUserPluginCacheDir(){return da()}getUserMarketplaceConfigPath(){return fa()}getProjectAgentDir(t=this.getActiveProjectRoot()){return lt(t)}getProjectSettingsPath(t=this.getActiveProjectRoot()){return ga(t)}getProjectInstructionsPath(t=this.getActiveProjectRoot()){return ma(t)}getProjectPluginsDir(t=this.getActiveProjectRoot()){return pa(t)}getProjectRulesDir(t=this.getActiveProjectRoot()){return ha(t)}getProjectSessionDataRoot(t=this.getActiveProjectRoot()){return Ta(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]
|
|
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)=>ka(a.reason)-ka(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 ka(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 Ca(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 Ra(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 xa(e){let n=Te(e)?.command;return typeof n=="string"&&n.trim()?n:void 0}var vn=5174;function _a(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 Ua(e){return/(?:^|\s)--strictPort(?:\s|$)/.test(e)}function Vd(e){if(Ua(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 va(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 _a(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)&&_a(e,vn-1)&&!Ua(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)}
|