@xenosystem/agent-sdk 0.10.41 → 0.10.43

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.
@@ -1,33 +1,27 @@
1
- "use strict";var C=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var ce=Object.prototype.hasOwnProperty;var le=(t,e)=>{for(var n in e)C(t,n,{get:e[n],enumerable:!0})},ue=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of oe(e))!ce.call(t,r)&&r!==n&&C(t,r,{get:()=>e[r],enumerable:!(i=ae(e,r))||i.enumerable});return t};var de=t=>ue(C({},"__esModule",{value:!0}),t);var Dt={};le(Dt,{ExecutionGovernance:()=>p,InteractiveChatTurnGovernance:()=>A,InteractiveTurnGovernance:()=>h,buildContractLedgerGuidance:()=>k,buildProjectBudgetFinalizationGuidance:()=>W,buildProjectExecutionGuidance:()=>E,buildProjectExecutionProfile:()=>x,createBenchBashMiddleware:()=>S,createGovernanceExtensions:()=>jt,isExplicitResearchPrompt:()=>_,isSimpleInformationalPrompt:()=>w,resolveInteractiveTurnMaxIterations:()=>ie,shouldEnableExecutionGovernance:()=>y});module.exports=de(Dt);var me=/(?:[A-Za-z]:\\[^\s"'`<>|]+|\/[^\s"'`<>|]+)/g,he=[/\bwrite\s+(?:the\s+)?(?:output|result|answer|contents?|solution)\s+to\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\bsave\s+(?:it|them|your\s+solution|the\s+(?:output|result|answer|solution|model|file|artifact))?\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\b(?:create|place)\s+(?:a\s+file\s+(?:called|named)|the\s+file)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\b(?:must|should|needs?\s+to)\s+be\s+(?:saved|written|placed|stored)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\bfinal\s+(?:model|output|artifact|answer|solution)\s+(?:needs?\s+to|should|must)\s+be\s+saved\s+as\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/i,/\b(?:at|in)\s+(?:"|'|`)?((?:\/app|\/workspace|\/tmp|\.{1,2}\/)[^\s"'`]+)(?:"|'|`)?\s+(?:containing|with\s+the\s+(?:answer|result|solution))/i],pe=/(?:"([^"\n]{4,240})"|'([^'\n]{4,240})'|`([^`\n]{4,240})`)/g,fe=/(?:^|\n)\s*(?:\$?\s*)?(uv run|python3?|pytest|npm|pnpm|yarn|cargo|make|cmake|ninja|gcc|g\+\+|clang|go|rustc|sqlite3|ffmpeg|openssl|qemu-system-[\w-]+|curl|ssh|git|docker|bash|sh)\b[^\n]{0,220}/gi,ge=/\b(?:at\s+least|at\s+most|less\s+than|more\s+than|greater\s+than|under|over|within|max(?:imum)?|min(?:imum)?|accuracy|score|valid\s+for|size|runtime|timeout|precision|recall|f1|rmse|mae)\b[^\n.;:]{0,120}\d+(?:\.\d+)?\s*(?:%|mb|gb|kb|bytes?|s|sec(?:onds?)?|ms|days?|years?|accuracy|score)?/gi,be=[{name:"ML/model artifact",pattern:/\b(?:model|weights?|checkpoint|ckpt|onnx|torch|pytorch|tensorflow|keras|fasttext|embedding|inference|prediction|logits?|classif(?:y|ication)|train(?:ing)?|accuracy|gpt-?2|tokeni[sz]er)\b/i,checks:["validate on multiple representative samples or a holdout, not one smoke input","reject constant, hard-coded, or one-sample inference stubs unless the task explicitly proves they are valid","verify artifact size, invocation, preprocessing, label order, and output schema together"]},{name:"visual/video/geometry",pattern:/\b(?:image|video|frame|opencv|cv2|ffmpeg|ocr|render|pixel|sprite|gcode|g-code|path\s*tracing|ray\s*tracing|camera|toml|move\s+extraction)\b/i,checks:["derive answers from pixels, frames, geometry, or rendered previews instead of filenames or comments","use at least two independent views when possible, such as numeric analysis plus preview inspection","for exact tokens or flags, verify the final text byte-for-byte before finishing"]},{name:"compiler/emulator/build",pattern:/\b(?:compile|compiler|cross-?compile|gcc|clang|cargo|rustc|make|cmake|ninja|mips|riscv|x86|arm|kernel|qemu|emulator|interpreter|assembly|linker|windows\s+3\.11|doom)\b/i,checks:["split build, run, and verifier phases, each with bounded logs and explicit success criteria","keep the final runnable artifact or service state after the last positive check","if full builds are expensive, run narrow syntax/unit checks before the full verifier-shaped command"]},{name:"symbolic/search/optimization",pattern:/\b(?:regex|regular expression|solver|constraint|backtracking|search|codegolf|shortest|smallest|optimi[sz]e|fibonacci|circuit|sat|smt|brute\s*force)\b/i,checks:["build a small independent verifier or counterexample generator before optimizing","checkpoint the current best valid candidate to the required output path before long searches","treat near-threshold wins as failures unless repeated checks show a clear margin"]},{name:"data integrity/conversion",pattern:/\b(?:csv|tsv|parquet|jsonl?|dataset|dataframe|reshard|compress|decompress|wal|sqlite|database|token(?:s|i[sz]e)?)\b/i,checks:["compare row counts, ordering, schema, nulls, and exact byte or cell values where relevant","validate by reading the produced artifact back, not only by checking that files exist","preserve required final files after temporary validation cleanup"]},{name:"service/VM/network",pattern:/\b(?:server|service|daemon|webserver|http|https|localhost|port\s+\d+|ssh|sshd|qemu|vm|virtual\s+machine|container)\b/i,checks:["poll readiness and verify the exact final client command, including auth and content","leave required long-running services or VMs alive in the final state","an open port alone is not a pass; verify the protocol-level contract"]},{name:"security/sanitization",pattern:/\b(?:xss|sanitize|html|javascript|script|payload|exploit|decrypt|archive|hash|password|secret|certificate|openssl)\b/i,checks:["test both positive and negative/adversarial cases, including idempotence when preserving clean input matters","do not write guesses or placeholders into required answer files","verify final artifacts with format-specific tools where available"]},{name:"science/numeric/bio",pattern:/\b(?:dna|protein|genome|melting|tm\b|raman|spectrum|fit|curve|simulation|molecule|assembly)\b/i,checks:["measure the exact numeric constraints the prompt states and keep safety margin beyond thresholds","run validation on the final submitted artifact, not an intermediate candidate","if stochastic search is used, save the best validated candidate before continuing"]},{name:"binary/ELF/recovery",pattern:/\b(?:elf|binary|disassembl|objdump|readelf|segment|memory|recovery|reverse\s*engineer)\b/i,checks:["parse the file format generically and validate against header/segment metadata","confirm address formats, endian handling, and value types match the required output","test on a second generated or varied sample when possible"]}];function D(t){return t.trim().replace(/^[`'"]+|[`'"]+$/g,"").replace(/[.,;:)\]]+$/g,"").trim()}function q(t){return t.length===0||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("//")}function b(t,e){let n=[],i=new Set;for(let r of t){let s=r.trim();if(!(!s||i.has(s))&&(i.add(s),n.push(s),n.length>=e))break}return n}function ve(t){let e=[];for(let n of he){let i=new RegExp(n.source,n.flags.includes("g")?n.flags:`${n.flags}g`),r;for(;(r=i.exec(t))!==null;){let s=r[1]?D(r[1]):"";q(s)||e.push(s)}}return b(e,8)}function ye(t,e){let n=new Set(e),i=t.match(me)??[];return b(i.map(r=>D(r)).filter(r=>!q(r)&&!n.has(r)),8)}function we(t){let e=[],n;for(;(n=pe.exec(t))!==null;){let i=(n[1]??n[2]??n[3]??"").trim();i&&(/^(?:\/|[A-Za-z]:\\|\.\.?\/)/.test(i)||/^(?:python|npm|uv|cargo|make|curl|ssh|git|docker)\b/i.test(i)||e.push(i.length>96?`${i.slice(0,93)}...`:i))}return b(e,6)}function ke(t){let e=[],n;for(;(n=fe.exec(t))!==null;){let i=n[0].replace(/^\s*\$?\s*/,"").trim();i.length>0&&e.push(i.length>140?`${i.slice(0,137)}...`:i)}return b(e,6)}function Re(t){let e=[],n;for(;(n=ge.exec(t))!==null;)e.push(n[0].replace(/\s+/g," ").trim());return b(e,6)}function xe(t){return be.filter(e=>e.pattern.test(t)).slice(0,5)}function j(t){return/\b(?:terminal-bench|benchmark|verifier|hidden tests?|run-tests\.sh|live benchmark task container|\/app)\b/i.test(t)}function k(t){let e=t?.trim()??"";if(!e)return"";let n=ve(e),i=ye(e,n),r=we(e),s=ke(e),a=Re(e),o=xe(e);if(n.length===0&&i.length===0&&r.length===0&&s.length===0&&a.length===0&&o.length===0&&!j(e))return"";let c=["","","# Contract Ledger","- Before implementation, maintain a mental or written ledger of the required final artifacts, exact outputs, thresholds, and verifier-shaped commands.","- Update the ledger when new evidence appears. Do not finish until every ledger item has direct evidence from the final submitted state."];n.length>0&&c.push(`- Required output artifacts: ${n.join(", ")}`),i.length>0&&c.push(`- Mentioned input/reference paths: ${i.join(", ")}`),r.length>0&&c.push(`- Exact literal candidates to preserve byte-for-byte: ${r.join(" | ")}`),a.length>0&&c.push(`- Numeric or policy thresholds to measure directly: ${a.join(" | ")}`),s.length>0&&c.push(`- Prompt-provided command shapes to honor or emulate: ${s.join(" | ")}`),o.length>0&&c.push(`- Risk domains detected: ${o.map(d=>d.name).join(", ")}`),c.push("","# Adversarial Verification","- Treat file existence, one happy-path sample, a self-written smoke test, or a plausible-looking artifact as insufficient evidence.","- Build hidden-test-like checks: multiple samples, malformed/adversarial inputs, round trips, byte-level reads, schema checks, process-level invocation, or exact verifier commands as appropriate.","- Run checks against the final submitted artifact or final live service state, not only against an intermediate candidate.","- If validation is ambiguous, below threshold, near threshold, or only passes because of a narrow stub, keep working or explicitly mark the task incomplete instead of claiming success."),j(e)&&c.push("- In benchmark containers, do not declare SELF_CHECK_PASS until the required files or services survive final cleanup and at least one verifier-shaped check passes.");for(let d of o)c.push(`- ${d.name}: ${d.checks.join("; ")}.`);return c.join(`
2
- `)}var Ee=/(?:[A-Za-z]:\\[^\s"'`<>|]+|\/[^\s"'`<>|]+)/g,Te=[/\b(?:save|write|place|store)\s+(?:the\s+)?(?:output|result|answer|solution|model|artifact|file|contents?)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:save|write|place|store)\s+(?:the\s+)?final\s+(?:output|result|answer|solution|model|artifact|file)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:create|place)\s+(?:a\s+file\s+(?:called|named)|the\s+file)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:write|create|implement)\s+(?:a\s+)?(?:C|C\+\+|Python|Rust|Go|JavaScript|TypeScript|shell|bash)?\s*(?:source\s+)?(?:program|script|implementation|module|file|code)\s+(?:at|as|in|to)?\s*(?:"|'|`)?((?:\/|\.{1,2}[\\/]|[A-Za-z0-9_.-]+[\\/])[^\s"'`]+|[A-Za-z0-9_.-]+\.(?:c|cc|cpp|h|hpp|py|js|ts|tsx|sh|rs|go|java|rb|pl|php|json|xml|tex|sql|vim))(?:"|'|`)?/gi,/\b(?:must|should|needs?\s+to)\s+be\s+(?:saved|written|placed|stored)\s+(?:as|to|in)\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\bfinal\s+(?:model|output|artifact|answer|solution)\s+(?:needs?\s+to|should|must)\s+be\s+saved\s+as\s+(?:"|'|`)?([^\s"'`]+)(?:"|'|`)?/gi,/\b(?:file|path)\s+(?:"|'|`)?((?:\/app|\/workspace|\/tmp|\.{1,2}\/)[^\s"'`]+)(?:"|'|`)?\s+(?:must|should|needs?\s+to|containing|with)\b/gi],Ae=[{key:"ml_artifact",label:"ML/model artifact",trigger:/\b(?:model|weights?|checkpoint|ckpt|onnx|torch|pytorch|tensorflow|keras|fasttext|embedding|inference|prediction|logits?|classif(?:y|ication)|train(?:ing)?|accuracy|loss|gpt-?2|tokeni[sz]er|vocab|bpe)\b/i,verifierRequirements:["inspect model, weight, tokenizer, preprocessing, label-order, and entrypoint schema before wrapping it","validate multiple representative samples or known labels; one smoke input is not enough","when provided artifacts exist, prove dependency by loading/schema-checking or mutation/removal changing outputs","for distributed/tensor-parallel code, run the actual multiprocess/world-size verifier shape instead of only syntax or static checks"],finalAuditItems:["final model or wrapper loads from the submitted path","final invocation uses provided weights/tokenizers instead of constants","metric or known-output evidence is recorded against the final artifact"]},{key:"visual_artifact",label:"visual/video/geometry artifact",trigger:/\b(?:image|video|frame|opencv|cv2|ffmpeg|ocr|render|raster|pixel|sprite|gcode|g-code|path\s*tracing|ray\s*tracing|camera|toml|move\s+extraction|mask|segmentation|pdf|invoice|document)\b/i,verifierRequirements:["derive answers from rendered pixels, frame samples, geometry, OCR, or simulation rather than filenames/comments","use two independent views for exact text, coordinates, masks, or temporal outputs","read generated images, CSVs, PDFs, or media outputs back through the same shape the verifier will inspect"],finalAuditItems:["submitted visual/document/media artifact exists at the required path","second-pass content check agrees with the final output","temporary previews did not replace or remove the final deliverable"]},{key:"structured_data",label:"structured data or script output",trigger:/\b(?:csv|tsv|parquet|arrow|jsonl?|dataframe|table|schema|columns?|rows?|coords_[xy]|metadata|reshard|compress|decompress|output_path)\b/i,verifierRequirements:["run the submitted script or converter end-to-end, then read the generated artifact back","assert row count, column order, scalar/list field types, nulls, dtypes, and exact value preservation","for conversions, compare source and produced artifact with dataframe or byte-level equality where relevant"],finalAuditItems:["final generated artifact has the required schema and parseable fields","clean/reference inputs were not overwritten unless explicitly required","single-file deliverables contain only expected final content"]},{key:"performance",label:"performance or optimization",trigger:/\b(?:optimi[sz]e|faster|speed\s*up|runtime|latency|throughput|benchmark|profile|median|p95|under\s+\d+(?:\.\d+)?\s*(?:ms|s|sec|seconds?|min|minutes?)|accuracy|score)\b/i,verifierRequirements:["measure a baseline before optimizing and compare against the final candidate","use bounded warmed runs with medians or thresholds instead of one noisy timing","inspect relevant plans/profiles and reject changes that only preserve correctness while losing the target metric"],finalAuditItems:["best measured candidate is written to the required path","metric evidence has clear margin beyond the threshold","no long benchmark loop is still running in the final state"]},{key:"compiler_emulator",label:"compiler, emulator, or cross-architecture",trigger:/\b(?:compile|compiler|cross-?compile|gcc|clang|cargo|rustc|make|cmake|ninja|mips|riscv|x86|arm|kernel|qemu|emulator|interpreter|polyglot|doom|windows\s+3\.11|assembly|linker)\b/i,verifierRequirements:["identify the exact target toolchain and verifier command first","run a small compile/run smoke before expensive full builds","leave the final runnable artifact, VM, or emulator state after the last positive check"],finalAuditItems:["final binary/script/service starts with the verifier-shaped command","logs show the latest build/run result, not an old intermediate","background VM/emulator/service remains alive when the task requires post-run access"]},{key:"service_vm",label:"service, VM, network, or SSH",trigger:/\b(?:server|service|daemon|webserver|http|https|localhost|port\s+\d+|ssh|sshd|git\s+(?:server|clone|push)|grpc|protobuf|proto\b|rpc|request|response|client|qemu|vm|virtual\s+machine|container|socket|telnet|serial|monitor\s+socket|qmp|sendkey)\b/i,verifierRequirements:["separate setup, readiness polling, final client command, and cleanup into bounded phases","verify the exact user/verifier client command including auth, content, and protocol behavior","for gRPC/protobuf/RPC work, instantiate generated request messages with required fields and call every required RPC through a real client","for VM/QEMU work, verify monitor/QMP/serial control surfaces and expected framebuffer or service behavior, not screenshots alone","keep only required long-lived processes in the background and preserve logs"],finalAuditItems:["final service or VM is running if the verifier connects after completion","last positive client check happened after cleanup/negative tests","open port is backed by protocol-level success, not only socket readiness","protocol schemas, request fields, response fields, and VM control sockets match the verifier contract when applicable"]},{key:"search_symbolic",label:"search, symbolic, regex, or code-size",trigger:/\b(?:regex|regular expression|solver|constraint|backtracking|search|codegolf|shortest|smallest|fibonacci|circuit|sat|smt|brute\s*force|decompress|codec|round\s*trip)\b/i,verifierRequirements:["build a correctness oracle or counterexample generator before optimizing size or speed","checkpoint the best valid candidate to the required output before long searches","for regex/chess/legal-move tasks, compare against an independent oracle such as python-chess across provided PGN/FEN fixtures","cap search loops and pivot after repeated failures in the same direction"],finalAuditItems:["current best valid candidate is preserved at the submission path","randomized or adversarial fixtures ran against the final candidate","no known counterexample from the latest check remains unresolved"]},{key:"security_sanitization",label:"security, sanitization, archive, or certificate",trigger:/\b(?:xss|sanitize|html|javascript|script|payload|exploit|decrypt|archive|7z|zip|rar|hash|password|secret|credential|token|leak|git\s+repo|repository\s+cleanup|diff\s+scope|certificate|openssl|pem|tls)\b/i,verifierRequirements:["test harmful and clean/idempotent cases through the submitted entrypoint","use format-specific tooling before broad guessing for archives, hashes, and certificates","avoid regex-only sanitizers when parser or allowlist behavior is required","for repository secret cleanup, scan for remaining secrets and audit changed paths against the contaminated/allowed file set"],finalAuditItems:["clean inputs remain semantically unchanged when required","harmful/adversarial inputs are blocked by the final artifact","placeholder outputs such as UNKNOWN or TODO are absent","repository diff scope contains no unrelated clean-file modifications when the task asks for surgical cleanup"]},{key:"science_bio_numeric",label:"science, biosequence, or numeric fitting",trigger:/\b(?:dna|primer|protein|genome|melting|tm\b|oligotm|raman|spectrum|fit|curve|simulation|molecule|assembly|mjcf|robot)\b/i,verifierRequirements:["measure every stated numeric constraint using the specified calculator or an equivalent exact implementation","keep safety margin beyond hard thresholds and rerun validation on the final submitted artifact","for biological assembly, verify orientation, overhangs, circularity, translation, and sequence order end-to-end"],finalAuditItems:["final sequence/numeric file passes exact threshold calculations","no intermediate candidate is mistaken for the final artifact","round-trip or reconstruction checks cover the complete intended product"]},{key:"binary_recovery",label:"binary/ELF/recovery",trigger:/\b(?:elf|binary|disassembl|objdump|readelf|segment|memory|address|endianness|reverse\s*engineer)\b/i,verifierRequirements:["parse file-backed bytes and metadata, not only loader-expanded memory","validate address formats, endian handling, p_filesz/p_memsz boundaries, and exact JSON/value types","test on a second generated or varied sample when possible"],finalAuditItems:["final parser reads the required input file directly","output values match declared numeric/string formats","metadata and data-region boundary cases are covered"]},{key:"async_process",label:"async, signal, or process cleanup",trigger:/\b(?:async|asyncio|signal|sigterm|sigint|interrupt|cancel(?:lation)?|cleanup|terminate|shutdown|background\s+process|worker|taskgroup|semaphore)\b/i,verifierRequirements:["exercise the real interruption, signal, cancellation, or shutdown path through the submitted entrypoint","assert cleanup markers, drained finalizers, process termination, and exit behavior","include boundary cases around queued work or concurrency limits when mentioned"],finalAuditItems:["final entrypoint handles the same signal path the verifier will call","cleanup evidence comes from the submitted artifact, not only the validation harness","no orphaned process remains unless it is the required final service"]}];function $(t){return t.trim().replace(/^[`'"]+|[`'"]+$/g,"").replace(/[.,;:)\]]+$/g,"").trim()}function U(t){return!!(!t||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("//"))}function R(t,e){let n=[],i=new Set;for(let r of t){let s=r.trim();if(!(!s||i.has(s))&&(i.add(s),n.push(s),n.length>=e))break}return n}function _e(t){let e=[];for(let n of Te){let i;for(;(i=n.exec(t))!==null;){let r=$(i[1]??"");U(r)||e.push(r)}}return R(e,10)}function Se(t,e){let n=new Set(e),i=t.match(Ee)??[];return R(i.map($).filter(r=>!U(r)&&!n.has(r)),10)}function Ce(t){return Ae.filter(e=>e.trigger.test(t)).slice(0,6)}function V(t){return/\b(?:terminal-bench|benchmark|hidden tests?|verifier|\/tests|test\.sh|run-tests\.sh|\/app)\b/i.test(t)}function Ie(t,e,n){return e.length>0||n.length>0||V(t)?!0:/\b(?:implement|fix|build|create|write|debug|optimi[sz]e|train|configure|recover|extract|convert|process|validate)\b/i.test(t)}function Pe(t,e){let n=t.some(r=>r.key==="ml_artifact"||r.key==="compiler_emulator"||r.key==="service_vm"||r.key==="search_symbolic"||r.key==="science_bio_numeric"),i=e||t.some(r=>r.key==="structured_data"||r.key==="visual_artifact"||r.key==="security_sanitization"||r.key==="binary_recovery"||r.key==="async_process");return n?[{name:"inspect",budgetPercent:15,objective:"extract the acceptance contract, toolchain, inputs, and verifier path before touching expensive work"},{name:"baseline",budgetPercent:15,objective:"create the smallest runnable baseline or measurement harness and write a checkpoint if an output path exists"},{name:"implement",budgetPercent:40,objective:"iterate on the candidate while keeping work bounded and evidence-driven"},{name:"validate",budgetPercent:20,objective:"run verifier-shaped checks against the final candidate and fix concrete failures only"},{name:"finalize",budgetPercent:10,objective:"restore final state, remove accidental temp artifacts, and preserve required outputs/services"}]:i?[{name:"inspect",budgetPercent:20,objective:"extract required outputs, fixtures, schema, and hidden-verifier assumptions"},{name:"baseline",budgetPercent:15,objective:"produce a narrow runnable baseline and a failing/passing local oracle"},{name:"implement",budgetPercent:35,objective:"implement the simplest general solution that satisfies the oracle"},{name:"validate",budgetPercent:20,objective:"read back artifacts and run adversarial, round-trip, or protocol checks"},{name:"finalize",budgetPercent:10,objective:"ensure the final filesystem/process state is exactly what the user or verifier will inspect"}]:[{name:"inspect",budgetPercent:20,objective:"understand the requested final state and available tests"},{name:"baseline",budgetPercent:10,objective:"make a small working baseline or reproduce the issue"},{name:"implement",budgetPercent:40,objective:"make the targeted change"},{name:"validate",budgetPercent:20,objective:"run the most relevant tests against the final state"},{name:"finalize",budgetPercent:10,objective:"clean temporary state and report only after validation"}]}function x(t){let e=t?.trim()??"",n=_e(e),i=Se(e,n),r=Ce(e),s=V(e),a=Ie(e,n,r),o=Pe(r,s),c=R([s?"check /tests, /test.sh, /run-tests.sh, README/instruction files, and prompt-provided commands early; if hidden, synthesize a contract-matched self-check":"look for existing tests or task-provided commands before writing custom checks",n.length>0?"write or preserve the best current candidate at each required output path before long-running work":"if a final artifact emerges, keep it in a stable path and validate that path","after any failed verifier/self-check, fix the first concrete failure and rerun the same check until a later passing signal supersedes it",...r.flatMap(m=>m.verifierRequirements)],12),d=R([...n.map(m=>`required output exists, is non-empty when applicable, and was read back: ${m}`),"latest validation ran after the last write to the submitted artifact","no known failed verifier, self-check, diff, build, or runtime signal remains unresolved","final filesystem/process state matches what the user or verifier will inspect after the agent exits",...r.flatMap(m=>m.finalAuditItems)],14);return{projectLike:a,hiddenVerifierLikely:s,requiredOutputs:n,referencedPaths:i,domains:r,phases:o,verifierRequirements:c,finalAuditItems:d}}function E(t){let e=x(t);if(!e.projectLike)return"";let n=["","","# Project Execution Board","- Treat non-trivial coding/terminal work as a project with phases, a live contract, a current best candidate, and explicit final-state proof.","- Do not optimize for appearing done. Optimize for the final filesystem, process, service, or artifact state a verifier/user will inspect.",`- Phase budget: ${e.phases.map(i=>`${i.name} ${i.budgetPercent}%`).join(" -> ")}.`];for(let i of e.phases)n.push(`- ${i.name}: ${i.objective}.`);return e.requiredOutputs.length>0&&n.push(`- Required outputs to preserve early: ${e.requiredOutputs.join(", ")}.`),e.referencedPaths.length>0&&n.push(`- Reference/input paths to avoid overwriting unless required: ${e.referencedPaths.join(", ")}.`),e.domains.length>0&&n.push(`- Domain kits active: ${e.domains.map(i=>i.label).join(", ")}.`),n.push("","# Verifier Synthesis",...e.verifierRequirements.map(i=>`- ${i}.`),"","# Final-State Auditor",...e.finalAuditItems.map(i=>`- ${i}.`)),n.join(`
3
- `)}function W(t){let e=x(t);if(!e.projectLike)return"";let n=e.domains.map(i=>i.label).join(", ");return["","[Project final-state audit]","You are now in validate/finalize mode, not exploration mode.",e.requiredOutputs.length>0?`Required output paths must already contain the best current candidate: ${e.requiredOutputs.join(", ")}.`:"If a final artifact/service exists, preserve the best current candidate before additional checks.",n?`Active domain risk kits: ${n}.`:"Use the general final-state audit.","Rerun only bounded verifier-shaped checks that target concrete unresolved failures.","Do not start a new long training/build/search/exploration loop unless it directly repairs the latest failing check.","Before the final answer, ensure the latest validation happened after the last artifact write and no known failing signal remains unresolved."].join(`
4
- `)}var T={official:6,project:5,user:4,self:3,smoke:2,syntax:1},z=/\b(?:pytest|py\.test|unittest|npm\s+(?:test|run\s+test)|pnpm\s+(?:test|run\s+test)|yarn\s+test|cargo\s+test|go\s+test|make\s+(?:test|check)|ctest|run-tests?\.sh|test\.sh|verifier|verify|check)\b/i,Ne=/(?:^|\s)(?:\/tests\b|\/run-tests\.sh\b|\.\/run-tests?\.sh\b|\.\/test\.sh\b|test_outputs\.py\b|official\s+verifier|hidden\s+tests?|verifier\b)/i,P=/\b(?:SELF_CHECK|CONTRACT|READBACK|ROUNDTRIP|SCHEMA|VALIDATION|VERIFIER)[_-]?(?:PASS|FAIL|FAILED|ERROR)\b/i,Le=/(?:^|\s)(?:cat\s+>|tee\b|cp\b|mv\b|rm\b|touch\b|mkdir\b|sed\b.*\s-i\b|patch\b|apply_patch\b|npm\s+install|pip\s+install)\b|[>]{1,2}|\b(?:writeFileSync|open\s*\([^)]*,\s*["']w|Path\([^)]*\)\.write_text)\b/i,G=[/\bFAILED\b/i,/\bFAILURES?\b/i,/\bAssertionError\b/i,/\bTraceback \(most recent call last\)/i,/\b(?:RuntimeError|ValueError|TypeError|SyntaxError|ModuleNotFoundError|ImportError)\b/i,/\b(?:mismatch|differs?|wrong output|does not match|not equal|not equivalent)\b/i,/\b(?:exit|status|return code|returncode)\s*[:=]?\s*[1-9]\d*\b/i,/\btimed?\s*out\b|\btimeout\b/i],Me=[/\b(?:all\s+tests?\s+passed|all\s+checks?\s+passed|verifier\s+passed|validation\s+passed)\b/i,/\b(?:SELF_CHECK|CONTRACT|READBACK|ROUNDTRIP|SCHEMA|VALIDATION|VERIFIER)[_-]?PASS\b/i,/\b(?:0\s+failed|no\s+failures?|passed)\b/i,/\b(?:SUCCESS|successful|verified)\b/i];function Fe(t,e=500){return t.replace(/\r\n/g,`
5
- `).replace(/[ \t]+$/gm,"").trim().slice(0,e)}function Oe(t){return t.toLowerCase().replace(/\b0x[0-9a-f]+\b/g,"0x").replace(/\b\d+(?:\.\d+)?\b/g,"#").replace(/\s+/g," ").trim().slice(0,160)}function v(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function je(t,e,n){let i=v(e)??"";return/^Bash$/i.test(t)&&z.test(i)||/^TaskOutput$/i.test(t)&&(z.test(n)||P.test(n))?!0:P.test(n)}function De(t,e,n){let i=v(e)??"",r=`${i}
6
- ${n}`;return Ne.test(r)?"official":/\b(?:pytest|npm\s+(?:test|run\s+test)|pnpm\s+(?:test|run\s+test)|yarn\s+test|cargo\s+test|go\s+test|make\s+(?:test|check)|ctest)\b/i.test(i)?"project":P.test(r)||/\bself[-_ ]?check\b/i.test(r)?"self":/\b(?:syntax|compile|lint|import)\b/i.test(r)?"syntax":/^Bash$/i.test(t)?"user":"smoke"}function qe(t){let e,n,i=t.match(/(?:^|\s)(\d+)\s+failed\b/i),r=t.match(/(?:^|\s)(\d+)\s+passed\b/i);return i&&(e=Number.parseInt(i[1],10)),r&&(n=Number.parseInt(r[1],10)),{failed:e,passed:n}}function $e(t,e){let n=t.replace(/\r\n/g,`
1
+ "use strict";var _=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var ce=Object.prototype.hasOwnProperty;var ue=(t,e)=>{for(var n in e)_(t,n,{get:e[n],enumerable:!0})},de=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of le(e))!ce.call(t,i)&&i!==n&&_(t,i,{get:()=>e[i],enumerable:!(s=ae(e,i))||s.enumerable});return t};var he=t=>de(_({},"__esModule",{value:!0}),t);var ht={};ue(ht,{ExecutionGovernance:()=>f,InteractiveChatTurnGovernance:()=>w,InteractiveTurnGovernance:()=>h,MAX_HOST_WEB_FETCHES_PER_TURN:()=>Y,MAX_HOST_WEB_SEARCHES_PER_TURN:()=>K,buildContractLedgerGuidance:()=>te,buildProjectBudgetFinalizationGuidance:()=>se,buildProjectExecutionGuidance:()=>ne,buildProjectExecutionProfile:()=>ie,createBenchBashMiddleware:()=>oe,createGovernanceExtensions:()=>dt,createRemoteEvalGuard:()=>b,findMissingRequiredOutputs:()=>A,isExplicitResearchPrompt:()=>y,isRemoteEvalCommand:()=>O,isSimpleInformationalPrompt:()=>v,parseWebResearchBudget:()=>Z,resolveInteractiveTurnMaxIterations:()=>ee,shouldEnableExecutionGovernance:()=>re});module.exports=he(ht);var E=require("node:fs"),T=require("node:path");function A(t,e=process.cwd()){let n=[];for(let s of t){let i=(0,T.isAbsolute)(s)?s:(0,T.resolve)(e,s);try{let r=(0,E.statSync)(i);r.isDirectory()?(0,E.readdirSync)(i).length===0&&n.push({path:s,problem:"empty"}):r.isFile()?r.size===0&&n.push({path:s,problem:"empty"}):n.push({path:s,problem:"not_a_file"})}catch{n.push({path:s,problem:"missing"})}}return n}var R={official:6,project:5,user:4,self:3,smoke:2,syntax:1},M=/\b(?:pytest|py\.test|unittest|npm\s+(?:test|run\s+test)|pnpm\s+(?:test|run\s+test)|yarn\s+test|cargo\s+test|go\s+test|make\s+(?:test|check)|ctest|run-tests?\.sh|test\.sh|verifier|verify|check)\b/i,C=/\b(?:SELF_CHECK|CONTRACT|READBACK|ROUNDTRIP|SCHEMA|VALIDATION|VERIFIER)[_-]?(?:PASS|FAIL|FAILED|ERROR)\b/i,D=/(?:^|\s)(?:cat\s+>|tee\b|cp\b|mv\b|rm\b|touch\b|mkdir\b|sed\b.*\s-i\b|patch\b|apply_patch\b|npm\s+install|pip\s+install)\b|[>]{1,2}|\b(?:writeFileSync|open\s*\([^)]*,\s*["']w|Path\([^)]*\)\.write_text)\b/i,U=[/\bFAILED\b/i,/\bFAILURES?\b/i,/\bAssertionError\b/i,/\bTraceback \(most recent call last\)/i,/\b(?:RuntimeError|ValueError|TypeError|SyntaxError|ModuleNotFoundError|ImportError)\b/i,/\b(?:mismatch|differs?|wrong output|does not match|not equal|not equivalent)\b/i,/\b(?:exit|status|return code|returncode)\s*[:=]?\s*[1-9]\d*\b/i,/\btimed?\s*out\b|\btimeout\b/i],me=[/\b(?:all\s+tests?\s+passed|all\s+checks?\s+passed|verifier\s+passed|validation\s+passed)\b/i,/\b(?:SELF_CHECK|CONTRACT|READBACK|ROUNDTRIP|SCHEMA|VALIDATION|VERIFIER)[_-]?PASS\b/i,/\b(?:0\s+failed|no\s+failures?|passed)\b/i,/\b(?:SUCCESS|successful|verified)\b/i];function pe(t,e=500){return t.replace(/\r\n/g,`
2
+ `).replace(/[ \t]+$/gm,"").trim().slice(0,e)}function fe(t){return t.toLowerCase().replace(/\b0x[0-9a-f]+\b/g,"0x").replace(/\b\d+(?:\.\d+)?\b/g,"#").replace(/\s+/g," ").trim().slice(0,160)}function p(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function I(t){return t.replace(/\d*>&\d+|&>\s*\/dev\/null|\d*>>?\s*\/dev\/null/g," ").replace(/-(?:o|-output)\s+\/dev\/null/g," ")}var ge=new Set(["ls","ll","dir","pwd","cd","echo","printf","cat","head","tail","less","more","wc","stat","file","find","grep","egrep","fgrep","rg","which","whereis","type","command","test","[","true","env","printenv","id","whoami","date","tree","du","df","ps","sort","uniq","cut","awk","sed","tr","set"]);function be(t){let e=I(t).split(/&&|\|\||;|\||\n/).map(n=>n.trim()).filter(n=>n.length>0);return e.length===0?!1:e.some(n=>{let i=(n.replace(/^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/,"").split(/\s+/)[0]??"").replace(/^.*\//,"");return i.length>0&&!ge.has(i)})}function W(t){return t.replace(/\s+/g," ").trim()}function ve(t,e){let n=W(t);return n.length>=12&&W(e).includes(n)}function Re(t,e,n){let s=p(e)??"";return/^Bash$/i.test(t)&&M.test(s)||/^TaskOutput$/i.test(t)&&(M.test(n)||C.test(n))?!0:C.test(n)}var Ee=/(?:^|[;&|(]\s*|(?<![\w./-])(?:bash|sh|zsh|source|exec|env|timeout\s+\S+)\s+(?:-\S+\s+)*)(?:\.\/|\/)?(?:[\w.-]+\/)*(?:run-tests?\.sh|test\.sh)\b|\b(?:pytest|py\.test|python3?\s+-m\s+pytest)\b[^;&|\n]*(?:\/tests?\b|\btest_outputs\.py\b)/i;function Te(t,e,n){let s=p(e)??"",i=`${s}
3
+ ${n}`;return Ee.test(s)?"official":/\b(?:pytest|py\.test|python3?\s+-m\s+unittest|unittest\s+discover|npm\s+(?:test|run\s+test)|pnpm\s+(?:test|run\s+test)|yarn\s+test|bun\s+test|vitest|jest|cargo\s+test|go\s+test|make\s+(?:test|check)|ctest|mvn\s+test|gradle\s+test|dotnet\s+test)\b/i.test(s)?"project":C.test(i)||/\bself[-_ ]?check\b/i.test(i)?"self":/\b(?:syntax|compile|lint|import)\b/i.test(i)?"syntax":/^Bash$/i.test(t)?"user":"smoke"}function we(t){let e,n,s=t.match(/(?:^|\s)(\d+)\s+failed\b/i),i=t.match(/(?:^|\s)(\d+)\s+passed\b/i);return s&&(e=Number.parseInt(s[1],10)),i&&(n=Number.parseInt(i[1],10)),{failed:e,passed:n}}function ye(t,e){let n=t.replace(/\r\n/g,`
7
4
  `).split(`
8
- `),i=[];for(let s=0;s<n.length;s+=1){let a=n[s]??"";if(/^(?:FAILED|ERROR)\s+[\w./:-]+/i.test(a.trim())||G.some(o=>o.test(a))){let o=n.slice(Math.max(0,s-1),Math.min(n.length,s+3)).join(`
9
- `);i.push(Fe(o,260))}}let r=new Map;for(let s of i.slice(0,12)){let a=Oe(s);if(!a)continue;let o=r.get(a);if(o){o.count+=1,o.latestExcerpt=s,o.lastIteration=e;continue}r.set(a,{signature:a,title:s.split(`
10
- `).find(c=>c.trim().length>0)?.trim().slice(0,140)??"Validation failure",count:1,firstIteration:e,lastIteration:e,latestExcerpt:s})}return[...r.values()]}function Ue(t,e){let n=qe(e);return n.failed!==void 0&&n.failed>0?{outcome:"fail",failureCount:n.failed,...n.passed!==void 0?{passCount:n.passed}:{},summary:`${n.failed} pytest failure(s)${n.passed!==void 0?`, ${n.passed} passed`:""}`}:t.success===!1||G.some(i=>i.test(e))?{outcome:"fail",summary:t.error?`Command failed: ${t.error}`:"Validation output contains failure evidence"}:n.passed!==void 0&&n.passed>0?{outcome:"pass",passCount:n.passed,summary:`${n.passed} pytest test(s) passed`}:Me.some(i=>i.test(e))?{outcome:"pass",summary:"Validation output contains pass evidence"}:{outcome:"unknown",summary:t.success?"Validation-like command produced no clear pass/fail signal":"Command failed without parseable validation signal"}}function Ve(t,e,n){if(!n.success)return!1;if(/^(?:Write|Edit|NotebookEdit|MemoryWrite)$/i.test(t))return!0;let i=v(e);return/^Bash$/i.test(t)&&!!i&&Le.test(i)}function I(t){return T[t.authority]>=T.project}function y(t){let e=t.taskPrompt??"";return t.benchmarkMode||(t.requiredOutputPaths??[]).length>0?!0:/\b(?:test|tests|pytest|verifier|benchmark|hidden\s+tests?|build|fix|implement|debug|\/app|run-tests?\.sh)\b/i.test(e)}var p=class{contract;signals=[];clusters=new Map;toolCalls=0;workspaceRevision=0;lastCompletionDecision=null;lastValidationIteration=null;lastEvaluatedIteration=null;constructor(e={}){let n=e.taskPrompt??"",i=[...e.requiredOutputPaths??[]],r=e.benchmarkMode===!0||i.length>0||/\b(?:test|tests|pytest|verifier|hidden\s+tests?|run-tests?\.sh|official|validate|validation)\b/i.test(n);this.contract={projectLike:y(e),benchmarkMode:e.benchmarkMode===!0,requiredOutputPaths:i,requiredValidation:r}}recordToolResult(e){if(this.toolCalls+=1,Ve(e.toolName,e.input,e.result)){this.workspaceRevision+=1;for(let a of this.signals)a.stale=!0}let n=`${e.result.output??""}
11
- ${e.result.error??""}`;if(!je(e.toolName,e.input,n))return[];let i=De(e.toolName,e.input,n),r=Ue(e.result,n),s={id:`validation-${this.signals.length+1}`,iteration:e.iteration,toolName:e.toolName,...v(e.input)?{command:v(e.input)}:{},authority:i,outcome:r.outcome,stale:!1,workspaceRevision:this.workspaceRevision,summary:r.summary,...r.failureCount!==void 0?{failureCount:r.failureCount}:{},...r.passCount!==void 0?{passCount:r.passCount}:{},clusters:r.outcome==="fail"?$e(n,e.iteration):[]};this.signals.push(s),this.lastValidationIteration=e.iteration;for(let a of s.clusters){let o=this.clusters.get(a.signature);if(o){o.count+=a.count,o.lastIteration=a.lastIteration,o.latestExcerpt=a.latestExcerpt;continue}this.clusters.set(a.signature,{...a})}return[s]}evaluateCompletion(e){this.lastEvaluatedIteration=e.iteration;let n=this.getLatestUnresolvedFailure(),i=this.getLatestAuthoritativeSignal();if(this.contract.projectLike&&this.toolCalls===0)return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"no_tool_execution",message:["Do not finish yet. This is an execution task, but no tool evidence was recorded.","Inspect the relevant project state, make the required change, and run the strongest exposed validation before answering."].join(`
12
- `),blocking:!0,unresolvedFailures:[],latestAuthoritativeSignal:i});if(n){let r=this.getRepeatedFailure(),s=["Do not finish yet. The latest authoritative validation signal is still failing.",`Latest failure: ${n.summary}.`,r?`Repeated failure signature detected (${r.count}x): ${r.title}`:"Use the concrete failure output, make the smallest targeted repair, then rerun the same verifier-shaped check.","A self-check pass or candidate note cannot supersede a later project/official failure."].join(`
13
- `);return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"authoritative_validation_failed",message:s,blocking:!0,unresolvedFailures:n.clusters,latestAuthoritativeSignal:i})}if(i?.outcome==="pass"&&!i.stale)return this.setDecision({action:"complete",finalStateVerified:!0,reason:"authoritative_validation_passed",message:"Latest authoritative validation passed after the current workspace revision.",blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:i});if(this.contract.requiredValidation&&e.stopReason!=="progress_checkpoint"){let r=this.getLatestSignal(),s=r?.outcome==="pass"&&!I(r),a=["Do not finish yet. This task requires authoritative validation evidence.",s?"The latest pass signal is only a self/smoke check; run the project test, verifier, or strongest exposed validation command.":"Run the project test, verifier, or strongest exposed validation command and fix concrete failures before answering."].join(`
14
- `);return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:s?"weak_validation_only":"missing_authoritative_validation",message:a,blocking:!0,unresolvedFailures:[],latestAuthoritativeSignal:i})}return this.setDecision({action:"complete",finalStateVerified:!1,reason:"no_governance_blocker",message:"No execution-governance blocker found.",blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:i})}getSummary(){return{contract:{...this.contract,requiredOutputPaths:[...this.contract.requiredOutputPaths]},validation:{latestSignal:this.cloneSignal(this.getLatestSignal()),latestAuthoritativeSignal:this.cloneSignal(this.getLatestAuthoritativeSignal()),latestUnresolvedFailure:this.cloneSignal(this.getLatestUnresolvedFailure()),signals:this.signals.slice(-20).map(e=>this.cloneSignal(e))},progress:{toolCalls:this.toolCalls,validationRuns:this.signals.length,workspaceRevision:this.workspaceRevision,repeatedFailureSignature:this.getRepeatedFailure()?.signature??null,repeatedFailureCount:this.getRepeatedFailure()?.count??0,iterationsSinceLastValidation:this.lastValidationIteration===null?null:Math.max(0,(this.lastEvaluatedIteration??this.lastValidationIteration)-this.lastValidationIteration)},completionDecision:this.lastCompletionDecision?{...this.lastCompletionDecision}:null}}getLatestSignal(){return this.signals.at(-1)??null}getLatestAuthoritativeSignal(){return[...this.signals].reverse().find(e=>I(e))??null}getLatestUnresolvedFailure(){let e=[...this.signals].reverse().find(i=>I(i)&&i.outcome==="fail"&&!i.stale);return e?this.signals.some(i=>i.iteration>e.iteration&&!i.stale&&i.outcome==="pass"&&T[i.authority]>=T[e.authority])?null:e:null}getRepeatedFailure(){let e=null;for(let n of this.clusters.values())n.count<2||(!e||n.count>e.count)&&(e=n);return e}setDecision(e){return this.lastCompletionDecision=e,e}cloneSignal(e){return e?{...e,clusters:e.clusters.map(n=>({...n}))}:null}};var We=new Set(["bash","elfanalyze","gitbranch","gitdiff","gitlog","gitstatus","glob","grep","ls","read","readimage"]),ze=new Set(["applypatch","edit","notebookedit","write"]),Ge=/\?|\b(?:can|could|did|do|does|has|have|is|should|was|were|will|would)\b|\b(?:correct|right)\s*[.!?]*$/i,Be=/\b(?:audit|build|change|check|clone|configure|copy|create|delete|deploy|edit|find|fix|implement|inspect|install|locate|make|migrate|move|publish|refactor|release|remove|rename|research|run|save|scaffold|search|set|start|stop|test|update|verify|write)\b/i,He=/^(?:ok(?:ay)?[\s,!.:-]*)?(?:then\s+)?(?:(?:let(?:'|’)s|lets)\s+)?(?:continue|do\s+it|fix\s+it|get\s+started|go\s+ahead|implement\s+it|make\s+it|proceed|procede|ship\s+it|start)(?:\s+(?:now|please))?[\s.!?]*$/i,B=new Set(["add","address","adjust","adopt","append","apply","build","bump","carry","change","clean","commit","complete","continue","convert","correct","create","delete","deploy","disable","do","drop","edit","enable","execute","extend","extract","finalize","finish","fix","follow","generate","go","handle","implement","improve","include","insert","install","integrate","introduce","keep","land","make","merge","migrate","modify","move","patch","port","prepend","proceed","publish","push","put","rebase","rebuild","redo","reduce","refactor","release","remove","rename","replace","rerun","resolve","restore","retry","revert","rewrite","run","set","ship","split","start","switch","test","tidy","try","tweak","undo","update","upgrade","use","wire","write"]),Xe=/^(?:(?:ok(?:ay)?|alright|all\s+right|right|great|good|cool|yes|yep|yeah|sure|thanks|thank\s+you|perfect|nice|fine|now|then|so|and|please|pls|kindly|just|also|let(?:'|’)?s|let\s+us)\b[\s,!.:;-]*)+/i,Qe=/^(?:can|could|would|will)\s+you\s+(?:please\s+)?([a-z]+)/i,Ke=/^do\s+(?:you|we|i|they|he|she)\b/i;function Ye(t){let e=t.trim();if(!e)return!1;let n=Qe.exec(e);if(n)return B.has(n[1].toLowerCase());if(/\?\s*$/.test(e)&&!/[,\s](?:ok(?:ay)?|right|please|yes)\s*\?\s*$/i.test(e))return!1;let i=e.replace(Xe,"");if(Ke.test(i))return!1;let r=/^([a-z]+)/i.exec(i)?.[1]?.toLowerCase();return r!==void 0&&B.has(r)}function Ze(t){return t.split(/(?<=[.!?;:])\s+|\s+[—–]\s+|\n+/).some(Ye)}var Je=["audit","build","change","check","clone","configure","create","delete","deploy","implement","inspect","install","locate","migrate","publish","refactor","release","remove","rename","research","scaffold","search","start","update","verify","write"],et=/\b(?:browse|investigate|research|search)\b|\b(?:check|find|look)\s+(?:it\s+)?(?:up|online|on\s+the\s+web)\b/i,tt=["browse","investigate","research","search"],nt=/\b(?:Add-Content|Clear-Content|Copy-Item|git\s+(?:add|commit|merge|mv|push|rebase|reset|restore|rm|switch)|Move-Item|New-Item|npm\s+(?:install|publish|uninstall)|pnpm\s+(?:add|install|publish|remove)|Remove-Item|Rename-Item|Set-Content|Start-Process|yarn\s+(?:add|install|publish|remove))\b|(?:^|[^<])>{1,2}\s*[^&]/i,it=/\b(?:installed|install(?:ed)?|on\s+(?:my|this)\s+(?:machine|pc|computer|system)|cli|command(?:\s+line)?|executable|on\s+(?:the\s+)?path|version|where(?:\.exe)?|which|available)\b/i,rt=/\b(?:Get-Command|where(?:\.exe)?|command\s+-v|which|type\s+-a?|--version|-v\b|--help|-h\b)\b/i,st=/\b(?:yes|installed|you\s+(?:have|do\s+have)|found|available|on\s+(?:your|the)\s+path|callable|working|responds?|verified|confirmed)\b/i,at=/\b(?:cannot\s+confirm|can't\s+confirm|not\s+confirm(?:ed)?|not\s+proven|not\s+verified|uncertain|failed|fails|could\s+not\s+verify|not\s+installed|does\s+not\s+appear|isn't\s+available|not\s+available)\b/i,ot=/\b(?:exit\s+code|exit\s+status|status|return\s+code|returncode)\s*[:= -]?\s*(?:-[1-9]\d*|[1-9]\d*)\b|\b(?:not\s+recognized|not\s+found|could\s+not\s+find|cannot\s+find|no\s+such\s+file|failed)\b/i,ct=/\b(?:created|generated|produced|saved|wrote|written|exported|converted|built|rendered|flattened|creat|generat|produs|salvat|scris|exportat|convertit|aplatizat)\b/i,lt=/\b(?:not|didn['’]?t|couldn['’]?t|cannot|failed\s+to|incomplete|missing|nu|n-am|nereu[sÈ™]it)\b/i,ut=/\b(?:pages?|page\s+count|dpi|ocr|text\s+layer|extractible\s+text|renders?|opens?|dimensions?|metadata|pagini|strat\s+(?:ocr|de\s+text)|text\s+extractibil|se\s+deschide|rezolu[tÈ›]ie)\b/i,dt=/(?:^|[\\/])\.xeno[\\/](?:sessions|audit)[\\/]/i,mt=/\b(?:official|docs?|documentation|source|reference|install(?:ation)?|supported|features?|commands?)\b/i,ht=/\b(?:search\s+online|look\s+online|web\s+search|web\s+fetch|fetch\s+(?:the\s+)?(?:official\s+)?page|official|docs?|documentation|source|reference|summarize|url)\b/i,pt=/\b(?:HTTP\s+404|404\s+Not\s+Found|not\s+found|does\s+not\s+exist|gone|HTTP\s+410|410\s+Gone)\b/i,ft=/\b(?:curl|wget|Invoke-WebRequest|Invoke-RestMethod|iwr|irm)\b[\s\S]*https?:\/\/|\bpython(?:3|\.exe)?\b[\s\S]*\b(?:urllib\.request|requests\.get|http\.client)\b[\s\S]*https?:\/\/|\bnode(?:\.exe)?\b[\s\S]*\b(?:fetch|https\.get|axios)\b[\s\S]*https?:\/\//i,gt=/https?:\/\/[^\s)>\]]+/i;function f(t){return t.trim().replace(/\s+/g," ")}function bt(t,e){if(t===e)return!0;if(Math.abs(t.length-e.length)>1)return!1;if(t.length===e.length){let o=[];for(let c=0;c<t.length;c+=1)if(t[c]!==e[c]&&o.push(c),o.length>2)return!1;return o.length===1?!0:o.length===2&&o[1]===o[0]+1&&t[o[0]]===e[o[1]]&&t[o[1]]===e[o[0]]}let[n,i]=t.length<e.length?[t,e]:[e,t],r=0,s=0,a=!1;for(;r<n.length&&s<i.length;){if(n[r]===i[s]){r+=1,s+=1;continue}if(a)return!1;a=!0,s+=1}return!0}function ne(t,e){return(t.toLowerCase().match(/[a-z]+/g)??[]).some(i=>i.length>=5&&e.some(r=>bt(i,r)))}function vt(t){return He.test(f(t))||Be.test(t)||ne(t,Je)}function _(t){return et.test(t)||ne(t,tt)}function F(t){return t.replace(/[\s_-]+/g,"").toLowerCase()}function N(t){return Array.isArray(t)?t.map(N):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,N(n)])):typeof t=="string"?f(t.replace(/\\/g,"/")):t}function H(t,e){return`${F(t)}:${JSON.stringify(N(e))}`}function X(t){return We.has(F(t))}function yt(t,e){let n=F(t);return ze.has(n)?!0:n==="bash"&&nt.test(L(e)??"")}function w(t){let e=f(t);return!e||e.length>320?!1:Ge.test(e)&&!vt(e)&&!Ze(e)}function ie(t,e){let n=Math.max(1,Math.floor(e));return w(t)?Math.min(n,15):n}function wt(t){if(typeof t!="string")return null;let e=f(t).toLowerCase();return e.length>0?e:null}function Q(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.hash="",e.pathname=e.pathname.replace(/\/+$/,"")||"/",e.toString().toLowerCase()}catch{let e=f(t).toLowerCase().replace(/#.*$/,"").replace(/\/+$/,"");return e.length>0?e:null}}function L(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():null}function M(t){return typeof t=="string"?[t]:Array.isArray(t)?t.flatMap(M):t&&typeof t=="object"?Object.values(t).flatMap(M):[]}function K(t){return t.replace(/\\/g,"/").toLowerCase()}function Y(t){return f([t.output,t.error].filter(Boolean).join(" ")).slice(0,240)}function Z(t){return t.success===!1||ot.test([t.output,t.error].filter(Boolean).join(`
15
- `))}function J(t){return/^Bash$/i.test(t)}function ee(t){return/^WebSearch$/i.test(t)}function te(t){return/^WebFetch$/i.test(t)}var h=class{taskPrompt;maxWebSearches;maxWebFetches;maxTotalWebResearchCalls;maxLocalInspectionCalls;simpleInformationalPrompt;explicitResearchPrompt;searchQueries=new Map;fetchedUrls=new Map;localInspectionRecords=new Map;localEvidence=[];webFetchEvidence=[];artifactEvidence=[];verificationRecords=[];pendingAwaitOperations=new Map;transcriptReadRanges=new Map;webSearches=0;webFetches=0;localInspectionCalls=0;mutationEpoch=0;constructor(e,n={}){this.taskPrompt=e,this.explicitResearchPrompt=_(e),this.maxWebSearches=Math.max(1,n.maxWebSearches??(this.explicitResearchPrompt?5:3)),this.maxWebFetches=Math.max(1,n.maxWebFetches??(this.explicitResearchPrompt?12:4)),this.maxTotalWebResearchCalls=Math.max(1,n.maxTotalWebResearchCalls??(this.explicitResearchPrompt?16:6)),this.simpleInformationalPrompt=w(e),this.maxLocalInspectionCalls=Math.max(1,n.maxLocalInspectionCalls??(this.simpleInformationalPrompt?12:Number.MAX_SAFE_INTEGER))}maybeBlockToolCall(e){let n=this.findOverlappingTranscriptRead(e.toolName,e.input);if(n)return this.blockedResult(["[Xeno continuation-state guard]",`This transcript range overlaps an earlier read in the current turn: ${n}`,"Use the structured operation/continuation checkpoint and the existing excerpt. Do not scan the growing session Markdown to rediscover current state."]);if(yt(e.toolName,e.input)){if(this.simpleInformationalPrompt)return this.blockedResult(["[Xeno interactive turn guard]","This is a short informational question, not a request to change files, configuration, packages, processes, or repository state.",`Blocked unrequested mutation through ${e.toolName}.`,"Answer the question from the evidence already available. Ask before making changes if a change would materially help."]);this.mutationEpoch+=1}if(X(e.toolName)){let i=`${this.mutationEpoch}:${H(e.toolName,e.input)}`,r=this.localInspectionRecords.get(i);if(r?.successful||(r?.attempts??0)>=2)return this.blockedResult(["[Xeno interactive turn guard]",r?.successful===!0?`This exact ${e.toolName} inspection already succeeded during the current turn.`:`This exact ${e.toolName} inspection has already failed twice during the current turn.`,"Do not repeat or cosmetically repackage the same inspection. Use the existing result, choose one materially different check, or answer now with the uncertainty that remains."]);if(this.localInspectionCalls>=this.maxLocalInspectionCalls)return this.blockedResult(["[Xeno interactive turn guard]",`The local inspection budget for this turn is exhausted (${this.localInspectionCalls}/${this.maxLocalInspectionCalls}).`,"Stop exploring. Give the shortest accurate answer supported by the evidence already gathered, and state one limitation if needed."]);this.localInspectionCalls+=1,this.localInspectionRecords.set(i,{attempts:(r?.attempts??0)+1,successful:r?.successful??!1})}if(J(e.toolName)&&this.isWebResearchQuestion()){let i=L(e.input);if(i&&ft.test(i))return this.blockedResult(["[Xeno interactive research guard]","Do not use Bash, Python, PowerShell, curl, wget, or ad hoc scripts to fetch public web pages during a web-research turn.","Use WebSearch to discover sources and WebFetch to read exact URLs. WebFetch handles timeouts, redirects, readable extraction, source metadata, and discovered documentation links.",this.fetchedSourceSummary()])}if(ee(e.toolName)){let i=wt(e.input.query),r=i?this.searchQueries.get(i)??0:0;if(this.shouldStopOfficialResearch())return this.blockedResult(["[Xeno interactive research guard]","Official web evidence has already been fetched this turn.",this.fetchedSourceSummary(),"Stop searching. Answer now from the fetched official source(s), naming the URL(s) used and clearly stating any remaining uncertainty."]);if(i&&r>0)return this.blockedResult(["[Xeno interactive research guard]",`The WebSearch query has already been run this turn: ${i}`,"Do not repeat equivalent searches. Use the existing search result, fetch one clearly relevant source, run a local verification command if the question is about this machine, or answer with the uncertainty that remains."]);if(this.webSearches>=this.maxWebSearches||this.totalWebResearchCalls()>=this.maxTotalWebResearchCalls)return this.blockedResult(["[Xeno interactive research guard]",`The per-turn web-search budget is exhausted (${this.webSearches}/${this.maxWebSearches} searches, ${this.totalWebResearchCalls()}/${this.maxTotalWebResearchCalls} total web calls).`,"Stop broad web exploration. Prefer official documentation already found, run a local check if relevant, or give a bounded answer that states what is and is not verified."]);this.webSearches+=1,i&&this.searchQueries.set(i,r+1)}if(te(e.toolName)){let i=Q(e.input.url),r=i?this.fetchedUrls.get(i)??0:0;if(this.shouldStopOfficialResearch())return this.blockedResult(["[Xeno interactive research guard]","Enough official web evidence has already been fetched this turn.",this.fetchedSourceSummary(),"Do not guess more nearby documentation URLs. Answer from the fetched source(s), cite the URL(s), and mention if a specific detail was not present."]);if(i&&r>0)return this.blockedResult(["[Xeno interactive research guard]",`This URL has already been fetched this turn: ${i}`,"Do not fetch the same page again. Use the existing content, fetch a more precise official source, run a local verification command if relevant, or answer with the uncertainty that remains."]);if(this.webFetches>=this.maxWebFetches||this.totalWebResearchCalls()>=this.maxTotalWebResearchCalls)return this.blockedResult(["[Xeno interactive research guard]",`The per-turn web-fetch budget is exhausted (${this.webFetches}/${this.maxWebFetches} fetches, ${this.totalWebResearchCalls()}/${this.maxTotalWebResearchCalls} total web calls).`,"Stop broad web exploration. Use the best source already gathered, run a local check if relevant, or answer with a clear limitation."]);this.webFetches+=1,i&&this.fetchedUrls.set(i,r+1)}return null}recordToolResult(e){let n=e.result.operation;n?.completionPolicy==="await"&&(n.terminal?this.pendingAwaitOperations.delete(n.operationId):this.pendingAwaitOperations.set(n.operationId,n.taskId??n.operationId));for(let s of e.result.evidence??n?.evidence??[]){let a=this.artifactEvidence.findIndex(c=>c.operationId===s.operationId&&c.path===s.path),o={iteration:e.iteration,path:s.path,status:s.status,operationId:s.operationId};a>=0?this.artifactEvidence[a]=o:this.artifactEvidence.push(o)}if(kt(e.toolName)&&this.verificationRecords.push({iteration:e.iteration,toolName:e.toolName,inputValues:M(e.input),success:e.result.success===!0&&!Z(e.result)}),X(e.toolName)){let s=`${this.mutationEpoch}:${H(e.toolName,e.input)}`,a=this.localInspectionRecords.get(s);a&&(a.successful=a.successful||e.result.success===!0)}if(ee(e.toolName))return;if(te(e.toolName)){let s=Q(e.input.url);s&&this.webFetchEvidence.push({iteration:e.iteration,url:s,success:e.result.success===!0,summary:Y(e.result)});return}if(!J(e.toolName)||!this.isLocalSetupQuestion())return;let i=L(e.input);if(!i||!rt.test(i))return;let r=Z(e.result);this.localEvidence.push({iteration:e.iteration,command:i,success:e.result.success===!0&&!r,summary:Y(e.result)})}evaluateCompletion(e){if(this.pendingAwaitOperations.size>0)return{blocking:!0,message:["[Xeno pending-operation guard]",`Awaited operation(s) are still nonterminal: ${Array.from(this.pendingAwaitOperations.values()).join(", ")}.`,"Suspend this turn without a final answer. The runtime will resume the objective exactly once when the operation becomes terminal."].join(`
16
- `)};let n=this.evaluateArtifactClaims(e.finalText);if(n)return n;if(this.isWebResearchQuestion()){let a=this.evaluateWebResearchCompletion(e.finalText);if(a)return a}if(!this.isLocalSetupQuestion())return null;let i=[...this.localEvidence].reverse().find(a=>!a.success);if(!i||this.localEvidence.some(a=>a.iteration>=i.iteration&&a.success))return null;let s=e.finalText.trim();return!s||!st.test(s)||at.test(s)?null:{blocking:!0,message:["[Xeno evidence correction]","Do not claim the local tool/app/CLI is installed or working yet.",`The latest local verification command failed: ${i.command}`,i.summary?`Failure evidence: ${i.summary}`:null,"Next step: either run one robust local verification command that directly proves the claim, or answer that the launcher/path may exist but the CLI status is not confirmed.","Do not use web documentation as proof of what is installed on this machine."].filter(Boolean).join(`
17
- `)}}evaluateWebResearchCompletion(e){let n=e.trim();if(!n)return null;let i=this.successfulWebFetches(),r=i.map(o=>o.url),s=gt.test(n),a=r.some(o=>n.toLowerCase().includes(o.toLowerCase()));return i.length>0&&(!s||!a)?{blocking:!0,message:["[Xeno source-citation correction]","The answer uses web/documentation evidence but does not clearly cite the fetched source URL(s).",this.fetchedSourceSummary(),"Rewrite the final answer with a short Sources section using Markdown links like `Sources: [Title](url)`, then the requested sections. Do not run more tools unless a required detail is still missing."].join(`
18
- `)}:null}isLocalSetupQuestion(){return it.test(this.taskPrompt)}totalWebResearchCalls(){return this.webSearches+this.webFetches}isOfficialResearchQuestion(){return mt.test(this.taskPrompt)}isWebResearchQuestion(){return this.explicitResearchPrompt||ht.test(this.taskPrompt)}successfulWebFetches(){return this.webFetchEvidence.filter(e=>e.success)}failedSpeculativeWebFetches(){return this.webFetchEvidence.filter(e=>!e.success&&pt.test(e.summary))}shouldStopOfficialResearch(){if(this.explicitResearchPrompt||!this.isOfficialResearchQuestion())return!1;let e=this.successfulWebFetches();return e.length>=this.minimumOfficialEvidenceFetches()?!0:e.length>=1&&this.failedSpeculativeWebFetches().length>=1}minimumOfficialEvidenceFetches(){let e=this.taskPrompt.toLowerCase(),n=/\binstall(?:ation)?|update|upgrade|version|verify\b/.test(e),i=/\binteractive|usage|using|agent\s+commands?|session|resume|flags?|shortcuts?\b/.test(e),r=/\bslash|reference|commands?\s+list|all\s+commands?\b/.test(e);return n&&i||r?Math.min(4,this.maxWebFetches):2}fetchedSourceSummary(){let e=this.successfulWebFetches().map(n=>n.url);return e.length===0?"No successful web fetch is recorded yet.":`Fetched source(s): ${e.join(", ")}`}blockedResult(e){return{success:!1,output:e.join(`
19
- `),error:"Interactive turn guard blocked redundant, excessive, or unrequested tool use"}}evaluateArtifactClaims(e){let n=e.trim();if(!ct.test(n)||lt.test(n))return null;let i=this.artifactEvidence.filter(a=>a.status==="verified");if(i.length===0){let a=this.artifactEvidence.filter(o=>o.status==="failed");return{blocking:!0,message:["[Xeno artifact-evidence guard]","Do not claim that an artifact was created, saved, converted, or written without current verified artifact evidence.",a.length>0?`The latest postcondition evidence failed for: ${a.map(o=>o.path??o.operationId).join(", ")}.`:"No successful artifact postcondition is recorded in this turn.","Inspect the target, verify it is the expected file, and only then give the completion answer."].join(`
20
- `)}}if(!ut.test(n))return null;let r=Math.max(...i.map(a=>a.iteration));return this.verificationRecords.some(a=>a.success&&a.iteration>=r&&i.some(o=>!o.path||a.inputValues.some(c=>K(c).includes(K(o.path)))))?null:{blocking:!0,message:["[Xeno semantic-evidence guard]","File existence does not prove semantic claims such as page count, OCR absence, dimensions, metadata, or successful rendering.","Run one bounded verifier against the generated artifact and then report only the properties that verifier established."].join(`
21
- `)}}findOverlappingTranscriptRead(e,n){if(!/^Read$/i.test(e))return null;let i=typeof n.file_path=="string"?n.file_path:"";if(!dt.test(i))return null;let r=Math.max(0,Number.isFinite(n.offset)?Math.floor(Number(n.offset)):0),s=Math.max(1,Number.isFinite(n.limit)?Math.floor(Number(n.limit)):2e3),a=r+s,o=i.toLowerCase(),c=this.transcriptReadRanges.get(o)??[],d=c.find(m=>r<m.end&&a>m.start);return d?`${i}:${r}-${a} overlaps ${d.start}-${d.end}`:(c.push({start:r,end:a}),this.transcriptReadRanges.set(o,c),null)}};function kt(t){return/^(?:Bash|Read|ReadImage|ElfAnalyze|NotebookRead)$/i.test(t)}var A=class{active=null;activePrompt=null;promptSection={name:"interactive-chat-answer-budget",order:20,provide:()=>this.activePrompt?_(this.activePrompt)?[`
5
+ `),s=[];for(let r=0;r<n.length;r+=1){let o=n[r]??"";if(/^(?:FAILED|ERROR)\s+[\w./:-]+/i.test(o.trim())||U.some(a=>a.test(o))){let a=n.slice(Math.max(0,r-1),Math.min(n.length,r+3)).join(`
6
+ `);s.push(pe(a,260))}}let i=new Map;for(let r of s.slice(0,12)){let o=fe(r);if(!o)continue;let a=i.get(o);if(a){a.count+=1,a.latestExcerpt=r,a.lastIteration=e;continue}i.set(o,{signature:o,title:r.split(`
7
+ `).find(c=>c.trim().length>0)?.trim().slice(0,140)??"Validation failure",count:1,firstIteration:e,lastIteration:e,latestExcerpt:r})}return[...i.values()]}function Se(t,e){let n=we(e);if(n.failed!==void 0&&n.failed>0)return{outcome:"fail",failureCount:n.failed,...n.passed!==void 0?{passCount:n.passed}:{},summary:`${n.failed} pytest failure(s)${n.passed!==void 0?`, ${n.passed} passed`:""}`};if(t.success===!1||U.some(i=>i.test(e)))return{outcome:"fail",summary:t.error?`Command failed: ${t.error}`:"Validation output contains failure evidence"};if(n.passed!==void 0&&n.passed>0)return{outcome:"pass",passCount:n.passed,summary:`${n.passed} pytest test(s) passed`};if(me.some(i=>i.test(e)))return{outcome:"pass",summary:"Validation output contains pass evidence"};let s=e.match(/\bRan\s+(\d+)\s+tests?\b[\s\S]{0,200}?\n\s*OK\b/);if(s&&Number.parseInt(s[1],10)>0){let i=Number.parseInt(s[1],10);return{outcome:"pass",passCount:i,summary:`${i} unittest test(s) passed`}}return t.success===!0&&t.error===void 0&&e.trim().length>0?{outcome:"pass",summary:"Check command exited 0 with no failure output"}:{outcome:"unknown",summary:t.success?"Validation-like command produced no clear pass/fail signal":"Command failed without parseable validation signal"}}function _e(t,e,n){if(!n.success)return!1;if(/^(?:Write|Edit|NotebookEdit|MemoryWrite)$/i.test(t))return!0;let s=p(e);return/^Bash$/i.test(t)&&!!s&&D.test(I(s))}function x(t){return R[t.authority]>=R.project}var f=class{contract;signals=[];clusters=new Map;toolCalls=0;workspaceRevision=0;ownTasks=new Map;nextOwnTaskId=1;uncheckedChangesAdvised=!1;lastCompletionDecision=null;lastValidationIteration=null;lastEvaluatedIteration=null;cwd;taskPrompt;constructor(e={}){this.cwd=e.cwd??process.cwd(),this.taskPrompt=e.taskPrompt??"",this.contract={requiredOutputPaths:[...e.requiredOutputPaths??[]],projectLike:!0,benchmarkMode:!1,requiredValidation:!1}}recordToolResult(e){if(this.toolCalls+=1,e.result.success===!0&&/^TaskCreate$/i.test(e.toolName)){let l=typeof e.input.subject=="string"?e.input.subject:"task";this.ownTasks.set(String(this.nextOwnTaskId++),{subject:l,status:"pending"})}else if(e.result.success===!0&&/^TaskUpdate$/i.test(e.toolName)){let l=String(e.input.taskId??""),u=typeof e.input.status=="string"?e.input.status:void 0;u==="deleted"?this.ownTasks.delete(l):u&&this.ownTasks.has(l)&&(this.ownTasks.get(l).status=u)}if(_e(e.toolName,e.input,e.result)){this.workspaceRevision+=1;for(let l of this.signals)l.stale=!0}let n=`${e.result.output??""}
8
+ ${e.result.error??""}`,s=p(e.input)??"",i=/^Bash$/i.test(e.toolName)&&ve(s,this.taskPrompt),r=Re(e.toolName,e.input,n),o=!r&&/^Bash$/i.test(e.toolName)&&e.result.success===!0&&!D.test(I(s))&&(i||this.workspaceRevision>0&&be(s));if(!r&&!o)return[];let a=i?"official":o?"self":Te(e.toolName,e.input,n),c=o?{outcome:"pass",summary:i?"The check named in the task exited 0":"Command exited 0"}:Se(e.result,n),d={id:`validation-${this.signals.length+1}`,iteration:e.iteration,toolName:e.toolName,...p(e.input)?{command:p(e.input)}:{},authority:a,outcome:c.outcome,stale:!1,workspaceRevision:this.workspaceRevision,summary:c.summary,...c.failureCount!==void 0?{failureCount:c.failureCount}:{},...c.passCount!==void 0?{passCount:c.passCount}:{},clusters:c.outcome==="fail"?ye(n,e.iteration):[]};this.signals.push(d),this.lastValidationIteration=e.iteration;for(let l of d.clusters){let u=this.clusters.get(l.signature);if(u){u.count+=l.count,u.lastIteration=l.lastIteration,u.latestExcerpt=l.latestExcerpt;continue}this.clusters.set(l.signature,{...l})}return[d]}evaluateCompletion(e){this.lastEvaluatedIteration=e.iteration;let n=this.getLatestUnresolvedFailure(),s=this.getLatestAuthoritativeSignal();if(e.stopReason!=="progress_checkpoint"){let i=[...this.ownTasks.values()].filter(r=>r.status!=="completed");if(i.length>0)return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"own_tasks_unfinished",message:["Do not finish yet. Your own task list still has unfinished work:",...i.slice(0,8).map(r=>`- ${r.subject} (${r.status})`),"Carry it out now. If an item is truly done, mark it completed; if it cannot be done, say exactly why in your answer and delete it."].join(`
9
+ `),blocking:!0,unresolvedFailures:[],latestAuthoritativeSignal:s})}if(this.contract.requiredOutputPaths.length>0&&e.stopReason!=="progress_checkpoint"){let i=A(this.contract.requiredOutputPaths,this.cwd);if(i.length>0)return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"required_outputs_missing",message:["Do not finish yet. Required output files are not in place.",...i.map(r=>`- ${r.path} (${r.problem==="missing"?"does not exist":r.problem==="empty"?"is empty":"is not a file"})`),"Create or complete them, then check their contents before answering."].join(`
10
+ `),blocking:!0,unresolvedFailures:[],latestAuthoritativeSignal:s})}if(n){let i=this.getRepeatedFailure(),r=["Do not finish yet. The latest authoritative validation signal is still failing.",`Latest failure: ${n.summary}.`,i?`Repeated failure signature detected (${i.count}x): ${i.title}`:"Use the concrete failure output, make the smallest targeted repair, then rerun the same verifier-shaped check.","A self-check pass or candidate note cannot supersede a later project/official failure."].join(`
11
+ `);return this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"authoritative_validation_failed",message:r,blocking:!0,unresolvedFailures:n.clusters,latestAuthoritativeSignal:s})}if(s?.outcome==="pass"&&!s.stale)return this.setDecision({action:"complete",finalStateVerified:!0,reason:"authoritative_validation_passed",message:"Latest authoritative validation passed after the current workspace revision.",blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:s});if(this.workspaceRevision>0&&e.stopReason!=="progress_checkpoint"){let i=this.getLatestSignal(),r=i?.outcome==="pass"&&!i.stale;return this.signals.some(a=>x(a)&&a.outcome!=="unknown")?this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"tests_not_rerun_after_changes",message:["Do not finish yet. You changed files after the last run of the project's tests.","Run them again on the current files and fix what fails before answering."].join(`
12
+ `),blocking:!0,unresolvedFailures:[],latestAuthoritativeSignal:s}):r?this.setDecision({action:"complete",finalStateVerified:!1,reason:"self_validation_passed",message:"No project test suite was run. The agent's own check passed against the current workspace; this is not an independent verification.",blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:s}):this.uncheckedChangesAdvised?this.setDecision({action:"complete",finalStateVerified:!1,reason:"changes_unverified",message:"The workspace was changed and no check was run against the final state.",blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:s}):(this.uncheckedChangesAdvised=!0,this.setDecision({action:e.stopReason==="max_iterations"?"incomplete":"continue",finalStateVerified:!1,reason:"changes_not_checked",message:["Before you finish: you changed the workspace and have not checked the result since your last change.","Run the check that would fail if the work were wrong (the project's tests, the command the task names, or your own comparison against an independent answer).","If nothing can be run against this change, say so plainly in your answer."].join(`
13
+ `),blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:s}))}return this.setDecision({action:"complete",finalStateVerified:!1,reason:"no_changes_made",message:"Nothing in the workspace was changed, so there is no result to verify.",blocking:!1,unresolvedFailures:[],latestAuthoritativeSignal:s})}getSummary(){return{contract:{...this.contract,requiredOutputPaths:[...this.contract.requiredOutputPaths]},validation:{latestSignal:this.cloneSignal(this.getLatestSignal()),latestAuthoritativeSignal:this.cloneSignal(this.getLatestAuthoritativeSignal()),latestUnresolvedFailure:this.cloneSignal(this.getLatestUnresolvedFailure()),signals:this.signals.slice(-20).map(e=>this.cloneSignal(e))},progress:{toolCalls:this.toolCalls,validationRuns:this.signals.length,workspaceRevision:this.workspaceRevision,repeatedFailureSignature:this.getRepeatedFailure()?.signature??null,repeatedFailureCount:this.getRepeatedFailure()?.count??0,iterationsSinceLastValidation:this.lastValidationIteration===null?null:Math.max(0,(this.lastEvaluatedIteration??this.lastValidationIteration)-this.lastValidationIteration)},completionDecision:this.lastCompletionDecision?{...this.lastCompletionDecision}:null}}getLatestSignal(){return this.signals.at(-1)??null}getLatestAuthoritativeSignal(){return[...this.signals].reverse().find(e=>x(e))??null}getLatestUnresolvedFailure(){let e=[...this.signals].reverse().find(s=>x(s)&&s.outcome==="fail"&&!s.stale);return e?this.signals.some(s=>s.iteration>e.iteration&&!s.stale&&s.outcome==="pass"&&R[s.authority]>=R[e.authority])?null:e:null}getRepeatedFailure(){let e=null;for(let n of this.clusters.values())n.count<2||(!e||n.count>e.count)&&(e=n);return e}setDecision(e){return this.lastCompletionDecision=e,e}cloneSignal(e){return e?{...e,clusters:e.clusters.map(n=>({...n}))}:null}};var K=200,Y=500;function k(t,e,n){if(e===void 0||e==="")return;let s=typeof e=="number"?e:/^[0-9]+$/.test(e.trim())?Number(e.trim()):NaN;if(!Number.isSafeInteger(s)||s<1||s>n)throw Object.assign(new Error(`${t} must be a whole number from 1 to ${n}.`),{code:"WEB_RESEARCH_BUDGET_INVALID"});return s}function Z(t){let e=k("The web search limit",t.searches,200),n=k("The web fetch limit",t.fetches,500),s=k("The total web call limit",t.calls,700);return{...e===void 0?{}:{maxWebSearches:e},...n===void 0?{}:{maxWebFetches:n},...s===void 0?{}:{maxTotalWebResearchCalls:s}}}var xe=15,Ce=new Set(["bash","elfanalyze","gitbranch","gitdiff","gitlog","gitstatus","glob","grep","ls","read","readimage"]),Ae=new Set(["applypatch","edit","notebookedit","write"]),Ie=/\?|\b(?:can|could|did|do|does|has|have|is|should|was|were|will|would)\b|\b(?:correct|right)\s*[.!?]*$/i,ke=/\b(?:audit|build|change|check|clone|configure|copy|create|delete|deploy|edit|find|fix|implement|inspect|install|locate|make|migrate|move|publish|refactor|release|remove|rename|research|run|save|scaffold|search|set|start|stop|test|update|verify|write)\b/i,Pe=/^(?:ok(?:ay)?[\s,!.:-]*)?(?:then\s+)?(?:(?:let(?:'|’)s|lets)\s+)?(?:continue|do\s+it|fix\s+it|get\s+started|go\s+ahead|implement\s+it|make\s+it|proceed|procede|ship\s+it|start)(?:\s+(?:now|please))?[\s.!?]*$/i,$=new Set(["add","address","adjust","adopt","append","apply","build","bump","carry","change","clean","commit","complete","continue","convert","correct","create","delete","deploy","disable","do","drop","edit","enable","execute","extend","extract","finalize","finish","fix","follow","generate","go","handle","implement","improve","include","insert","install","integrate","introduce","keep","land","make","merge","migrate","modify","move","patch","port","prepend","proceed","publish","push","put","rebase","rebuild","redo","reduce","refactor","release","remove","rename","replace","rerun","resolve","restore","retry","revert","rewrite","run","set","ship","split","start","switch","test","tidy","try","tweak","undo","update","upgrade","use","wire","write"]),Ne=/^(?:(?:ok(?:ay)?|alright|all\s+right|right|great|good|cool|yes|yep|yeah|sure|thanks|thank\s+you|perfect|nice|fine|now|then|so|and|please|pls|kindly|just|also|let(?:'|’)?s|let\s+us)\b[\s,!.:;-]*)+/i,Le=/^(?:can|could|would|will)\s+you\s+(?:please\s+)?([a-z]+)/i,Fe=/^do\s+(?:you|we|i|they|he|she)\b/i;function Oe(t){let e=t.trim();if(!e)return!1;let n=Le.exec(e);if(n)return $.has(n[1].toLowerCase());if(/\?\s*$/.test(e)&&!/[,\s](?:ok(?:ay)?|right|please|yes)\s*\?\s*$/i.test(e))return!1;let s=e.replace(Ne,"");if(Fe.test(s))return!1;let i=/^([a-z]+)/i.exec(s)?.[1]?.toLowerCase();return i!==void 0&&$.has(i)}function Me(t){return t.split(/(?<=[.!?;:])\s+|\s+[—–]\s+|\n+/).some(Oe)}var We=["audit","build","change","check","clone","configure","create","delete","deploy","implement","inspect","install","locate","migrate","publish","refactor","release","remove","rename","research","scaffold","search","start","update","verify","write"],De=/\b(?:browse|investigate|research|search)\b|\b(?:check|find|look)\s+(?:it\s+)?(?:up|online|on\s+the\s+web)\b/i,Ue=["browse","investigate","research","search"],$e=/\b(?:Add-Content|Clear-Content|Copy-Item|git\s+(?:add|commit|merge|mv|push|rebase|reset|restore|rm|switch)|Move-Item|New-Item|npm\s+(?:install|publish|uninstall)|pnpm\s+(?:add|install|publish|remove)|Remove-Item|Rename-Item|Set-Content|Start-Process|yarn\s+(?:add|install|publish|remove))\b|(?:^|[^<])>{1,2}\s*[^&]/i,Ve=/\b(?:installed|install(?:ed)?|on\s+(?:my|this)\s+(?:machine|pc|computer|system)|cli|command(?:\s+line)?|executable|on\s+(?:the\s+)?path|version|where(?:\.exe)?|which|available)\b/i,Ge=/\b(?:Get-Command|where(?:\.exe)?|command\s+-v|which|type\s+-a?|--version|-v\b|--help|-h\b)\b/i,je=/\b(?:yes|installed|you\s+(?:have|do\s+have)|found|available|on\s+(?:your|the)\s+path|callable|working|responds?|verified|confirmed)\b/i,Be=/\b(?:cannot\s+confirm|can't\s+confirm|not\s+confirm(?:ed)?|not\s+proven|not\s+verified|uncertain|failed|fails|could\s+not\s+verify|not\s+installed|does\s+not\s+appear|isn't\s+available|not\s+available)\b/i,He=/\b(?:exit\s+code|exit\s+status|status|return\s+code|returncode)\s*[:= -]?\s*(?:-[1-9]\d*|[1-9]\d*)\b|\b(?:not\s+recognized|not\s+found|could\s+not\s+find|cannot\s+find|no\s+such\s+file|failed)\b/i,qe=/\b(?:created|generated|produced|saved|wrote|written|exported|converted|built|rendered|flattened|creat|generat|produs|salvat|scris|exportat|convertit|aplatizat)\b/i,Xe=/\b(?:not|didn['’]?t|couldn['’]?t|cannot|failed\s+to|incomplete|missing|nu|n-am|nereu[sÈ™]it)\b/i,ze=/\b(?:pages?|page\s+count|dpi|ocr|text\s+layer|extractible\s+text|renders?|opens?|dimensions?|metadata|pagini|strat\s+(?:ocr|de\s+text)|text\s+extractibil|se\s+deschide|rezolu[tÈ›]ie)\b/i,Qe=/(?:^|[\\/])\.xeno[\\/](?:sessions|audit)[\\/]/i,Ke=/\b(?:official|docs?|documentation|source|reference|install(?:ation)?|supported|features?|commands?)\b/i,Ye=/\b(?:search\s+online|look\s+online|web\s+search|web\s+fetch|fetch\s+(?:the\s+)?(?:official\s+)?page|official|docs?|documentation|source|reference|summarize|url)\b/i,Ze=/\b(?:HTTP\s+404|404\s+Not\s+Found|not\s+found|does\s+not\s+exist|gone|HTTP\s+410|410\s+Gone)\b/i,Je=/\b(?:curl|wget|Invoke-WebRequest|Invoke-RestMethod|iwr|irm)\b[\s\S]*https?:\/\/|\bpython(?:3|\.exe)?\b[\s\S]*\b(?:urllib\.request|requests\.get|http\.client)\b[\s\S]*https?:\/\/|\bnode(?:\.exe)?\b[\s\S]*\b(?:fetch|https\.get|axios)\b[\s\S]*https?:\/\//i,et=/https?:\/\/[^\s)>\]]+/i,tt=/^(?:localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[?::1\]?|10(?:\.\d{1,3}){3}|192\.168(?:\.\d{1,3}){2}|172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2}|[a-z0-9-]+\.(?:local|localhost|test|internal))$/i;function nt(t){return Je.test(t)?[...t.matchAll(/https?:\/\/(\[[0-9a-f:]+\]|[^\s/:"'`)>\]]+)/gi)].map(n=>n[1]).some(n=>!tt.test(n)):!1}function g(t){return t.trim().replace(/\s+/g," ")}function st(t,e){if(t===e)return!0;if(Math.abs(t.length-e.length)>1)return!1;if(t.length===e.length){let a=[];for(let c=0;c<t.length;c+=1)if(t[c]!==e[c]&&a.push(c),a.length>2)return!1;return a.length===1?!0:a.length===2&&a[1]===a[0]+1&&t[a[0]]===e[a[1]]&&t[a[1]]===e[a[0]]}let[n,s]=t.length<e.length?[t,e]:[e,t],i=0,r=0,o=!1;for(;i<n.length&&r<s.length;){if(n[i]===s[r]){i+=1,r+=1;continue}if(o)return!1;o=!0,r+=1}return!0}function J(t,e){return(t.toLowerCase().match(/[a-z]+/g)??[]).some(s=>s.length>=5&&e.some(i=>st(s,i)))}function it(t){return Pe.test(g(t))||ke.test(t)||J(t,We)}function y(t){return De.test(t)||J(t,Ue)}function F(t){return t.replace(/[\s_-]+/g,"").toLowerCase()}function P(t){return Array.isArray(t)?t.map(P):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,P(n)])):typeof t=="string"?g(t.replace(/\\/g,"/")):t}function V(t,e){return`${F(t)}:${JSON.stringify(P(e))}`}function G(t){return Ce.has(F(t))}function rt(t,e){let n=F(t);return Ae.has(n)?!0:n==="bash"&&$e.test(N(e)??"")}function v(t){let e=g(t);return!e||e.length>320?!1:Ie.test(e)&&!it(e)&&!Me(e)}function ee(t,e){let n=Math.max(1,Math.floor(e));return v(t)?Math.min(n,xe):n}function ot(t){if(typeof t!="string")return null;let e=g(t).toLowerCase();return e.length>0?e:null}function j(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.hash="",e.pathname=e.pathname.replace(/\/+$/,"")||"/",e.toString().toLowerCase()}catch{let e=g(t).toLowerCase().replace(/#.*$/,"").replace(/\/+$/,"");return e.length>0?e:null}}function N(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():null}function L(t){return typeof t=="string"?[t]:Array.isArray(t)?t.flatMap(L):t&&typeof t=="object"?Object.values(t).flatMap(L):[]}function B(t){return t.replace(/\\/g,"/").toLowerCase()}function H(t){return g([t.output,t.error].filter(Boolean).join(" ")).slice(0,240)}function q(t){return t.success===!1||He.test([t.output,t.error].filter(Boolean).join(`
14
+ `))}function X(t){return/^Bash$/i.test(t)}function z(t){return/^WebSearch$/i.test(t)}function Q(t){return/^WebFetch$/i.test(t)}var h=class{taskPrompt;maxWebSearches;maxWebFetches;maxTotalWebResearchCalls;maxLocalInspectionCalls;simpleInformationalPrompt;explicitResearchPrompt;hostWebBudget;searchQueries=new Map;fetchedUrls=new Map;localInspectionRecords=new Map;localEvidence=[];webFetchEvidence=[];artifactEvidence=[];verificationRecords=[];pendingAwaitOperations=new Map;transcriptReadRanges=new Map;webSearches=0;webFetches=0;localInspectionCalls=0;mutationEpoch=0;constructor(e,n={}){this.taskPrompt=e,this.explicitResearchPrompt=y(e),this.maxWebSearches=Math.max(1,n.maxWebSearches??(this.explicitResearchPrompt?5:3)),this.maxWebFetches=Math.max(1,n.maxWebFetches??(this.explicitResearchPrompt?12:4)),this.hostWebBudget=n.maxWebSearches!==void 0||n.maxWebFetches!==void 0||n.maxTotalWebResearchCalls!==void 0;let s=this.explicitResearchPrompt?16:6;this.maxTotalWebResearchCalls=Math.max(1,n.maxTotalWebResearchCalls??(this.hostWebBudget?Math.max(s,this.maxWebSearches+this.maxWebFetches):s)),this.simpleInformationalPrompt=v(e),this.maxLocalInspectionCalls=Math.max(1,n.maxLocalInspectionCalls??(this.simpleInformationalPrompt?12:Number.MAX_SAFE_INTEGER))}maybeBlockToolCall(e){let n=this.findOverlappingTranscriptRead(e.toolName,e.input);if(n)return this.blockedResult(["[Xeno continuation-state guard]",`This transcript range overlaps an earlier read in the current turn: ${n}`,"Use the structured operation/continuation checkpoint and the existing excerpt. Do not scan the growing session Markdown to rediscover current state."]);if(rt(e.toolName,e.input)){if(this.simpleInformationalPrompt)return this.blockedResult(["[Xeno interactive turn guard]","This is a short informational question, not a request to change files, configuration, packages, processes, or repository state.",`Blocked unrequested mutation through ${e.toolName}.`,"Answer the question from the evidence already available. Ask before making changes if a change would materially help."]);this.mutationEpoch+=1}if(G(e.toolName)){let s=`${this.mutationEpoch}:${V(e.toolName,e.input)}`,i=this.localInspectionRecords.get(s);if(i?.successful||(i?.attempts??0)>=2)return this.blockedResult(["[Xeno interactive turn guard]",i?.successful===!0?`This exact ${e.toolName} inspection already succeeded during the current turn.`:`This exact ${e.toolName} inspection has already failed twice during the current turn.`,"Do not repeat or cosmetically repackage the same inspection. Use the existing result, choose one materially different check, or answer now with the uncertainty that remains."]);if(this.localInspectionCalls>=this.maxLocalInspectionCalls)return this.blockedResult(["[Xeno interactive turn guard]",`The local inspection budget for this turn is exhausted (${this.localInspectionCalls}/${this.maxLocalInspectionCalls}).`,"Stop exploring. Give the shortest accurate answer supported by the evidence already gathered, and state one limitation if needed."]);this.localInspectionCalls+=1,this.localInspectionRecords.set(s,{attempts:(i?.attempts??0)+1,successful:i?.successful??!1})}if(X(e.toolName)&&this.isWebResearchQuestion()){let s=N(e.input);if(s&&nt(s))return this.blockedResult(["[Xeno interactive research guard]","Do not use Bash, Python, PowerShell, curl, wget, or ad hoc scripts to fetch public web pages during a web-research turn.","Use WebSearch to discover sources and WebFetch to read exact URLs. WebFetch handles timeouts, redirects, readable extraction, source metadata, and discovered documentation links.",this.fetchedSourceSummary()])}if(z(e.toolName)){let s=ot(e.input.query),i=s?this.searchQueries.get(s)??0:0;if(this.shouldStopOfficialResearch())return this.blockedResult(["[Xeno interactive research guard]","Official web evidence has already been fetched this turn.",this.fetchedSourceSummary(),"Stop searching. Answer now from the fetched official source(s), naming the URL(s) used and clearly stating any remaining uncertainty."]);if(s&&i>0)return this.blockedResult(["[Xeno interactive research guard]",`The WebSearch query has already been run this turn: ${s}`,"Do not repeat equivalent searches. Use the existing search result, fetch one clearly relevant source, run a local verification command if the question is about this machine, or answer with the uncertainty that remains."]);if(this.webSearches>=this.maxWebSearches||this.totalWebResearchCalls()>=this.maxTotalWebResearchCalls)return this.blockedResult(["[Xeno interactive research guard]",`The per-turn web-search budget is exhausted (${this.webSearches}/${this.maxWebSearches} searches, ${this.totalWebResearchCalls()}/${this.maxTotalWebResearchCalls} total web calls).`,"Stop broad web exploration. Prefer official documentation already found, run a local check if relevant, or give a bounded answer that states what is and is not verified."]);this.webSearches+=1,s&&this.searchQueries.set(s,i+1)}if(Q(e.toolName)){let s=j(e.input.url),i=s?this.fetchedUrls.get(s)??0:0;if(this.shouldStopOfficialResearch())return this.blockedResult(["[Xeno interactive research guard]","Enough official web evidence has already been fetched this turn.",this.fetchedSourceSummary(),"Do not guess more nearby documentation URLs. Answer from the fetched source(s), cite the URL(s), and mention if a specific detail was not present."]);if(s&&i>0)return this.blockedResult(["[Xeno interactive research guard]",`This URL has already been fetched this turn: ${s}`,"Do not fetch the same page again. Use the existing content, fetch a more precise official source, run a local verification command if relevant, or answer with the uncertainty that remains."]);if(this.webFetches>=this.maxWebFetches||this.totalWebResearchCalls()>=this.maxTotalWebResearchCalls)return this.blockedResult(["[Xeno interactive research guard]",`The per-turn web-fetch budget is exhausted (${this.webFetches}/${this.maxWebFetches} fetches, ${this.totalWebResearchCalls()}/${this.maxTotalWebResearchCalls} total web calls).`,"Stop broad web exploration. Use the best source already gathered, run a local check if relevant, or answer with a clear limitation."]);this.webFetches+=1,s&&this.fetchedUrls.set(s,i+1)}return null}recordToolResult(e){let n=e.result.operation;n?.completionPolicy==="await"&&(n.terminal?this.pendingAwaitOperations.delete(n.operationId):this.pendingAwaitOperations.set(n.operationId,n.taskId??n.operationId));for(let r of e.result.evidence??n?.evidence??[]){let o=this.artifactEvidence.findIndex(c=>c.operationId===r.operationId&&c.path===r.path),a={iteration:e.iteration,path:r.path,status:r.status,operationId:r.operationId};o>=0?this.artifactEvidence[o]=a:this.artifactEvidence.push(a)}if(at(e.toolName)&&this.verificationRecords.push({iteration:e.iteration,toolName:e.toolName,inputValues:L(e.input),success:e.result.success===!0&&!q(e.result)}),G(e.toolName)){let r=`${this.mutationEpoch}:${V(e.toolName,e.input)}`,o=this.localInspectionRecords.get(r);o&&(o.successful=o.successful||e.result.success===!0)}if(z(e.toolName))return;if(Q(e.toolName)){let r=j(e.input.url);r&&this.webFetchEvidence.push({iteration:e.iteration,url:r,success:e.result.success===!0,summary:H(e.result)});return}if(!X(e.toolName)||!this.isLocalSetupQuestion())return;let s=N(e.input);if(!s||!Ge.test(s))return;let i=q(e.result);this.localEvidence.push({iteration:e.iteration,command:s,success:e.result.success===!0&&!i,summary:H(e.result)})}evaluateCompletion(e){if(this.pendingAwaitOperations.size>0)return{blocking:!0,message:["[Xeno pending-operation guard]",`Awaited operation(s) are still nonterminal: ${Array.from(this.pendingAwaitOperations.values()).join(", ")}.`,"Suspend this turn without a final answer. The runtime will resume the objective exactly once when the operation becomes terminal."].join(`
15
+ `)};let n=this.evaluateArtifactClaims(e.finalText);if(n)return n;if(this.isWebResearchQuestion()){let o=this.evaluateWebResearchCompletion(e.finalText);if(o)return o}if(!this.isLocalSetupQuestion())return null;let s=[...this.localEvidence].reverse().find(o=>!o.success);if(!s||this.localEvidence.some(o=>o.iteration>=s.iteration&&o.success))return null;let r=e.finalText.trim();return!r||!je.test(r)||Be.test(r)?null:{blocking:!0,message:["[Xeno evidence correction]","Do not claim the local tool/app/CLI is installed or working yet.",`The latest local verification command failed: ${s.command}`,s.summary?`Failure evidence: ${s.summary}`:null,"Next step: either run one robust local verification command that directly proves the claim, or answer that the launcher/path may exist but the CLI status is not confirmed.","Do not use web documentation as proof of what is installed on this machine."].filter(Boolean).join(`
16
+ `)}}evaluateWebResearchCompletion(e){let n=e.trim();if(!n)return null;let s=this.successfulWebFetches(),i=s.map(a=>a.url),r=et.test(n),o=i.some(a=>n.toLowerCase().includes(a.toLowerCase()));return s.length>0&&(!r||!o)?{blocking:!0,message:["[Xeno source-citation correction]","The answer uses web/documentation evidence but does not clearly cite the fetched source URL(s).",this.fetchedSourceSummary(),"Rewrite the final answer with a short Sources section using Markdown links like `Sources: [Title](url)`, then the requested sections. Do not run more tools unless a required detail is still missing."].join(`
17
+ `)}:null}isLocalSetupQuestion(){return Ve.test(this.taskPrompt)}totalWebResearchCalls(){return this.webSearches+this.webFetches}isOfficialResearchQuestion(){return Ke.test(this.taskPrompt)}isWebResearchQuestion(){return this.explicitResearchPrompt||Ye.test(this.taskPrompt)}successfulWebFetches(){return this.webFetchEvidence.filter(e=>e.success)}failedSpeculativeWebFetches(){return this.webFetchEvidence.filter(e=>!e.success&&Ze.test(e.summary))}shouldStopOfficialResearch(){if(this.explicitResearchPrompt||this.hostWebBudget||!this.isOfficialResearchQuestion())return!1;let e=this.successfulWebFetches();return e.length>=this.minimumOfficialEvidenceFetches()?!0:e.length>=1&&this.failedSpeculativeWebFetches().length>=1}minimumOfficialEvidenceFetches(){let e=this.taskPrompt.toLowerCase(),n=/\binstall(?:ation)?|update|upgrade|version|verify\b/.test(e),s=/\binteractive|usage|using|agent\s+commands?|session|resume|flags?|shortcuts?\b/.test(e),i=/\bslash|reference|commands?\s+list|all\s+commands?\b/.test(e);return n&&s||i?Math.min(4,this.maxWebFetches):2}fetchedSourceSummary(){let e=this.successfulWebFetches().map(n=>n.url);return e.length===0?"No successful web fetch is recorded yet.":`Fetched source(s): ${e.join(", ")}`}blockedResult(e){return{success:!1,output:e.join(`
18
+ `),error:"Interactive turn guard blocked redundant, excessive, or unrequested tool use"}}evaluateArtifactClaims(e){let n=e.trim();if(!qe.test(n)||Xe.test(n))return null;let s=this.artifactEvidence.filter(o=>o.status==="verified");if(s.length===0){let o=this.artifactEvidence.filter(a=>a.status==="failed");return{blocking:!0,message:["[Xeno artifact-evidence guard]","Do not claim that an artifact was created, saved, converted, or written without current verified artifact evidence.",o.length>0?`The latest postcondition evidence failed for: ${o.map(a=>a.path??a.operationId).join(", ")}.`:"No successful artifact postcondition is recorded in this turn.","Inspect the target, verify it is the expected file, and only then give the completion answer."].join(`
19
+ `)}}if(!ze.test(n))return null;let i=Math.max(...s.map(o=>o.iteration));return this.verificationRecords.some(o=>o.success&&o.iteration>=i&&s.some(a=>!a.path||o.inputValues.some(c=>B(c).includes(B(a.path)))))?null:{blocking:!0,message:["[Xeno semantic-evidence guard]","File existence does not prove semantic claims such as page count, OCR absence, dimensions, metadata, or successful rendering.","Run one bounded verifier against the generated artifact and then report only the properties that verifier established."].join(`
20
+ `)}}findOverlappingTranscriptRead(e,n){if(!/^Read$/i.test(e))return null;let s=typeof n.file_path=="string"?n.file_path:"";if(!Qe.test(s))return null;let i=Math.max(0,Number.isFinite(n.offset)?Math.floor(Number(n.offset)):0),r=Math.max(1,Number.isFinite(n.limit)?Math.floor(Number(n.limit)):2e3),o=i+r,a=s.toLowerCase(),c=this.transcriptReadRanges.get(a)??[],d=c.find(l=>i<l.end&&o>l.start);return d?`${s}:${i}-${o} overlaps ${d.start}-${d.end}`:(c.push({start:i,end:o}),this.transcriptReadRanges.set(a,c),null)}};function at(t){return/^(?:Bash|Read|ReadImage|ElfAnalyze|NotebookRead)$/i.test(t)}var w=class{constructor(e={}){this.options=e}options;active=null;activePrompt=null;promptSection={name:"interactive-chat-answer-budget",order:20,provide:()=>this.activePrompt?y(this.activePrompt)?[`
22
21
 
23
22
  <interactive_research_budget>`,"The user explicitly requested research. Gather enough primary evidence to answer the requested scope; do not treat this as a four-fetch quick lookup.","Start broad once, then fetch distinct targeted sources. For a public repository, prefer repository metadata, one recursive tree, and only the files needed for the answer.","Do not fetch duplicate representations of the same content or guess files already disproved by the repository tree.","Synthesize the answer once the evidence is sufficient. Tool limits preserve a separate tool-free final-answer turn.","</interactive_research_budget>"].join(`
24
- `):w(this.activePrompt)?[`
23
+ `):v(this.activePrompt)?[`
25
24
 
26
25
  <interactive_answer_budget>`,"This turn is a short informational question, not an implementation request.","Answer directly when the current context already contains the answer.","If local verification is genuinely needed, use one broad lookup and at most one targeted read, then answer.","Do not modify files, configuration, packages, processes, or repository state. Do not convert the question into an installation or workflow task.","</interactive_answer_budget>"].join(`
27
- `):null:null};toolMiddleware=async(e,n)=>{let i=this.active;if(!i)return n();let r=i.maybeBlockToolCall({toolName:e.toolName,input:e.input,iteration:e.iteration});if(r)return r;let s=await n();return i.recordToolResult({toolName:e.toolName,input:e.input,result:s,iteration:e.iteration}),s};completionGuard={name:"interactive-chat-turn-governance",order:10,evaluate:e=>{let n=this.active?.evaluateCompletion({finalText:e.finalText,iteration:e.iteration,stopReason:e.stopReason});return n?{allow:!1,guidance:n.message}:{allow:!0}}};beginTurn(e){this.activePrompt=e,this.active=new h(e)}endTurn(){this.active=null,this.activePrompt=null}};var re=String.raw`(?:^|[\n;&|]\s*|\(\s*)`,Rt=new RegExp(String.raw`${re}(?:timeout\s+\S+\s+)?(?:sudo\s+)?eval\s+(?:"|'|)?\$\(\s*(?:curl|wget)\b`,"i"),xt=new RegExp(`${re}(?:timeout\\s+\\S+\\s+)?(?:sudo\\s+)?(?:env\\s+(?:\\S+=\\S+\\s+)*)?(?:make(?:\\s|$)|cmake\\s+--build\\b|ninja\\b|cargo\\s+build\\b|go\\s+build\\b)`,"i"),Et=/\b(?:make|ninja|cmake\s+--build)\b[\s\S]*?(?:^|\s)-j\s*(?:\$\(?nproc\)?|[5-9]\b|\d{2,}\b)/i,Tt=900,At=/\b(?:cifar(?:-?10)?|mnist|imagenet|yelp|fasttext|wikitext|c4|common\s*crawl|glue|squad|train(?:ing)?[_ -]?data|test[_ -]?data|lmdb)\b/i,_t=/\b(?:synthetic|fake|dummy|placeholder|random(?:\.|_|ness|\b)|randint|randn|np\.random|os\.urandom|bytearray|generate(?:d|s)?\s+(?:data|dataset|samples?|images?|records?)|make_img|SYNTHETIC[_ -]?DATA)\b/i,St=/\b(?:>\s*|tee\s+|open\s*\(|write(?:_text|_bytes)?\s*\(|to_csv\s*\(|np\.save|torch\.save|pickle\.dump|lmdb|create[_ -]?(?:dataset|data)|mkdir(?:\s+-p)?|rm\s+-rf)\b/i,Ct=/\btimeout\s+(\d+)([smhd]?)/i;function It(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():null}function Pt(t){return/^Bash$/i.test(t)}function Nt(t){let e=t.match(Ct);if(!e)return null;let n=Number(e[1]);if(!Number.isFinite(n))return null;let i=e[2]?.toLowerCase();return i==="h"?n*3600:i==="m"?n*60:i==="d"?n*86400:n}function Lt(t){if(!xt.test(t))return null;if(Et.test(t))return["[xeno guidance]","This finite source build uses an unbounded or oversized parallelism setting such as -j$(nproc).","In benchmark containers this often slows the build down or causes timeout/memory failure instead of making progress.","Rerun the build with conservative parallelism such as -j2 or -j4, keep logs visible, and continue from the existing partial build artifacts."].join(`
28
- `);let e=Nt(t);return e!==null&&e<Tt?["[xeno guidance]",`This required finite build is wrapped in a shell timeout of ${e}s.`,"Do not use a too-short shell timeout around source builds where partial output is not the final artifact.","Use the Bash tool timeout instead, run with conservative parallelism such as -j2 or -j4, and preserve final budget for verifier/training only after the build succeeds."].join(`
29
- `):null}function Mt(t){return!At.test(t)||!_t.test(t)||!St.test(t)?null:["[xeno guidance]","This command appears to synthesize or overwrite a named/provided training dataset.","Do not replace CIFAR, MNIST, Yelp, C4, LMDB, or other task datasets with random, synthetic, dummy, or placeholder data to recover from a crash.","Fix the real data path instead: repair the download/extraction/conversion/dependency issue, remove corrupted partial outputs, and rerun only the failed stage with bounded resources."].join(`
30
- `)}function Ft(t){return Rt.test(t)}function Ot(){return{success:!1,output:["[Xeno benchmark Bash guard]",'Blocked a shell-eval-download command (eval "$(curl \xE2\u20AC\xA6)" / eval "$(wget \xE2\u20AC\xA6)").',"Piping remote content straight into a shell evaluator is unsafe and non-reproducible.","Download the artifact to a file with WebFetch or curl/wget, inspect it, then run the verified script explicitly."].join(`
31
- `),error:"Benchmark Bash guard blocked a shell-eval-download command"}}function S(t={}){let e=t.benchmarkMode===!0;return async(n,i)=>{if(!Pt(n.toolName))return i();let r=It(n.input);if(!r)return i();if(Ft(r))return Ot();if(e){let s=Lt(r);s&&n.addGuidance(s);let a=Mt(r);a&&n.addGuidance(a)}return i()}}var se=`
32
-
33
- `;function jt(t){let e=t.taskPrompt??"",n=t.benchmarkMode===!0,i=t.requiredOutputPaths??[],r=t.interactiveTurnGovernance===!1?null:new h(e,t.interactiveTurnGovernance??{}),a=(t.executionGovernance===!1?!1:t.executionGovernance===!0||y({taskPrompt:e,benchmarkMode:n,requiredOutputPaths:i}))?new p({taskPrompt:e,benchmarkMode:n,requiredOutputPaths:i}):null,o=a?.getSummary()??null,c=[];(r||a)&&c.push(async(l,u)=>{if(r){let O=r.maybeBlockToolCall({toolName:l.toolName,input:l.input,iteration:l.iteration});if(O)return O}let g=await u();return r&&r.recordToolResult({toolName:l.toolName,input:l.input,result:g,iteration:l.iteration}),a&&(a.recordToolResult({toolName:l.toolName,input:l.input,result:g,iteration:l.iteration}),o=a.getSummary(),t.onExecutionGovernanceUpdate?.(o)),g}),c.push(S({benchmarkMode:n}));let d=[];r&&d.push({name:"interactive-turn-governance",order:10,evaluate(l){let u=r.evaluateCompletion({finalText:l.finalText,iteration:l.iteration,stopReason:l.stopReason});return u?{allow:!1,guidance:u.message}:{allow:!0}}}),a&&d.push({name:"execution-governance",order:20,evaluate(l){let u=a.evaluateCompletion({finalText:l.finalText,iteration:l.iteration,stopReason:l.stopReason,messages:l.messages,maxIterations:l.maxIterations});if(o=a.getSummary(),t.onExecutionGovernanceUpdate?.(o),u.action==="complete"||!u.blocking)return{allow:!0};let g=u.action==="incomplete";return{allow:!1,guidance:u.message,stop:g}}});let m=[];return t.promptGuidance!==!1&&(m.push({name:"contract-ledger",order:100,provide(l){let u=k(l.taskPrompt??e);return u?`${se}${u.replace(/^\n+/,"")}`:null}}),m.push({name:"project-execution",order:110,provide(l){let u=E(l.taskPrompt??e);return u?`${se}${u.replace(/^\n+/,"")}`:null}})),{toolMiddleware:c,promptSections:m,completionGuards:d,getExecutionGovernanceSummary:()=>o}}0&&(module.exports={ExecutionGovernance,InteractiveChatTurnGovernance,InteractiveTurnGovernance,buildContractLedgerGuidance,buildProjectBudgetFinalizationGuidance,buildProjectExecutionGuidance,buildProjectExecutionProfile,createBenchBashMiddleware,createGovernanceExtensions,isExplicitResearchPrompt,isSimpleInformationalPrompt,resolveInteractiveTurnMaxIterations,shouldEnableExecutionGovernance});
26
+ `):null:null};toolMiddleware=async(e,n)=>{let s=this.active;if(!s)return n();let i=s.maybeBlockToolCall({toolName:e.toolName,input:e.input,iteration:e.iteration});if(i)return i;let r=await n();return s.recordToolResult({toolName:e.toolName,input:e.input,result:r,iteration:e.iteration}),r};completionGuard={name:"interactive-chat-turn-governance",order:10,evaluate:e=>{let n=this.active?.evaluateCompletion({finalText:e.finalText,iteration:e.iteration,stopReason:e.stopReason});return n?{allow:!1,guidance:n.message}:{allow:!0}}};beginTurn(e){this.activePrompt=e,this.active=new h(e,this.options)}endTurn(){this.active=null,this.activePrompt=null}};var lt=String.raw`(?:^|[\n;&|]\s*|\(\s*)`,ct=new RegExp(String.raw`${lt}(?:timeout\s+\S+\s+)?(?:sudo\s+)?eval\s+(?:"|'|)?\$\(\s*(?:curl|wget)\b`,"i");function O(t){return ct.test(t)}function ut(){return{success:!1,output:['Blocked: this command evaluates downloaded content directly in the shell (eval "$(curl ...)" or eval "$(wget ...)").',"Running remote content unseen is unsafe and cannot be reproduced.","Download it to a file, read it, then run the script explicitly."].join(`
27
+ `),error:"Blocked a command that evaluates downloaded content in the shell"}}function b(){return async(t,e)=>{if(!/^Bash$/i.test(t.toolName))return e();let n=typeof t.input.command=="string"?t.input.command.trim():"";return n&&O(n)?ut():e()}}function te(t){return""}function ne(t){return""}function se(t){return""}function ie(t){return{projectLike:!1,domains:[],phases:[],verifierRequirements:[],finalAuditItems:[]}}function re(t){return!0}function oe(t={}){return b()}function dt(t){let e=t.taskPrompt??"",n=t.requiredOutputPaths??[],s=t.interactiveTurnGovernance===!1?null:new h(e,t.interactiveTurnGovernance??{}),r=t.executionGovernance!==!1?new f({taskPrompt:e,requiredOutputPaths:n,...t.cwd?{cwd:t.cwd}:{}}):null,o=r?.getSummary()??null,a=[];(s||r)&&a.push(async(l,u)=>{if(s){let S=s.maybeBlockToolCall({toolName:l.toolName,input:l.input,iteration:l.iteration});if(S)return S}let m=await u();return s&&s.recordToolResult({toolName:l.toolName,input:l.input,result:m,iteration:l.iteration}),r&&(r.recordToolResult({toolName:l.toolName,input:l.input,result:m,iteration:l.iteration}),o=r.getSummary(),t.onExecutionGovernanceUpdate?.(o)),m}),a.push(b());let c=[];return s&&c.push({name:"interactive-turn-governance",order:10,evaluate(l){let u=s.evaluateCompletion({finalText:l.finalText,iteration:l.iteration,stopReason:l.stopReason});return u?{allow:!1,guidance:u.message}:{allow:!0}}}),r&&c.push({name:"execution-governance",order:20,evaluate(l){let u=r.evaluateCompletion({finalText:l.finalText,iteration:l.iteration,stopReason:l.stopReason,messages:l.messages,maxIterations:l.maxIterations});if(o=r.getSummary(),t.onExecutionGovernanceUpdate?.(o),u.action==="complete")return{allow:!0,...u.reason==="authoritative_validation_passed"||u.reason==="self_validation_passed"?{final:!0}:{}};if(!u.blocking)return{allow:!0};let m=u.action==="incomplete";return{allow:!1,guidance:u.message,stop:m,blocking:!m}}}),{toolMiddleware:a,promptSections:[],completionGuards:c,getExecutionGovernanceSummary:()=>o}}0&&(module.exports={ExecutionGovernance,InteractiveChatTurnGovernance,InteractiveTurnGovernance,MAX_HOST_WEB_FETCHES_PER_TURN,MAX_HOST_WEB_SEARCHES_PER_TURN,buildContractLedgerGuidance,buildProjectBudgetFinalizationGuidance,buildProjectExecutionGuidance,buildProjectExecutionProfile,createBenchBashMiddleware,createGovernanceExtensions,createRemoteEvalGuard,findMissingRequiredOutputs,isExplicitResearchPrompt,isRemoteEvalCommand,isSimpleInformationalPrompt,parseWebResearchBudget,resolveInteractiveTurnMaxIterations,shouldEnableExecutionGovernance});
@@ -203,11 +203,18 @@ interface CompletionGuardEvaluationContext {
203
203
  }
204
204
  type CompletionGuardDecision = {
205
205
  allow: true;
206
+ final?: boolean;
206
207
  } | {
207
208
  allow: false;
208
209
  guidance: string;
209
210
  stop?: boolean;
211
+ blocking?: boolean;
212
+ toolPolicy?: CompletionGuardToolPolicy;
210
213
  };
214
+ interface CompletionGuardToolPolicy {
215
+ mode: string;
216
+ [key: string]: unknown;
217
+ }
211
218
  interface CompletionGuard {
212
219
  name: string;
213
220
  order?: number;
@@ -239,9 +246,9 @@ interface ValidationSignal {
239
246
  clusters: FailureCluster[];
240
247
  }
241
248
  interface ContractLedgerSummary {
249
+ requiredOutputPaths: string[];
242
250
  projectLike: boolean;
243
251
  benchmarkMode: boolean;
244
- requiredOutputPaths: string[];
245
252
  requiredValidation: boolean;
246
253
  }
247
254
  interface ValidationLedgerSummary {
@@ -277,23 +284,33 @@ interface ExecutionGovernanceOptions {
277
284
  taskPrompt?: string;
278
285
  benchmarkMode?: boolean;
279
286
  requiredOutputPaths?: string[];
287
+ cwd?: string;
288
+ }
289
+ interface MissingRequiredOutput {
290
+ path: string;
291
+ problem: "missing" | "empty" | "not_a_file";
280
292
  }
293
+ declare function findMissingRequiredOutputs(paths: readonly string[], cwd?: string): MissingRequiredOutput[];
281
294
  interface RecordToolResultInput {
282
295
  toolName: string;
283
296
  input: Record<string, unknown>;
284
297
  result: ToolResult;
285
298
  iteration: number;
286
299
  }
287
- declare function shouldEnableExecutionGovernance(options: ExecutionGovernanceOptions): boolean;
288
300
  declare class ExecutionGovernance {
289
301
  private readonly contract;
290
302
  private readonly signals;
291
303
  private readonly clusters;
292
304
  private toolCalls;
293
305
  private workspaceRevision;
306
+ private readonly ownTasks;
307
+ private nextOwnTaskId;
308
+ private uncheckedChangesAdvised;
294
309
  private lastCompletionDecision;
295
310
  private lastValidationIteration;
296
311
  private lastEvaluatedIteration;
312
+ private readonly cwd;
313
+ private readonly taskPrompt;
297
314
  constructor(options?: ExecutionGovernanceOptions);
298
315
  recordToolResult(input: RecordToolResultInput): ValidationSignal[];
299
316
  evaluateCompletion(args: {
@@ -337,6 +354,14 @@ interface InteractiveGovernanceDecision {
337
354
  message: string;
338
355
  blocking: boolean;
339
356
  }
357
+ declare const MAX_HOST_WEB_SEARCHES_PER_TURN = 200;
358
+ declare const MAX_HOST_WEB_FETCHES_PER_TURN = 500;
359
+ interface WebResearchBudgetInput {
360
+ searches?: string | number;
361
+ fetches?: string | number;
362
+ calls?: string | number;
363
+ }
364
+ declare function parseWebResearchBudget(input: WebResearchBudgetInput): InteractiveTurnGovernanceOptions;
340
365
  declare function isExplicitResearchPrompt(taskPrompt: string): boolean;
341
366
  declare function isSimpleInformationalPrompt(taskPrompt: string): boolean;
342
367
  declare function resolveInteractiveTurnMaxIterations(taskPrompt: string, configuredMaxIterations: number): number;
@@ -348,6 +373,7 @@ declare class InteractiveTurnGovernance {
348
373
  private readonly maxLocalInspectionCalls;
349
374
  private readonly simpleInformationalPrompt;
350
375
  private readonly explicitResearchPrompt;
376
+ private readonly hostWebBudget;
351
377
  private readonly searchQueries;
352
378
  private readonly fetchedUrls;
353
379
  private readonly localInspectionRecords;
@@ -380,52 +406,52 @@ declare class InteractiveTurnGovernance {
380
406
  private findOverlappingTranscriptRead;
381
407
  }
382
408
  declare class InteractiveChatTurnGovernance {
409
+ private readonly options;
383
410
  private active;
384
411
  private activePrompt;
385
412
  readonly promptSection: PromptSectionProvider;
386
413
  readonly toolMiddleware: ToolMiddleware;
387
414
  readonly completionGuard: CompletionGuard;
415
+ constructor(options?: InteractiveTurnGovernanceOptions);
388
416
  beginTurn(taskPrompt: string): void;
389
417
  endTurn(): void;
390
418
  }
391
- declare function buildContractLedgerGuidance(userPrompt?: string): string;
392
- type ProjectDomainKey = "ml_artifact" | "visual_artifact" | "structured_data" | "performance" | "compiler_emulator" | "service_vm" | "search_symbolic" | "security_sanitization" | "science_bio_numeric" | "binary_recovery" | "async_process";
419
+ declare function isRemoteEvalCommand(command: string): boolean;
420
+ declare function createRemoteEvalGuard(): ToolMiddleware;
393
421
  interface ProjectDomainProfile {
394
- key: ProjectDomainKey;
422
+ id: string;
395
423
  label: string;
396
- trigger: RegExp;
397
424
  verifierRequirements: string[];
398
425
  finalAuditItems: string[];
399
426
  }
400
427
  interface ProjectExecutionPhase {
401
- name: "inspect" | "baseline" | "implement" | "validate" | "finalize";
402
- budgetPercent: number;
428
+ id: string;
429
+ title: string;
403
430
  objective: string;
404
431
  }
405
432
  interface ProjectExecutionProfile {
406
433
  projectLike: boolean;
407
- hiddenVerifierLikely: boolean;
408
- requiredOutputs: string[];
409
- referencedPaths: string[];
410
434
  domains: ProjectDomainProfile[];
411
435
  phases: ProjectExecutionPhase[];
412
436
  verifierRequirements: string[];
413
437
  finalAuditItems: string[];
414
438
  }
415
- declare function buildProjectExecutionProfile(prompt?: string): ProjectExecutionProfile;
416
- declare function buildProjectExecutionGuidance(prompt?: string): string;
417
- declare function buildProjectBudgetFinalizationGuidance(prompt?: string): string;
418
439
  interface BenchBashMiddlewareOptions {
419
440
  benchmarkMode?: boolean;
420
441
  }
421
- declare function createBenchBashMiddleware(options?: BenchBashMiddlewareOptions): ToolMiddleware;
442
+ declare function buildContractLedgerGuidance(_userPrompt?: string): string;
443
+ declare function buildProjectExecutionGuidance(_prompt?: string): string;
444
+ declare function buildProjectBudgetFinalizationGuidance(_prompt?: string): string;
445
+ declare function buildProjectExecutionProfile(_prompt?: string): ProjectExecutionProfile;
446
+ declare function shouldEnableExecutionGovernance(_options?: unknown): boolean;
447
+ declare function createBenchBashMiddleware(_options?: BenchBashMiddlewareOptions): ToolMiddleware;
422
448
  interface GovernanceExtensionsOptions {
423
449
  taskPrompt: string;
424
450
  benchmarkMode?: boolean;
425
451
  requiredOutputPaths?: string[];
452
+ cwd?: string;
426
453
  interactiveTurnGovernance?: InteractiveTurnGovernanceOptions | false;
427
454
  executionGovernance?: boolean;
428
- promptGuidance?: boolean;
429
455
  onExecutionGovernanceUpdate?: (summary: ExecutionGovernanceSummary) => void | Promise<void>;
430
456
  }
431
457
  interface GovernanceExtensions {
@@ -435,4 +461,4 @@ interface GovernanceExtensions {
435
461
  getExecutionGovernanceSummary(): ExecutionGovernanceSummary | null;
436
462
  }
437
463
  declare function createGovernanceExtensions(options: GovernanceExtensionsOptions): GovernanceExtensions;
438
- export { type BenchBashMiddlewareOptions, type CompletionDecision, ExecutionGovernance, type ExecutionGovernanceOptions, type ExecutionGovernanceSummary, type FailureCluster, type GovernanceExtensions, type GovernanceExtensionsOptions, InteractiveChatTurnGovernance, InteractiveTurnGovernance, type InteractiveTurnGovernanceOptions, type ProjectDomainProfile, type ProjectExecutionPhase, type ProjectExecutionProfile, type ValidationSignal, buildContractLedgerGuidance, buildProjectBudgetFinalizationGuidance, buildProjectExecutionGuidance, buildProjectExecutionProfile, createBenchBashMiddleware, createGovernanceExtensions, isExplicitResearchPrompt, isSimpleInformationalPrompt, resolveInteractiveTurnMaxIterations, shouldEnableExecutionGovernance };
464
+ export { type BenchBashMiddlewareOptions, type CompletionDecision, ExecutionGovernance, type ExecutionGovernanceOptions, type ExecutionGovernanceSummary, type FailureCluster, type GovernanceExtensions, type GovernanceExtensionsOptions, InteractiveChatTurnGovernance, InteractiveTurnGovernance, type InteractiveTurnGovernanceOptions, MAX_HOST_WEB_FETCHES_PER_TURN, MAX_HOST_WEB_SEARCHES_PER_TURN, type ProjectDomainProfile, type ProjectExecutionPhase, type ProjectExecutionProfile, type ValidationSignal, type WebResearchBudgetInput, buildContractLedgerGuidance, buildProjectBudgetFinalizationGuidance, buildProjectExecutionGuidance, buildProjectExecutionProfile, createBenchBashMiddleware, createGovernanceExtensions, createRemoteEvalGuard, findMissingRequiredOutputs, isExplicitResearchPrompt, isRemoteEvalCommand, isSimpleInformationalPrompt, parseWebResearchBudget, resolveInteractiveTurnMaxIterations, shouldEnableExecutionGovernance };