@xenosystem/agent-sdk 0.9.11 → 0.9.14

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.
Files changed (102) hide show
  1. package/LICENSE +15 -15
  2. package/README.md +511 -511
  3. package/dist/agents/index.cjs +5 -5
  4. package/dist/agents/index.js +15 -15
  5. package/dist/agents/metafile-cjs.json +1 -1
  6. package/dist/agents/metafile-esm.json +1 -1
  7. package/dist/artifacts/index.cjs +1 -1
  8. package/dist/artifacts/index.js +1 -1
  9. package/dist/artifacts/metafile-cjs.json +1 -1
  10. package/dist/artifacts/metafile-esm.json +1 -1
  11. package/dist/automation/index.d.cts +1 -0
  12. package/dist/automation/index.d.ts +1 -0
  13. package/dist/automation/metafile-cjs.json +1 -1
  14. package/dist/automation/metafile-esm.json +1 -1
  15. package/dist/control-plane/index.cjs +1 -1
  16. package/dist/control-plane/index.js +1 -1
  17. package/dist/control-plane/metafile-cjs.json +1 -1
  18. package/dist/control-plane/metafile-esm.json +1 -1
  19. package/dist/control-room/metafile-cjs.json +1 -1
  20. package/dist/control-room/metafile-esm.json +1 -1
  21. package/dist/electron/index.cjs +107 -107
  22. package/dist/electron/index.d.cts +8 -0
  23. package/dist/electron/index.d.ts +8 -0
  24. package/dist/electron/index.js +103 -103
  25. package/dist/electron/metafile-cjs.json +1 -1
  26. package/dist/electron/metafile-esm.json +1 -1
  27. package/dist/governance/index.cjs +18 -18
  28. package/dist/governance/index.d.cts +1 -0
  29. package/dist/governance/index.d.ts +1 -0
  30. package/dist/governance/index.js +18 -18
  31. package/dist/governance/metafile-cjs.json +1 -1
  32. package/dist/governance/metafile-esm.json +1 -1
  33. package/dist/hooks/metafile-cjs.json +1 -1
  34. package/dist/hooks/metafile-esm.json +1 -1
  35. package/dist/hosted/index.cjs +1 -1
  36. package/dist/hosted/index.js +1 -1
  37. package/dist/hosted/metafile-cjs.json +1 -1
  38. package/dist/hosted/metafile-esm.json +1 -1
  39. package/dist/index.cjs +347 -329
  40. package/dist/index.d.cts +113 -2
  41. package/dist/index.d.ts +113 -2
  42. package/dist/index.js +329 -311
  43. package/dist/intelligence/metafile-cjs.json +1 -1
  44. package/dist/intelligence/metafile-esm.json +1 -1
  45. package/dist/mcp/index.d.cts +1 -0
  46. package/dist/mcp/index.d.ts +1 -0
  47. package/dist/mcp/metafile-cjs.json +1 -1
  48. package/dist/mcp/metafile-esm.json +1 -1
  49. package/dist/metafile-cjs.json +1 -1
  50. package/dist/metafile-esm.json +1 -1
  51. package/dist/oracle/metafile-cjs.json +1 -1
  52. package/dist/oracle/metafile-esm.json +1 -1
  53. package/dist/providers/metafile-cjs.json +1 -1
  54. package/dist/providers/metafile-esm.json +1 -1
  55. package/dist/recipes/metafile-cjs.json +1 -1
  56. package/dist/recipes/metafile-esm.json +1 -1
  57. package/dist/research/metafile-cjs.json +1 -1
  58. package/dist/research/metafile-esm.json +1 -1
  59. package/dist/session/index.cjs +2 -2
  60. package/dist/session/index.d.cts +8 -0
  61. package/dist/session/index.d.ts +8 -0
  62. package/dist/session/index.js +2 -2
  63. package/dist/session/metafile-cjs.json +1 -1
  64. package/dist/session/metafile-esm.json +1 -1
  65. package/dist/sharing/metafile-cjs.json +1 -1
  66. package/dist/sharing/metafile-esm.json +1 -1
  67. package/dist/skills/index.d.cts +1 -0
  68. package/dist/skills/index.d.ts +1 -0
  69. package/dist/skills/metafile-cjs.json +1 -1
  70. package/dist/skills/metafile-esm.json +1 -1
  71. package/dist/soul/metafile-cjs.json +1 -1
  72. package/dist/soul/metafile-esm.json +1 -1
  73. package/dist/terminal/metafile-cjs.json +1 -1
  74. package/dist/terminal/metafile-esm.json +1 -1
  75. package/dist/ui/index.d.cts +1 -0
  76. package/dist/ui/index.d.ts +1 -0
  77. package/dist/ui/metafile-cjs.json +1 -1
  78. package/dist/ui/metafile-esm.json +1 -1
  79. package/dist/utils/index.d.cts +1 -0
  80. package/dist/utils/index.d.ts +1 -0
  81. package/dist/utils/metafile-cjs.json +1 -1
  82. package/dist/utils/metafile-esm.json +1 -1
  83. package/native/mxc/LICENSE.microsoft-mxc-sdk.md +20 -20
  84. package/native/mxc/README.md +25 -25
  85. package/native/mxc/package.json +58 -58
  86. package/ownership/CLEAN_ROOM_CONTRIBUTOR_GUIDE.md +63 -63
  87. package/ownership/evidence/PROPRIETARY-COMMAND-1/implementation-record.md +77 -77
  88. package/ownership/evidence/PROPRIETARY-COMMAND-1/provenance-review.md +51 -51
  89. package/ownership/evidence/PROPRIETARY-MEDIA-1/implementation-record.md +131 -131
  90. package/ownership/evidence/PROPRIETARY-MEDIA-1/provenance-review.md +50 -50
  91. package/ownership/evidence/PROPRIETARY-PTY-1/implementation-record.md +86 -86
  92. package/ownership/evidence/PROPRIETARY-PTY-1/provenance-review.md +52 -52
  93. package/ownership/evidence/PROPRIETARY-RUNTIME-1/implementation-record.md +68 -68
  94. package/ownership/evidence/PROPRIETARY-RUNTIME-1/provenance-review.md +32 -32
  95. package/ownership/evidence/PROPRIETARY-TOOLCHAIN-1/implementation-record.md +53 -53
  96. package/ownership/evidence/PROPRIETARY-TOOLCHAIN-1/provenance-review.md +32 -32
  97. package/ownership/evidence/PROPRIETARY-UI-1/implementation-record.md +96 -96
  98. package/ownership/evidence/PROPRIETARY-UI-1/provenance-review.md +46 -46
  99. package/ownership/ownership-policy.schema.json +192 -192
  100. package/ownership/templates/clean-room-implementation-record.md +70 -70
  101. package/ownership/templates/provenance-review.md +51 -51
  102. package/package.json +1 -1
@@ -1,33 +1,33 @@
1
- var ne=/(?:[A-Za-z]:\\[^\s"'`<>|]+|\/[^\s"'`<>|]+)/g,ie=[/\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],re=/(?:"([^"\n]{4,240})"|'([^'\n]{4,240})'|`([^`\n]{4,240})`)/g,se=/(?:^|\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,ae=/\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,oe=[{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 O(t){return t.trim().replace(/^[`'"]+|[`'"]+$/g,"").replace(/[.,;:)\]]+$/g,"").trim()}function D(t){return t.length===0||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("//")}function f(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 ce(t){let e=[];for(let n of ie){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]?O(r[1]):"";D(s)||e.push(s)}}return f(e,8)}function le(t,e){let n=new Set(e),i=t.match(ne)??[];return f(i.map(r=>O(r)).filter(r=>!D(r)&&!n.has(r)),8)}function ue(t){let e=[],n;for(;(n=re.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 f(e,6)}function de(t){let e=[],n;for(;(n=se.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 f(e,6)}function me(t){let e=[],n;for(;(n=ae.exec(t))!==null;)e.push(n[0].replace(/\s+/g," ").trim());return f(e,6)}function he(t){return oe.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 x(t){let e=t?.trim()??"";if(!e)return"";let n=ce(e),i=le(e,n),r=ue(e),s=de(e),a=me(e),o=he(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(`
1
+ var ne=/(?:[A-Za-z]:\\[^\s"'`<>|]+|\/[^\s"'`<>|]+)/g,ie=[/\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],re=/(?:"([^"\n]{4,240})"|'([^'\n]{4,240})'|`([^`\n]{4,240})`)/g,se=/(?:^|\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,ae=/\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,oe=[{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 O(t){return t.trim().replace(/^[`'"]+|[`'"]+$/g,"").replace(/[.,;:)\]]+$/g,"").trim()}function D(t){return t.length===0||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("//")}function g(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 ce(t){let e=[];for(let n of ie){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]?O(r[1]):"";D(s)||e.push(s)}}return g(e,8)}function le(t,e){let n=new Set(e),i=t.match(ne)??[];return g(i.map(r=>O(r)).filter(r=>!D(r)&&!n.has(r)),8)}function ue(t){let e=[],n;for(;(n=re.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 g(e,6)}function de(t){let e=[],n;for(;(n=se.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 g(e,6)}function me(t){let e=[],n;for(;(n=ae.exec(t))!==null;)e.push(n[0].replace(/\s+/g," ").trim());return g(e,6)}function he(t){return oe.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 x(t){let e=t?.trim()??"";if(!e)return"";let n=ce(e),i=le(e,n),r=ue(e),s=de(e),a=me(e),o=he(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
2
  `)}var pe=/(?:[A-Za-z]:\\[^\s"'`<>|]+|\/[^\s"'`<>|]+)/g,fe=[/\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],ge=[{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 q(t){return t.trim().replace(/^[`'"]+|[`'"]+$/g,"").replace(/[.,;:)\]]+$/g,"").trim()}function $(t){return!!(!t||/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("//"))}function y(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 be(t){let e=[];for(let n of fe){let i;for(;(i=n.exec(t))!==null;){let r=q(i[1]??"");$(r)||e.push(r)}}return y(e,10)}function ve(t,e){let n=new Set(e),i=t.match(pe)??[];return y(i.map(q).filter(r=>!$(r)&&!n.has(r)),10)}function ye(t){return ge.filter(e=>e.trigger.test(t)).slice(0,6)}function U(t){return/\b(?:terminal-bench|benchmark|hidden tests?|verifier|\/tests|test\.sh|run-tests\.sh|\/app)\b/i.test(t)}function we(t,e,n){return e.length>0||n.length>0||U(t)?!0:/\b(?:implement|fix|build|create|write|debug|optimi[sz]e|train|configure|recover|extract|convert|process|validate)\b/i.test(t)}function ke(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 E(t){let e=t?.trim()??"",n=be(e),i=ve(e,n),r=ye(e),s=U(e),a=we(e,n,r),o=ke(r,s),c=y([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=y([...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 T(t){let e=E(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
3
  `)}function Re(t){let e=E(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
4
  `)}var w={official:6,project:5,user:4,self:3,smoke:2,syntax:1},V=/\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,xe=/(?:^|\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,_=/\b(?:SELF_CHECK|CONTRACT|READBACK|ROUNDTRIP|SCHEMA|VALIDATION|VERIFIER)[_-]?(?:PASS|FAIL|FAILED|ERROR)\b/i,Ee=/(?:^|\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],Te=[/\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 Ae(t,e=500){return t.replace(/\r\n/g,`
5
- `).replace(/[ \t]+$/gm,"").trim().slice(0,e)}function _e(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 g(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Se(t,e,n){let i=g(e)??"";return/^Bash$/i.test(t)&&V.test(i)||/^TaskOutput$/i.test(t)&&(V.test(n)||_.test(n))?!0:_.test(n)}function Ce(t,e,n){let i=g(e)??"",r=`${i}
5
+ `).replace(/[ \t]+$/gm,"").trim().slice(0,e)}function _e(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 b(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Se(t,e,n){let i=b(e)??"";return/^Bash$/i.test(t)&&V.test(i)||/^TaskOutput$/i.test(t)&&(V.test(n)||_.test(n))?!0:_.test(n)}function Ce(t,e,n){let i=b(e)??"",r=`${i}
6
6
  ${n}`;return xe.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":_.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 Ie(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 Pe(t,e){let n=t.replace(/\r\n/g,`
7
7
  `).split(`
8
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
9
  `);i.push(Ae(o,260))}}let r=new Map;for(let s of i.slice(0,12)){let a=_e(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 Ne(t,e){let n=Ie(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`}:Te.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 Le(t,e,n){if(!n.success)return!1;if(/^(?:Write|Edit|NotebookEdit|MemoryWrite)$/i.test(t))return!0;let i=g(e);return/^Bash$/i.test(t)&&!!i&&Ee.test(i)}function A(t){return w[t.authority]>=w.project}function k(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 b=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:k(e),benchmarkMode:e.benchmarkMode===!0,requiredOutputPaths:i,requiredValidation:r}}recordToolResult(e){if(this.toolCalls+=1,Le(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(!Se(e.toolName,e.input,n))return[];let i=Ce(e.toolName,e.input,n),r=Ne(e.result,n),s={id:`validation-${this.signals.length+1}`,iteration:e.iteration,toolName:e.toolName,...g(e.input)?{command:g(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"?Pe(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(`
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 Ne(t,e){let n=Ie(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`}:Te.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 Le(t,e,n){if(!n.success)return!1;if(/^(?:Write|Edit|NotebookEdit|MemoryWrite)$/i.test(t))return!0;let i=b(e);return/^Bash$/i.test(t)&&!!i&&Ee.test(i)}function A(t){return w[t.authority]>=w.project}function k(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 v=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:k(e),benchmarkMode:e.benchmarkMode===!0,requiredOutputPaths:i,requiredValidation:r}}recordToolResult(e){if(this.toolCalls+=1,Le(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(!Se(e.toolName,e.input,n))return[];let i=Ce(e.toolName,e.input,n),r=Ne(e.result,n),s={id:`validation-${this.signals.length+1}`,iteration:e.iteration,toolName:e.toolName,...b(e.input)?{command:b(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"?Pe(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
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
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"&&!A(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=>A(e))??null}getLatestUnresolvedFailure(){let e=[...this.signals].reverse().find(i=>A(i)&&i.outcome==="fail"&&!i.stale);return e?this.signals.some(i=>i.iteration>e.iteration&&!i.stale&&i.outcome==="pass"&&w[i.authority]>=w[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 Me=new Set(["bash","elfanalyze","gitbranch","gitdiff","gitlog","gitstatus","glob","grep","ls","read","readimage"]),Fe=new Set(["applypatch","edit","notebookedit","write"]),je=/\?|\b(?:can|could|did|do|does|has|have|is|should|was|were|will|would)\b|\b(?:correct|right)\s*[.!?]*$/i,Oe=/\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,De=["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"],qe=/\b(?:browse|investigate|research|search)\b|\b(?:check|find|look)\s+(?:it\s+)?(?:up|online|on\s+the\s+web)\b/i,$e=["browse","investigate","research","search"],Ue=/\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,We=/\b(?:yes|installed|you\s+(?:have|do\s+have)|found|available|on\s+(?:your|the)\s+path|callable|working|responds?|verified|confirmed)\b/i,ze=/\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,Be=/\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,He=/\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,Qe=/\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,Ke=/(?:^|[\\/])\.xeno[\\/](?:sessions|audit)[\\/]/i,Ye=/\b(?:official|docs?|documentation|source|reference|install(?:ation)?|supported|features?|commands?)\b/i,Ze=/\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,Je=/\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,et=/\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,tt=/https?:\/\/[^\s)>\]]+/i;function v(t){return t.trim().replace(/\s+/g," ")}function nt(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 J(t,e){return(t.toLowerCase().match(/[a-z]+/g)??[]).some(i=>i.length>=5&&e.some(r=>nt(i,r)))}function it(t){return Oe.test(t)||J(t,De)}function N(t){return qe.test(t)||J(t,$e)}function L(t){return t.replace(/[\s_-]+/g,"").toLowerCase()}function S(t){return Array.isArray(t)?t.map(S):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,S(n)])):typeof t=="string"?v(t.replace(/\\/g,"/")):t}function W(t,e){return`${L(t)}:${JSON.stringify(S(e))}`}function z(t){return Me.has(L(t))}function rt(t,e){let n=L(t);return Fe.has(n)?!0:n==="bash"&&Ue.test(C(e)??"")}function R(t){let e=v(t);return!e||e.length>320?!1:je.test(e)&&!it(e)}function st(t,e){let n=Math.max(1,Math.floor(e));return R(t)?Math.min(n,4):n}function at(t){if(typeof t!="string")return null;let e=v(t).toLowerCase();return e.length>0?e:null}function B(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=v(t).toLowerCase().replace(/#.*$/,"").replace(/\/+$/,"");return e.length>0?e:null}}function C(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():null}function I(t){return typeof t=="string"?[t]:Array.isArray(t)?t.flatMap(I):t&&typeof t=="object"?Object.values(t).flatMap(I):[]}function H(t){return t.replace(/\\/g,"/").toLowerCase()}function X(t){return v([t.output,t.error].filter(Boolean).join(" ")).slice(0,240)}function Q(t){return t.success===!1||Be.test([t.output,t.error].filter(Boolean).join(`
15
- `))}function K(t){return/^Bash$/i.test(t)}function Y(t){return/^WebSearch$/i.test(t)}function Z(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=N(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=R(e),this.maxLocalInspectionCalls=Math.max(1,n.maxLocalInspectionCalls??(this.simpleInformationalPrompt?4: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(z(e.toolName)){let i=`${this.mutationEpoch}:${W(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(K(e.toolName)&&this.isWebResearchQuestion()){let i=C(e.input);if(i&&et.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(Y(e.toolName)){let i=at(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(Z(e.toolName)){let i=B(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(ot(e.toolName)&&this.verificationRecords.push({iteration:e.iteration,toolName:e.toolName,inputValues:I(e.input),success:e.result.success===!0&&!Q(e.result)}),z(e.toolName)){let s=`${this.mutationEpoch}:${W(e.toolName,e.input)}`,a=this.localInspectionRecords.get(s);a&&(a.successful=a.successful||e.result.success===!0)}if(Y(e.toolName))return;if(Z(e.toolName)){let s=B(e.input.url);s&&this.webFetchEvidence.push({iteration:e.iteration,url:s,success:e.result.success===!0,summary:X(e.result)});return}if(!K(e.toolName)||!this.isLocalSetupQuestion())return;let i=C(e.input);if(!i||!Ge.test(i))return;let r=Q(e.result);this.localEvidence.push({iteration:e.iteration,command:i,success:e.result.success===!0&&!r,summary:X(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||!We.test(s)||ze.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=tt.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 Ve.test(this.taskPrompt)}totalWebResearchCalls(){return this.webSearches+this.webFetches}isOfficialResearchQuestion(){return Ye.test(this.taskPrompt)}isWebResearchQuestion(){return this.explicitResearchPrompt||Ze.test(this.taskPrompt)}successfulWebFetches(){return this.webFetchEvidence.filter(e=>e.success)}failedSpeculativeWebFetches(){return this.webFetchEvidence.filter(e=>!e.success&&Je.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(!He.test(n)||Xe.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(!Qe.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=>H(c).includes(H(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(!Ke.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 ot(t){return/^(?:Bash|Read|ReadImage|ElfAnalyze|NotebookRead)$/i.test(t)}var P=class{active=null;activePrompt=null;promptSection={name:"interactive-chat-answer-budget",order:20,provide:()=>this.activePrompt?N(this.activePrompt)?[`
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=>A(e))??null}getLatestUnresolvedFailure(){let e=[...this.signals].reverse().find(i=>A(i)&&i.outcome==="fail"&&!i.stale);return e?this.signals.some(i=>i.iteration>e.iteration&&!i.stale&&i.outcome==="pass"&&w[i.authority]>=w[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 Me=new Set(["bash","elfanalyze","gitbranch","gitdiff","gitlog","gitstatus","glob","grep","ls","read","readimage"]),Fe=new Set(["applypatch","edit","notebookedit","write"]),je=/\?|\b(?:can|could|did|do|does|has|have|is|should|was|were|will|would)\b|\b(?:correct|right)\s*[.!?]*$/i,Oe=/\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,De=/^(?: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,qe=["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"],$e=/\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"],Ve=/\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,Ge=/\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,We=/\b(?:Get-Command|where(?:\.exe)?|command\s+-v|which|type\s+-a?|--version|-v\b|--help|-h\b)\b/i,ze=/\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,Xe=/\b(?:created|generated|produced|saved|wrote|written|exported|converted|built|rendered|flattened|creat|generat|produs|salvat|scris|exportat|convertit|aplatizat)\b/i,Qe=/\b(?:not|didn['’]?t|couldn['’]?t|cannot|failed\s+to|incomplete|missing|nu|n-am|nereu[sÈ™]it)\b/i,Ke=/\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,Ye=/(?:^|[\\/])\.xeno[\\/](?:sessions|audit)[\\/]/i,Ze=/\b(?:official|docs?|documentation|source|reference|install(?:ation)?|supported|features?|commands?)\b/i,Je=/\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,et=/\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,tt=/\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,nt=/https?:\/\/[^\s)>\]]+/i;function p(t){return t.trim().replace(/\s+/g," ")}function it(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 J(t,e){return(t.toLowerCase().match(/[a-z]+/g)??[]).some(i=>i.length>=5&&e.some(r=>it(i,r)))}function rt(t){return De.test(p(t))||Oe.test(t)||J(t,qe)}function N(t){return $e.test(t)||J(t,Ue)}function L(t){return t.replace(/[\s_-]+/g,"").toLowerCase()}function S(t){return Array.isArray(t)?t.map(S):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,S(n)])):typeof t=="string"?p(t.replace(/\\/g,"/")):t}function W(t,e){return`${L(t)}:${JSON.stringify(S(e))}`}function z(t){return Me.has(L(t))}function st(t,e){let n=L(t);return Fe.has(n)?!0:n==="bash"&&Ve.test(C(e)??"")}function R(t){let e=p(t);return!e||e.length>320?!1:je.test(e)&&!rt(e)}function at(t,e){let n=Math.max(1,Math.floor(e));return R(t)?Math.min(n,15):n}function ot(t){if(typeof t!="string")return null;let e=p(t).toLowerCase();return e.length>0?e:null}function B(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=p(t).toLowerCase().replace(/#.*$/,"").replace(/\/+$/,"");return e.length>0?e:null}}function C(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():null}function I(t){return typeof t=="string"?[t]:Array.isArray(t)?t.flatMap(I):t&&typeof t=="object"?Object.values(t).flatMap(I):[]}function H(t){return t.replace(/\\/g,"/").toLowerCase()}function X(t){return p([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(`
15
+ `))}function K(t){return/^Bash$/i.test(t)}function Y(t){return/^WebSearch$/i.test(t)}function Z(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=N(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=R(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(st(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(z(e.toolName)){let i=`${this.mutationEpoch}:${W(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(K(e.toolName)&&this.isWebResearchQuestion()){let i=C(e.input);if(i&&tt.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(Y(e.toolName)){let i=ot(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(Z(e.toolName)){let i=B(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(ct(e.toolName)&&this.verificationRecords.push({iteration:e.iteration,toolName:e.toolName,inputValues:I(e.input),success:e.result.success===!0&&!Q(e.result)}),z(e.toolName)){let s=`${this.mutationEpoch}:${W(e.toolName,e.input)}`,a=this.localInspectionRecords.get(s);a&&(a.successful=a.successful||e.result.success===!0)}if(Y(e.toolName))return;if(Z(e.toolName)){let s=B(e.input.url);s&&this.webFetchEvidence.push({iteration:e.iteration,url:s,success:e.result.success===!0,summary:X(e.result)});return}if(!K(e.toolName)||!this.isLocalSetupQuestion())return;let i=C(e.input);if(!i||!We.test(i))return;let r=Q(e.result);this.localEvidence.push({iteration:e.iteration,command:i,success:e.result.success===!0&&!r,summary:X(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||!ze.test(s)||Be.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=nt.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 Ge.test(this.taskPrompt)}totalWebResearchCalls(){return this.webSearches+this.webFetches}isOfficialResearchQuestion(){return Ze.test(this.taskPrompt)}isWebResearchQuestion(){return this.explicitResearchPrompt||Je.test(this.taskPrompt)}successfulWebFetches(){return this.webFetchEvidence.filter(e=>e.success)}failedSpeculativeWebFetches(){return this.webFetchEvidence.filter(e=>!e.success&&et.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(!Xe.test(n)||Qe.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(!Ke.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=>H(c).includes(H(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(!Ye.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 ct(t){return/^(?:Bash|Read|ReadImage|ElfAnalyze|NotebookRead)$/i.test(t)}var P=class{active=null;activePrompt=null;promptSection={name:"interactive-chat-answer-budget",order:20,provide:()=>this.activePrompt?N(this.activePrompt)?[`
22
22
 
23
23
  <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
24
  `):R(this.activePrompt)?[`
25
25
 
26
26
  <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 ee=String.raw`(?:^|[\n;&|]\s*|\(\s*)`,ct=new RegExp(String.raw`${ee}(?:timeout\s+\S+\s+)?(?:sudo\s+)?eval\s+(?:"|'|)?\$\(\s*(?:curl|wget)\b`,"i"),lt=new RegExp(`${ee}(?: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"),ut=/\b(?:make|ninja|cmake\s+--build)\b[\s\S]*?(?:^|\s)-j\s*(?:\$\(?nproc\)?|[5-9]\b|\d{2,}\b)/i,dt=900,mt=/\b(?:cifar(?:-?10)?|mnist|imagenet|yelp|fasttext|wikitext|c4|common\s*crawl|glue|squad|train(?:ing)?[_ -]?data|test[_ -]?data|lmdb)\b/i,ht=/\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,pt=/\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,ft=/\btimeout\s+(\d+)([smhd]?)/i;function gt(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():null}function bt(t){return/^Bash$/i.test(t)}function vt(t){let e=t.match(ft);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 yt(t){if(!lt.test(t))return null;if(ut.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=vt(t);return e!==null&&e<dt?["[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 wt(t){return!mt.test(t)||!ht.test(t)||!pt.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 kt(t){return ct.test(t)}function Rt(){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 M(t={}){let e=t.benchmarkMode===!0;return async(n,i)=>{if(!bt(n.toolName))return i();let r=gt(n.input);if(!r)return i();if(kt(r))return Rt();if(e){let s=yt(r);s&&n.addGuidance(s);let a=wt(r);a&&n.addGuidance(a)}return i()}}var te=`
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 ee=String.raw`(?:^|[\n;&|]\s*|\(\s*)`,lt=new RegExp(String.raw`${ee}(?:timeout\s+\S+\s+)?(?:sudo\s+)?eval\s+(?:"|'|)?\$\(\s*(?:curl|wget)\b`,"i"),ut=new RegExp(`${ee}(?: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"),dt=/\b(?:make|ninja|cmake\s+--build)\b[\s\S]*?(?:^|\s)-j\s*(?:\$\(?nproc\)?|[5-9]\b|\d{2,}\b)/i,mt=900,ht=/\b(?:cifar(?:-?10)?|mnist|imagenet|yelp|fasttext|wikitext|c4|common\s*crawl|glue|squad|train(?:ing)?[_ -]?data|test[_ -]?data|lmdb)\b/i,pt=/\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,ft=/\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,gt=/\btimeout\s+(\d+)([smhd]?)/i;function bt(t){let e=t.command;return typeof e=="string"&&e.trim().length>0?e.trim():null}function vt(t){return/^Bash$/i.test(t)}function yt(t){let e=t.match(gt);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 wt(t){if(!ut.test(t))return null;if(dt.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=yt(t);return e!==null&&e<mt?["[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 kt(t){return!ht.test(t)||!pt.test(t)||!ft.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 Rt(t){return lt.test(t)}function xt(){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 M(t={}){let e=t.benchmarkMode===!0;return async(n,i)=>{if(!vt(n.toolName))return i();let r=bt(n.input);if(!r)return i();if(Rt(r))return xt();if(e){let s=wt(r);s&&n.addGuidance(s);let a=kt(r);a&&n.addGuidance(a)}return i()}}var te=`
32
32
 
33
- `;function Lt(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||k({taskPrompt:e,benchmarkMode:n,requiredOutputPaths:i}))?new b({taskPrompt:e,benchmarkMode:n,requiredOutputPaths:i}):null,o=a?.getSummary()??null,c=[];(r||a)&&c.push(async(l,u)=>{if(r){let F=r.maybeBlockToolCall({toolName:l.toolName,input:l.input,iteration:l.iteration});if(F)return F}let p=await u();return r&&r.recordToolResult({toolName:l.toolName,input:l.input,result:p,iteration:l.iteration}),a&&(a.recordToolResult({toolName:l.toolName,input:l.input,result:p,iteration:l.iteration}),o=a.getSummary(),t.onExecutionGovernanceUpdate?.(o)),p}),c.push(M({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 p=u.action==="incomplete";return{allow:!1,guidance:u.message,stop:p}}});let m=[];return t.promptGuidance!==!1&&(m.push({name:"contract-ledger",order:100,provide(l){let u=x(l.taskPrompt??e);return u?`${te}${u.replace(/^\n+/,"")}`:null}}),m.push({name:"project-execution",order:110,provide(l){let u=T(l.taskPrompt??e);return u?`${te}${u.replace(/^\n+/,"")}`:null}})),{toolMiddleware:c,promptSections:m,completionGuards:d,getExecutionGovernanceSummary:()=>o}}export{b as ExecutionGovernance,P as InteractiveChatTurnGovernance,h as InteractiveTurnGovernance,x as buildContractLedgerGuidance,Re as buildProjectBudgetFinalizationGuidance,T as buildProjectExecutionGuidance,E as buildProjectExecutionProfile,M as createBenchBashMiddleware,Lt as createGovernanceExtensions,N as isExplicitResearchPrompt,R as isSimpleInformationalPrompt,st as resolveInteractiveTurnMaxIterations,k as shouldEnableExecutionGovernance};
33
+ `;function Mt(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||k({taskPrompt:e,benchmarkMode:n,requiredOutputPaths:i}))?new v({taskPrompt:e,benchmarkMode:n,requiredOutputPaths:i}):null,o=a?.getSummary()??null,c=[];(r||a)&&c.push(async(l,u)=>{if(r){let F=r.maybeBlockToolCall({toolName:l.toolName,input:l.input,iteration:l.iteration});if(F)return F}let f=await u();return r&&r.recordToolResult({toolName:l.toolName,input:l.input,result:f,iteration:l.iteration}),a&&(a.recordToolResult({toolName:l.toolName,input:l.input,result:f,iteration:l.iteration}),o=a.getSummary(),t.onExecutionGovernanceUpdate?.(o)),f}),c.push(M({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 f=u.action==="incomplete";return{allow:!1,guidance:u.message,stop:f}}});let m=[];return t.promptGuidance!==!1&&(m.push({name:"contract-ledger",order:100,provide(l){let u=x(l.taskPrompt??e);return u?`${te}${u.replace(/^\n+/,"")}`:null}}),m.push({name:"project-execution",order:110,provide(l){let u=T(l.taskPrompt??e);return u?`${te}${u.replace(/^\n+/,"")}`:null}})),{toolMiddleware:c,promptSections:m,completionGuards:d,getExecutionGovernanceSummary:()=>o}}export{v as ExecutionGovernance,P as InteractiveChatTurnGovernance,h as InteractiveTurnGovernance,x as buildContractLedgerGuidance,Re as buildProjectBudgetFinalizationGuidance,T as buildProjectExecutionGuidance,E as buildProjectExecutionProfile,M as createBenchBashMiddleware,Mt as createGovernanceExtensions,N as isExplicitResearchPrompt,R as isSimpleInformationalPrompt,at as resolveInteractiveTurnMaxIterations,k as shouldEnableExecutionGovernance};
@@ -1 +1 @@
1
- {"inputs":{"src/governance/contract-ledger.ts":{"bytes":12518,"imports":[],"format":"esm"},"src/governance/project-execution.ts":{"bytes":22404,"imports":[],"format":"esm"},"src/governance/execution-governance.ts":{"bytes":19143,"imports":[],"format":"esm"},"src/governance/interactive-turn-governance.ts":{"bytes":35260,"imports":[],"format":"esm"},"src/governance/bench-bash-middleware.ts":{"bytes":8788,"imports":[],"format":"esm"},"src/governance/index.ts":{"bytes":10695,"imports":[{"path":"src/governance/contract-ledger.ts","kind":"import-statement","original":"./contract-ledger.js"},{"path":"src/governance/project-execution.ts","kind":"import-statement","original":"./project-execution.js"},{"path":"src/governance/execution-governance.ts","kind":"import-statement","original":"./execution-governance.js"},{"path":"src/governance/interactive-turn-governance.ts","kind":"import-statement","original":"./interactive-turn-governance.js"},{"path":"src/governance/bench-bash-middleware.ts","kind":"import-statement","original":"./bench-bash-middleware.js"},{"path":"src/governance/contract-ledger.ts","kind":"import-statement","original":"./contract-ledger.js"},{"path":"src/governance/project-execution.ts","kind":"import-statement","original":"./project-execution.js"},{"path":"src/governance/execution-governance.ts","kind":"import-statement","original":"./execution-governance.js"},{"path":"src/governance/interactive-turn-governance.ts","kind":"import-statement","original":"./interactive-turn-governance.js"},{"path":"src/governance/bench-bash-middleware.ts","kind":"import-statement","original":"./bench-bash-middleware.js"}],"format":"esm"}},"outputs":{"dist/governance/index.cjs":{"imports":[],"exports":[],"entryPoint":"src/governance/index.ts","inputs":{"src/governance/index.ts":{"bytesInOutput":2317},"src/governance/contract-ledger.ts":{"bytesInOutput":8666},"src/governance/project-execution.ts":{"bytesInOutput":16608},"src/governance/execution-governance.ts":{"bytesInOutput":9563},"src/governance/interactive-turn-governance.ts":{"bytesInOutput":19593},"src/governance/bench-bash-middleware.ts":{"bytesInOutput":3388}},"bytes":60969}}}
1
+ {"inputs":{"src/governance/contract-ledger.ts":{"bytes":12254,"imports":[],"format":"esm"},"src/governance/project-execution.ts":{"bytes":21971,"imports":[],"format":"esm"},"src/governance/execution-governance.ts":{"bytes":18654,"imports":[],"format":"esm"},"src/governance/interactive-turn-governance.ts":{"bytes":35032,"imports":[],"format":"esm"},"src/governance/bench-bash-middleware.ts":{"bytes":8601,"imports":[],"format":"esm"},"src/governance/index.ts":{"bytes":10412,"imports":[{"path":"src/governance/contract-ledger.ts","kind":"import-statement","original":"./contract-ledger.js"},{"path":"src/governance/project-execution.ts","kind":"import-statement","original":"./project-execution.js"},{"path":"src/governance/execution-governance.ts","kind":"import-statement","original":"./execution-governance.js"},{"path":"src/governance/interactive-turn-governance.ts","kind":"import-statement","original":"./interactive-turn-governance.js"},{"path":"src/governance/bench-bash-middleware.ts","kind":"import-statement","original":"./bench-bash-middleware.js"},{"path":"src/governance/contract-ledger.ts","kind":"import-statement","original":"./contract-ledger.js"},{"path":"src/governance/project-execution.ts","kind":"import-statement","original":"./project-execution.js"},{"path":"src/governance/execution-governance.ts","kind":"import-statement","original":"./execution-governance.js"},{"path":"src/governance/interactive-turn-governance.ts","kind":"import-statement","original":"./interactive-turn-governance.js"},{"path":"src/governance/bench-bash-middleware.ts","kind":"import-statement","original":"./bench-bash-middleware.js"}],"format":"esm"}},"outputs":{"dist/governance/index.cjs":{"imports":[],"exports":[],"entryPoint":"src/governance/index.ts","inputs":{"src/governance/index.ts":{"bytesInOutput":2317},"src/governance/contract-ledger.ts":{"bytesInOutput":8666},"src/governance/project-execution.ts":{"bytesInOutput":16608},"src/governance/execution-governance.ts":{"bytesInOutput":9563},"src/governance/interactive-turn-governance.ts":{"bytesInOutput":19826},"src/governance/bench-bash-middleware.ts":{"bytesInOutput":3388}},"bytes":61202}}}
@@ -1 +1 @@
1
- {"inputs":{"src/governance/contract-ledger.ts":{"bytes":12518,"imports":[],"format":"esm"},"src/governance/project-execution.ts":{"bytes":22404,"imports":[],"format":"esm"},"src/governance/execution-governance.ts":{"bytes":19143,"imports":[],"format":"esm"},"src/governance/interactive-turn-governance.ts":{"bytes":35260,"imports":[],"format":"esm"},"src/governance/bench-bash-middleware.ts":{"bytes":8788,"imports":[],"format":"esm"},"src/governance/index.ts":{"bytes":10695,"imports":[{"path":"src/governance/contract-ledger.ts","kind":"import-statement","original":"./contract-ledger.js"},{"path":"src/governance/project-execution.ts","kind":"import-statement","original":"./project-execution.js"},{"path":"src/governance/execution-governance.ts","kind":"import-statement","original":"./execution-governance.js"},{"path":"src/governance/interactive-turn-governance.ts","kind":"import-statement","original":"./interactive-turn-governance.js"},{"path":"src/governance/bench-bash-middleware.ts","kind":"import-statement","original":"./bench-bash-middleware.js"},{"path":"src/governance/contract-ledger.ts","kind":"import-statement","original":"./contract-ledger.js"},{"path":"src/governance/project-execution.ts","kind":"import-statement","original":"./project-execution.js"},{"path":"src/governance/execution-governance.ts","kind":"import-statement","original":"./execution-governance.js"},{"path":"src/governance/interactive-turn-governance.ts","kind":"import-statement","original":"./interactive-turn-governance.js"},{"path":"src/governance/bench-bash-middleware.ts","kind":"import-statement","original":"./bench-bash-middleware.js"}],"format":"esm"}},"outputs":{"dist/governance/index.js":{"imports":[],"exports":["ExecutionGovernance","InteractiveChatTurnGovernance","InteractiveTurnGovernance","buildContractLedgerGuidance","buildProjectBudgetFinalizationGuidance","buildProjectExecutionGuidance","buildProjectExecutionProfile","createBenchBashMiddleware","createGovernanceExtensions","isExplicitResearchPrompt","isSimpleInformationalPrompt","resolveInteractiveTurnMaxIterations","shouldEnableExecutionGovernance"],"entryPoint":"src/governance/index.ts","inputs":{"src/governance/contract-ledger.ts":{"bytesInOutput":8666},"src/governance/project-execution.ts":{"bytesInOutput":16609},"src/governance/execution-governance.ts":{"bytesInOutput":9563},"src/governance/interactive-turn-governance.ts":{"bytesInOutput":19587},"src/governance/bench-bash-middleware.ts":{"bytesInOutput":3388},"src/governance/index.ts":{"bytesInOutput":1820}},"bytes":60086}}}
1
+ {"inputs":{"src/governance/contract-ledger.ts":{"bytes":12254,"imports":[],"format":"esm"},"src/governance/project-execution.ts":{"bytes":21971,"imports":[],"format":"esm"},"src/governance/execution-governance.ts":{"bytes":18654,"imports":[],"format":"esm"},"src/governance/interactive-turn-governance.ts":{"bytes":35032,"imports":[],"format":"esm"},"src/governance/bench-bash-middleware.ts":{"bytes":8601,"imports":[],"format":"esm"},"src/governance/index.ts":{"bytes":10412,"imports":[{"path":"src/governance/contract-ledger.ts","kind":"import-statement","original":"./contract-ledger.js"},{"path":"src/governance/project-execution.ts","kind":"import-statement","original":"./project-execution.js"},{"path":"src/governance/execution-governance.ts","kind":"import-statement","original":"./execution-governance.js"},{"path":"src/governance/interactive-turn-governance.ts","kind":"import-statement","original":"./interactive-turn-governance.js"},{"path":"src/governance/bench-bash-middleware.ts","kind":"import-statement","original":"./bench-bash-middleware.js"},{"path":"src/governance/contract-ledger.ts","kind":"import-statement","original":"./contract-ledger.js"},{"path":"src/governance/project-execution.ts","kind":"import-statement","original":"./project-execution.js"},{"path":"src/governance/execution-governance.ts","kind":"import-statement","original":"./execution-governance.js"},{"path":"src/governance/interactive-turn-governance.ts","kind":"import-statement","original":"./interactive-turn-governance.js"},{"path":"src/governance/bench-bash-middleware.ts","kind":"import-statement","original":"./bench-bash-middleware.js"}],"format":"esm"}},"outputs":{"dist/governance/index.js":{"imports":[],"exports":["ExecutionGovernance","InteractiveChatTurnGovernance","InteractiveTurnGovernance","buildContractLedgerGuidance","buildProjectBudgetFinalizationGuidance","buildProjectExecutionGuidance","buildProjectExecutionProfile","createBenchBashMiddleware","createGovernanceExtensions","isExplicitResearchPrompt","isSimpleInformationalPrompt","resolveInteractiveTurnMaxIterations","shouldEnableExecutionGovernance"],"entryPoint":"src/governance/index.ts","inputs":{"src/governance/contract-ledger.ts":{"bytesInOutput":8666},"src/governance/project-execution.ts":{"bytesInOutput":16609},"src/governance/execution-governance.ts":{"bytesInOutput":9563},"src/governance/interactive-turn-governance.ts":{"bytesInOutput":19820},"src/governance/bench-bash-middleware.ts":{"bytesInOutput":3388},"src/governance/index.ts":{"bytesInOutput":1820}},"bytes":60319}}}
@@ -1 +1 @@
1
- {"inputs":{"src/hooks/command-hook.ts":{"bytes":10057,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/security/permission-profile.ts":{"bytes":8013,"imports":[],"format":"esm"},"src/hooks/http-hook.ts":{"bytes":6327,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/security/permission-profile.ts","kind":"import-statement","original":"../security/permission-profile.js"}],"format":"esm"},"src/hooks/model-hook.ts":{"bytes":3834,"imports":[{"path":"node:perf_hooks","kind":"import-statement","external":true},{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"}],"format":"esm"},"src/hooks/runner.ts":{"bytes":4461,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/hooks/http-hook.ts","kind":"import-statement","original":"./http-hook.js"},{"path":"src/hooks/model-hook.ts","kind":"import-statement","original":"./model-hook.js"}],"format":"esm"},"src/hooks/index.ts":{"bytes":860,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/hooks/http-hook.ts","kind":"import-statement","original":"./http-hook.js"},{"path":"src/hooks/model-hook.ts","kind":"import-statement","original":"./model-hook.js"},{"path":"src/hooks/runner.ts","kind":"import-statement","original":"./runner.js"}],"format":"esm"}},"outputs":{"dist/hooks/index.cjs":{"imports":[{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:perf_hooks","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/hooks/index.ts","inputs":{"src/hooks/index.ts":{"bytesInOutput":361},"src/hooks/command-hook.ts":{"bytesInOutput":4530},"src/security/permission-profile.ts":{"bytesInOutput":902},"src/hooks/http-hook.ts":{"bytesInOutput":2575},"src/hooks/model-hook.ts":{"bytesInOutput":1468},"src/hooks/runner.ts":{"bytesInOutput":1584}},"bytes":12102}}}
1
+ {"inputs":{"src/hooks/command-hook.ts":{"bytes":9737,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/security/permission-profile.ts":{"bytes":7737,"imports":[],"format":"esm"},"src/hooks/http-hook.ts":{"bytes":6142,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/security/permission-profile.ts","kind":"import-statement","original":"../security/permission-profile.js"}],"format":"esm"},"src/hooks/model-hook.ts":{"bytes":3723,"imports":[{"path":"node:perf_hooks","kind":"import-statement","external":true},{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"}],"format":"esm"},"src/hooks/runner.ts":{"bytes":4318,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/hooks/http-hook.ts","kind":"import-statement","original":"./http-hook.js"},{"path":"src/hooks/model-hook.ts","kind":"import-statement","original":"./model-hook.js"}],"format":"esm"},"src/hooks/index.ts":{"bytes":813,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/hooks/http-hook.ts","kind":"import-statement","original":"./http-hook.js"},{"path":"src/hooks/model-hook.ts","kind":"import-statement","original":"./model-hook.js"},{"path":"src/hooks/runner.ts","kind":"import-statement","original":"./runner.js"}],"format":"esm"}},"outputs":{"dist/hooks/index.cjs":{"imports":[{"path":"node:child_process","kind":"require-call","external":true},{"path":"node:perf_hooks","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/hooks/index.ts","inputs":{"src/hooks/index.ts":{"bytesInOutput":361},"src/hooks/command-hook.ts":{"bytesInOutput":4530},"src/security/permission-profile.ts":{"bytesInOutput":902},"src/hooks/http-hook.ts":{"bytesInOutput":2575},"src/hooks/model-hook.ts":{"bytesInOutput":1468},"src/hooks/runner.ts":{"bytesInOutput":1584}},"bytes":12102}}}
@@ -1 +1 @@
1
- {"inputs":{"src/hooks/command-hook.ts":{"bytes":10057,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/security/permission-profile.ts":{"bytes":8013,"imports":[],"format":"esm"},"src/hooks/http-hook.ts":{"bytes":6327,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/security/permission-profile.ts","kind":"import-statement","original":"../security/permission-profile.js"}],"format":"esm"},"src/hooks/model-hook.ts":{"bytes":3834,"imports":[{"path":"node:perf_hooks","kind":"import-statement","external":true},{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"}],"format":"esm"},"src/hooks/runner.ts":{"bytes":4461,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/hooks/http-hook.ts","kind":"import-statement","original":"./http-hook.js"},{"path":"src/hooks/model-hook.ts","kind":"import-statement","original":"./model-hook.js"}],"format":"esm"},"src/hooks/index.ts":{"bytes":860,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/hooks/http-hook.ts","kind":"import-statement","original":"./http-hook.js"},{"path":"src/hooks/model-hook.ts","kind":"import-statement","original":"./model-hook.js"},{"path":"src/hooks/runner.ts","kind":"import-statement","original":"./runner.js"}],"format":"esm"}},"outputs":{"dist/hooks/index.js":{"imports":[{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:perf_hooks","kind":"import-statement","external":true}],"exports":["AgentHookRunner","CommandHookRunner","HookRunner","HookRuntime","HttpHookRunner","PromptHookRunner","buildHookEnvironment","hookResultStatus","normalizeHookDecision","runAgentHook","runCommandHook","runHookDefinition","runHooks","runHttpHook","runPromptHook"],"entryPoint":"src/hooks/index.ts","inputs":{"src/hooks/command-hook.ts":{"bytesInOutput":4513},"src/hooks/index.ts":{"bytesInOutput":0},"src/security/permission-profile.ts":{"bytesInOutput":902},"src/hooks/http-hook.ts":{"bytesInOutput":2575},"src/hooks/model-hook.ts":{"bytesInOutput":1433},"src/hooks/runner.ts":{"bytesInOutput":1584}},"bytes":11321}}}
1
+ {"inputs":{"src/hooks/command-hook.ts":{"bytes":9737,"imports":[{"path":"node:child_process","kind":"import-statement","external":true}],"format":"esm"},"src/security/permission-profile.ts":{"bytes":7737,"imports":[],"format":"esm"},"src/hooks/http-hook.ts":{"bytes":6142,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/security/permission-profile.ts","kind":"import-statement","original":"../security/permission-profile.js"}],"format":"esm"},"src/hooks/model-hook.ts":{"bytes":3723,"imports":[{"path":"node:perf_hooks","kind":"import-statement","external":true},{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"}],"format":"esm"},"src/hooks/runner.ts":{"bytes":4318,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/hooks/http-hook.ts","kind":"import-statement","original":"./http-hook.js"},{"path":"src/hooks/model-hook.ts","kind":"import-statement","original":"./model-hook.js"}],"format":"esm"},"src/hooks/index.ts":{"bytes":813,"imports":[{"path":"src/hooks/command-hook.ts","kind":"import-statement","original":"./command-hook.js"},{"path":"src/hooks/http-hook.ts","kind":"import-statement","original":"./http-hook.js"},{"path":"src/hooks/model-hook.ts","kind":"import-statement","original":"./model-hook.js"},{"path":"src/hooks/runner.ts","kind":"import-statement","original":"./runner.js"}],"format":"esm"}},"outputs":{"dist/hooks/index.js":{"imports":[{"path":"node:child_process","kind":"import-statement","external":true},{"path":"node:perf_hooks","kind":"import-statement","external":true}],"exports":["AgentHookRunner","CommandHookRunner","HookRunner","HookRuntime","HttpHookRunner","PromptHookRunner","buildHookEnvironment","hookResultStatus","normalizeHookDecision","runAgentHook","runCommandHook","runHookDefinition","runHooks","runHttpHook","runPromptHook"],"entryPoint":"src/hooks/index.ts","inputs":{"src/hooks/command-hook.ts":{"bytesInOutput":4513},"src/hooks/index.ts":{"bytesInOutput":0},"src/security/permission-profile.ts":{"bytesInOutput":902},"src/hooks/http-hook.ts":{"bytesInOutput":2575},"src/hooks/model-hook.ts":{"bytesInOutput":1433},"src/hooks/runner.ts":{"bytesInOutput":1584}},"bytes":11321}}}
@@ -1 +1 @@
1
- "use strict";var O=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var pe=Object.prototype.hasOwnProperty;var ge=(e,t)=>{for(var r in t)O(e,r,{get:t[r],enumerable:!0})},fe=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of me(t))!pe.call(e,o)&&o!==r&&O(e,o,{get:()=>t[o],enumerable:!(n=le(t,o))||n.enumerable});return e};var he=e=>fe(O({},"__esModule",{value:!0}),e);var We={};ge(We,{XENO_HOSTED_CONTROL_SCHEMA_VERSION:()=>q,XENO_HOSTED_ENVIRONMENT_SCHEMA_VERSION:()=>k,XENO_HOSTED_EVENT_SCHEMA_VERSION:()=>P,XENO_HOSTED_EXECUTION_ADAPTER_CERTIFICATION_SCHEMA:()=>w,XENO_HOSTED_EXECUTION_ADAPTER_MAX_CERTIFICATE_LIFETIME_MS:()=>W,XENO_HOSTED_EXECUTION_ADAPTER_PROTOCOL_VERSION:()=>M,XENO_HOSTED_EXECUTION_PROTOCOL_VERSION:()=>re,XENO_HOSTED_EXECUTION_TOOL_NAMES:()=>ne,XENO_HOSTED_RESULT_SCHEMA_VERSION:()=>L,XENO_HOSTED_RUN_SCHEMA_VERSION:()=>Qe,XENO_HOSTED_TRIGGER_SCHEMA_VERSION:()=>Ye,assertValidXenoHostedExecutionJob:()=>Me,createXenoHostedControlCommand:()=>ce,createXenoHostedEnvironmentManifest:()=>ye,createXenoHostedEvent:()=>xe,createXenoHostedExecutionBoundaryReceipt:()=>oe,createXenoHostedRunResult:()=>de,deriveHostedIdempotencyKey:()=>Ee,hostedEnvironmentIdentity:()=>be,normalizeXenoHostedControlAcknowledgement:()=>Ue,verifyXenoHostedControlCommand:()=>ze,verifyXenoHostedEnvironmentManifest:()=>I,verifyXenoHostedEventChain:()=>we,verifyXenoHostedExecutionAdapterCertification:()=>Oe,verifyXenoHostedExecutionJob:()=>se,verifyXenoHostedRunResult:()=>Je,verifyXenoHostedWebhook:()=>Ae,xenoHostedExecutionAdapterSigningPayload:()=>Ce});module.exports=he(We);var k=1,Qe=1,P=1,Ye=1;var x=require("node:crypto");function u(e){return JSON.stringify(N(e,new Set))}function N(e,t){if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new TypeError("Artifact JSON cannot contain non-finite numbers");return e}if(t.has(e))throw new TypeError("Artifact JSON cannot contain cycles");if(t.add(e),Array.isArray(e)){let n=e.map(o=>N(o,t));return t.delete(e),n}let r={};for(let n of Object.keys(e).sort((o,s)=>o.localeCompare(s))){let o=e[n];if(o===void 0)throw new TypeError(`Artifact JSON property ${n} is undefined`);r[n]=N(o,t)}return t.delete(e),r}function y(e,t={}){for(let r of e){let n=r.codePointAt(0);if(n===127)return!0;if(!(n>31)&&!(n===9&&t.allowTab===!0)&&!((n===10||n===13)&&t.allowLineBreaks===!0))return!0}return!1}function ye(e){let t={...J(e),schemaVersion:1,kind:"xeno-hosted-environment"};return{...t,checksum:{algorithm:"sha256",value:_(t)}}}function I(e){let t=[];if(e?.schemaVersion!==1||e.kind!=="xeno-hosted-environment")return t.push("Unsupported hosted environment manifest"),{valid:!1,errors:t};let r;try{let{checksum:n,schemaVersion:o,kind:s,...i}=e;r={...J(i),schemaVersion:1,kind:"xeno-hosted-environment"}}catch(n){return t.push(n instanceof Error?n.message:String(n)),{valid:!1,errors:t}}return u(r)!==u(ve(e))&&t.push("Hosted environment manifest is not normalized"),(e.checksum?.algorithm!=="sha256"||e.checksum.value!==_(r))&&t.push("Hosted environment checksum mismatch"),{valid:t.length===0,errors:t}}function xe(e){let t=p(e.streamId,"streamId"),r=K(e.sequence,"sequence");if(e.previous){if(e.previous.streamId!==t)throw new Error("Previous event belongs to another stream");if(e.previous.sequence+1!==r)throw new Error("Hosted event sequence must be contiguous")}else if(r!==1)throw new Error("The first hosted event sequence must be 1");let n={schemaVersion:1,kind:"xeno-hosted-event",eventId:p(e.eventId??`hevt_${(0,x.randomUUID)()}`,"eventId"),streamId:t,sequence:r,timestamp:G(e.timestamp??new Date().toISOString(),"timestamp"),type:F(e.type,"type"),actorId:p(e.actorId,"actorId"),...e.idempotencyKey?{idempotencyKey:c(e.idempotencyKey,"idempotencyKey",512)}:{},payload:ke(e.payload??{},"payload"),previousHash:e.previous?.hash??null};return{...n,hash:_(n)}}function we(e,t){let r=[],n,o=t?t.afterSequence+1:1,s=t?.lastHash??null;for(let a of e){if(a.schemaVersion!==1||a.kind!=="xeno-hosted-event"){r.push(`Unsupported hosted event at sequence ${String(a.sequence)}`);continue}a.sequence!==o&&r.push(`Hosted event sequence gap at ${a.sequence}; expected ${o}`),a.previousHash!==s&&r.push(`Hosted event previous hash mismatch at ${a.sequence}`);let{hash:m,...h}=a;m!==_(h)&&r.push(`Hosted event hash mismatch at ${a.sequence}`),n&&n.streamId!==a.streamId&&r.push(`Hosted event stream changed at ${a.sequence}`),n=a,o=a.sequence+1,s=a.hash}let i=e.at(-1);return{valid:r.length===0,errors:r,cursor:i?{streamId:i.streamId,afterSequence:i.sequence,lastHash:i.hash}:t??null}}function be(e){let t=I(e);if(!t.valid)throw new Error(t.errors.join("; "));return`${e.environmentId}@${e.revision}:${e.checksum.value}`}function Ee(...e){if(e.length===0)throw new Error("At least one idempotency-key part is required");let t=e.map((r,n)=>He(r,`parts[${n}]`));return`xeno:${(0,x.createHash)("sha256").update(t.join("\0")).digest("hex")}`}function J(e){let t=e.secrets.map((o,s)=>({ref:p(o.ref,`secrets[${s}].ref`),target:o.target.kind==="environment"?{kind:"environment",name:_e(o.target.name)}:{kind:"file",path:H(o.target.path,`secrets[${s}].target.path`)},required:!!o.required,exposeToChildProcesses:!!o.exposeToChildProcesses})),r=new Set,n=new Set;for(let o of t){if(r.has(o.ref))throw new Error(`Duplicate secret ref: ${o.ref}`);r.add(o.ref);let s=`${o.target.kind}:${o.target.kind==="environment"?o.target.name:o.target.path}`;if(n.has(s))throw new Error(`Duplicate secret target: ${s}`);n.add(s)}if(e.network.default!=="deny")throw new Error("Hosted network policy must be default-deny");return{environmentId:p(e.environmentId,"environmentId"),revision:K(e.revision,"revision"),createdAt:G(e.createdAt,"createdAt"),createdBy:p(e.createdBy,"createdBy"),workspaceId:p(e.workspaceId,"workspaceId"),name:c(e.name,"name",160),repository:{provider:e.repository.provider,repository:c(e.repository.repository,"repository.repository",2048),ref:c(e.repository.ref,"repository.ref",512),...e.repository.commit?{commit:Te(e.repository.commit,"repository.commit")}:{},...e.repository.subdirectory?{subdirectory:H(e.repository.subdirectory,"repository.subdirectory")}:{},...e.repository.shallow!==void 0?{shallow:!!e.repository.shallow}:{}},image:{reference:c(e.image.reference,"image.reference",2048),digest:Se(e.image.digest),os:e.image.os,architecture:e.image.architecture},setup:e.setup.map((o,s)=>({id:p(o.id,`setup[${s}].id`),command:c(o.command,`setup[${s}].command`,32768),...o.workingDirectory?{workingDirectory:H(o.workingDirectory,`setup[${s}].workingDirectory`)}:{},timeoutMs:d(o.timeoutMs,`setup[${s}].timeoutMs`,1e3,36e5),network:o.network})),caches:e.caches.map((o,s)=>({key:c(o.key,`caches[${s}].key`,512),path:H(o.path,`caches[${s}].path`),...o.restoreKeys?.length?{restoreKeys:Re(o.restoreKeys,`caches[${s}].restoreKeys`,512)}:{},...o.readOnly!==void 0?{readOnly:!!o.readOnly}:{},...o.maxBytes!==void 0?{maxBytes:d(o.maxBytes,`caches[${s}].maxBytes`,1,Number.MAX_SAFE_INTEGER)}:{}})),network:{default:"deny",dns:e.network.dns,destinations:e.network.destinations.map((o,s)=>({host:Ie(o.host,`network.destinations[${s}].host`),...o.ports?.length?{ports:[...new Set(o.ports.map(i=>d(i,"port",1,65535)))].sort((i,a)=>i-a)}:{},...o.protocols?.length?{protocols:[...new Set(o.protocols)].sort()}:{},reason:c(o.reason,`network.destinations[${s}].reason`,500)})).sort((o,s)=>o.host.localeCompare(s.host)),...e.network.maxResponseBytes!==void 0?{maxResponseBytes:d(e.network.maxResponseBytes,"network.maxResponseBytes",1,Number.MAX_SAFE_INTEGER)}:{}},secrets:t,resources:{cpuMillis:d(e.resources.cpuMillis,"resources.cpuMillis",10,1e6),memoryBytes:d(e.resources.memoryBytes,"resources.memoryBytes",16*1024*1024,Number.MAX_SAFE_INTEGER),diskBytes:d(e.resources.diskBytes,"resources.diskBytes",16*1024*1024,Number.MAX_SAFE_INTEGER),processLimit:d(e.resources.processLimit,"resources.processLimit",1,65535),wallTimeMs:d(e.resources.wallTimeMs,"resources.wallTimeMs",1e3,10080*60*1e3)},retention:{workspaceTtlMs:d(e.retention.workspaceTtlMs,"retention.workspaceTtlMs",0,365*24*60*60*1e3),eventTtlMs:d(e.retention.eventTtlMs,"retention.eventTtlMs",6e4,365*24*60*60*1e3),artifactTtlMs:d(e.retention.artifactTtlMs,"retention.artifactTtlMs",6e4,365*24*60*60*1e3),wipeWorkspace:!!e.retention.wipeWorkspace},labels:Object.fromEntries(Object.entries(e.labels).map(([o,s])=>[F(o,"label key"),c(s,`labels.${o}`,500)]).sort(([o],[s])=>o.localeCompare(s)))}}function ve(e){let{checksum:t,...r}=e;return r}function _(e){return(0,x.createHash)("sha256").update(u(e)).digest("hex")}function ke(e,t){let r=u(e);if(Buffer.byteLength(r,"utf8")>256*1024)throw new Error(`${t} exceeds 262144 bytes`);return JSON.parse(r)}function p(e,t){let r=c(e,t,512);if(!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/.test(r))throw new Error(`${t} is invalid`);return r}function F(e,t){let r=c(e,t,160);if(!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(r))throw new Error(`${t} is invalid`);return r}function c(e,t,r){let n=e.trim();if(!n||n.length>r||y(n,{allowTab:!0,allowLineBreaks:!0}))throw new Error(`${t} is invalid`);return n}function He(e,t){let r=e.trim();if(r.length>4096||y(r,{allowTab:!0,allowLineBreaks:!0}))throw new Error(`${t} is invalid`);return r}function K(e,t){return d(e,t,1,Number.MAX_SAFE_INTEGER)}function d(e,t,r,n){if(!Number.isSafeInteger(e)||e<r||e>n)throw new Error(`${t} must be an integer between ${r} and ${n}`);return e}function G(e,t){let r=Date.parse(e);if(!Number.isFinite(r)||new Date(r).toISOString()!==e)throw new Error(`${t} must be an ISO-8601 UTC timestamp`);return e}function Ie(e,t){let r=c(e.toLowerCase(),t,253);if(r==="localhost"||/^(?:\d{1,3}\.){3}\d{1,3}$/.test(r)||r.includes(":")||!/^(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(r))throw new Error(`${t} must be a public DNS hostname or wildcard hostname`);return r}function H(e,t){let r=c(e.replaceAll("\\","/"),t,4096);if(r.startsWith("/")||/^[A-Za-z]:\//.test(r)||r.split("/").includes(".."))throw new Error(`${t} must be workspace-relative`);return r.replace(/^\.\//,"")}function _e(e){let t=c(e,"secret environment name",256);if(!/^[A-Z_][A-Z0-9_]*$/.test(t))throw new Error("Secret environment target must be an uppercase environment variable name");return t}function Se(e){let t=e.trim().toLowerCase();if(!/^sha256:[a-f0-9]{64}$/.test(t))throw new Error("image.digest must be a sha256 OCI digest");return t}function Te(e,t){return c(e,t,512)}function Re(e,t,r){return[...new Set(e.map((n,o)=>c(n,`${t}[${o}]`,r)))]}var g=require("node:crypto");function Ae(e){let t=typeof e.body=="string"?Buffer.from(e.body,"utf8"):Buffer.from(e.body),r=(0,g.createHash)("sha256").update(t).digest("hex"),n=e.signature?.trim();if(!n)return{valid:!1,source:e.source,bodySha256:r,error:"missing-signature"};if(!e.secret||e.secret.length<16)throw new Error("Webhook secret must contain at least 16 characters");let o,s=n;if(e.source==="slack"){if(!e.timestamp||!/^\d+$/.test(e.timestamp))return{valid:!1,source:e.source,bodySha256:r,error:"invalid-timestamp"};let a=Number(e.timestamp)*1e3,m=Math.abs((e.now??new Date).getTime()-a);if(!Number.isFinite(a)||m>(e.maxClockSkewMs??5*6e4))return{valid:!1,source:e.source,bodySha256:r,timestamp:e.timestamp,error:"stale-timestamp"};o=`v0=${(0,g.createHmac)("sha256",e.secret).update(`v0:${e.timestamp}:`).update(t).digest("hex")}`}else e.source==="gitlab"?o=e.secret:e.source==="teams"?o=`HMAC ${(0,g.createHmac)("sha256",Buffer.from(e.secret,"base64")).update(t).digest("base64")}`:(o=`${e.source==="github"||e.source==="jira"?"sha256=":e.source==="xeno"?"v1=":""}${(0,g.createHmac)("sha256",e.secret).update(t).digest("hex")}`,e.source==="linear"&&s.startsWith("sha256=")&&(s=s.slice(7)));let i=Xe(o,s);return{valid:i,source:e.source,bodySha256:r,...e.timestamp?{timestamp:e.timestamp}:{},...i?{}:{error:"invalid-signature"}}}function Xe(e,t){let r=Buffer.from(e,"utf8"),n=Buffer.from(t,"utf8");return r.length===n.length&&(0,g.timingSafeEqual)(r,n)}var A=require("node:crypto");var w="xeno.hosted-execution-adapter-certification.v2",M=2,W=744*60*60*1e3;function Ce(e){return Z(e),Buffer.from(D(e),"utf8")}function Oe(e,t){if(e?.schemaVersion!==w)throw new Error(`Hosted execution adapter certificate must use ${w}`);let{signature:r,...n}=e;if(Z(n),r?.algorithm!=="ed25519")throw new Error("Hosted execution adapter signature must use ed25519");let o=T(t.executableSha256,"executableSha256"),s=T(t.controlPlaneCandidateSha256,"controlPlaneCandidateSha256");if(n.adapter.executableSha256!==o)throw new Error("Hosted execution adapter executable does not match its signed certificate");if(n.controlPlaneCandidateSha256!==s)throw new Error("Hosted execution adapter certificate is bound to another control-plane candidate");let i=t.platform??process.platform,a=t.architecture??process.arch;if(n.platform.os!==i||n.platform.architecture!==a)throw new Error(`Hosted execution adapter certificate targets ${n.platform.os}-${n.platform.architecture}, not ${i}-${a}`);let m=R(n.issuedAt,"issuedAt"),h=R(n.expiresAt,"expiresAt"),z=(t.now??new Date).getTime();if(m>z+5*6e4)throw new Error("Hosted execution adapter certificate is not yet valid");if(h<=z)throw new Error("Hosted execution adapter certificate has expired");if(h<=m||h-m>W)throw new Error("Hosted execution adapter certificate lifetime must be positive and at most 31 days");let U=t.trustedKeys[n.reviewer.keyId];if(!U)throw new Error(`Hosted execution adapter reviewer key is not trusted: ${n.reviewer.keyId}`);if(!(0,A.verify)(null,Buffer.from(D(n),"utf8"),U,Pe(r.value,"signature.value")))throw new Error("Hosted execution adapter certificate signature is invalid");return{certificationId:n.certificationId,adapterName:n.adapter.name,adapterVersion:n.adapter.version,protocolVersion:n.adapter.protocolVersion,executableSha256:o,controlPlaneCandidateSha256:s,certificateSha256:(0,A.createHash)("sha256").update(D(e)).digest("hex"),expiresAt:n.expiresAt,reviewerKeyId:n.reviewer.keyId}}function Z(e){if(e.schemaVersion!==w)throw new Error(`Hosted execution adapter certificate must use ${w}`);if(S(e.certificationId,"certificationId"),S(e.adapter?.name,"adapter.name"),S(e.adapter?.version,"adapter.version"),e.adapter?.protocolVersion!==M)throw new Error(`Hosted execution adapter protocol must be ${M}`);T(e.adapter.executableSha256,"adapter.executableSha256"),T(e.controlPlaneCandidateSha256,"controlPlaneCandidateSha256"),S(e.reviewer?.keyId,"reviewer.keyId");let t=["immutableImages","filesystemIsolation","networkDefaultDeny","destinationAllowlist","secretProjection","nonRootExecution","readOnlyRoot","processTreeCleanup","resourceLimits","interactiveControl","artifactProtocol","gitResultReporting"];if(!e.capabilities||t.some(r=>e.capabilities[r]!==!0))throw new Error("Hosted execution adapter certificate does not attest every required containment capability");R(e.issuedAt,"issuedAt"),R(e.expiresAt,"expiresAt")}function D(e){return u(e)}function T(e,t){let r=e?.trim().toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error(`${t} must be a lowercase SHA-256 digest`);return r}function S(e,t){let r=e?.trim();if(!r||r.length>256||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/.test(r))throw new Error(`${t} is invalid`);return r}function R(e,t){let r=Date.parse(e);if(!Number.isFinite(r)||new Date(r).toISOString()!==e)throw new Error(`${t} must be an ISO-8601 UTC timestamp`);return r}function Pe(e,t){if(typeof e!="string"||e.length===0||e.length>4096||!/^[A-Za-z0-9+/]+={0,2}$/.test(e))throw new Error(`${t} must be bounded base64`);let r=Buffer.from(e,"base64");if(r.toString("base64")!==e)throw new Error(`${t} is not canonical base64`);return r}var te=require("node:crypto");var Q=["low","medium","high","xhigh","max"],Y=["default","plan","acceptEdits","auto","dontAsk","bypassPermissions"];var re=2,ne=["Read","Write","Edit","Glob","Grep","WebFetch"],Ne=new Set(ne);function oe(e){if(!ie(e.certificationId))throw new Error("certificationId is invalid");let t=new Set(e.authority.secretRefs);return{certificationId:e.certificationId,environmentChecksum:e.environment.checksum.value,imageDigest:e.environment.image.digest,networkPolicySha256:ee({authority:e.authority.network,policy:e.environment.network}),secretProjectionSha256:ee(e.environment.secrets.filter(r=>t.has(r.ref))),filesystem:e.authority.filesystem,network:e.authority.network==="deny"?"deny":"allowlist",immutableImage:!0,readOnlyRoot:!0,nonRoot:!0,processTreeCleanup:!0,resourceLimits:!0,inferenceGateway:"brokered"}}function se(e){let t=[];if(!Le(e))return{valid:!1,errors:["Hosted execution job must be an object"]};let r=e;if(r.protocolVersion!==re||r.kind!=="xeno-hosted-execution-job")return t.push("Unsupported hosted execution protocol"),{valid:!1,errors:t};b(r.runId,"runId",t),b(r.userId,"userId",t),b(r.workspaceId,"workspaceId",t),V(r.workspaceHostPath,"workspaceHostPath",4096,t),V(r.prompt,"prompt",512*1024,t),V(r.model,"model",512,t),r.effort!==void 0&&!Q.includes(r.effort)&&t.push("effort is invalid"),Y.includes(r.permissionMode)||t.push("permissionMode is invalid"),(typeof r.runScopedToken!="string"||!r.runScopedToken.startsWith("xrun_")||r.runScopedToken.length>16*1024)&&t.push("runScopedToken is not a bounded run-scoped token");let n;try{n=new URL(r.inferenceBaseUrl),(n.protocol!=="https:"||n.username||n.password||n.hash)&&t.push("inferenceBaseUrl must be credential-free HTTPS")}catch{t.push("inferenceBaseUrl is invalid")}let o=I(r.environment);t.push(...o.errors.map(i=>`environment: ${i}`)),r.environment?.workspaceId!==r.workspaceId&&t.push("environment workspace does not match the job"),r.environment?.image?.os!=="linux"&&t.push("hosted execution image must target Linux");let s=r.environment?.repository?.commit;(typeof s!="string"||!/^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/.test(s))&&t.push("environment repository requires a full 40- or 64-character commit object id"),De(r.authority,t),Ve(r.budget,r.environment,t),Be(r.allowedTools,t),$e(r,t),qe(r,t),n&&!r.environment?.network?.destinations?.some(i=>{let a=i.ports?.length?i.ports:[443];return i.host.toLowerCase()===n.hostname.toLowerCase()&&a.includes(Number(n.port||443))})&&t.push("inference origin is absent from the environment network allowlist");try{let i=je(r.environment?.repository);r.environment?.network?.destinations?.some(a=>{let m=a.ports?.length?a.ports:[443];return a.host.toLowerCase()===i.hostname&&m.includes(i.port)})||t.push("repository origin is absent from the environment network allowlist")}catch{t.push("environment repository must resolve to a credential-free HTTPS origin")}return{valid:t.length===0,errors:t}}function Me(e){let t=se(e);if(!t.valid)throw new Error(`Invalid hosted execution job: ${t.errors.join("; ")}`)}function De(e,t){(!e||!["read","workspace-write"].includes(e.filesystem))&&t.push("authority.filesystem is invalid"),(!e||!["deny","environment-policy"].includes(e.network))&&t.push("authority.network is invalid"),(!e||!["deny","approval-required"].includes(e.externalActions))&&t.push("authority.externalActions is invalid"),!Array.isArray(e?.secretRefs)||new Set(e.secretRefs).size!==e.secretRefs.length?t.push("authority.secretRefs must be a unique array"):e.secretRefs.forEach((r,n)=>b(r,`authority.secretRefs[${n}]`,t))}function Ve(e,t,r){(!e||!Number.isFinite(e.maxCredits)||e.maxCredits<=0)&&r.push("budget.maxCredits is invalid"),(!e||!B(e.maxDurationMs)||e.maxDurationMs>(t?.resources?.wallTimeMs??0))&&r.push("budget.maxDurationMs is invalid or exceeds the environment limit"),e?.maxTokens!==void 0&&!B(e.maxTokens)&&r.push("budget.maxTokens is invalid"),e?.maxToolCalls!==void 0&&!B(e.maxToolCalls)&&r.push("budget.maxToolCalls is invalid")}function Be(e,t){if(!Array.isArray(e)||e.length<1||e.length>512||new Set(e).size!==e.length){t.push("allowedTools must contain 1..512 unique tool names");return}e.forEach((r,n)=>{b(r,`allowedTools[${n}]`,t),Ne.has(r)||t.push(`allowedTools[${n}] is not in the hosted v0.1 registry`)})}function $e(e,t){if(!Array.isArray(e.secrets)||e.secrets.length>128){t.push("secrets must be a bounded array");return}let r=new Set(e.authority?.secretRefs??[]),n=new Map((e.environment?.secrets??[]).map(s=>[s.ref,s])),o=new Set;for(let[s,i]of e.secrets.entries()){let a=n.get(i.ref);if(!a||!r.has(i.ref)||o.has(i.ref)){t.push(`secrets[${s}] is undeclared, unauthorized, or duplicated`);continue}o.add(i.ref),(E(a.target)!==E(i.target)||a.exposeToChildProcesses!==i.exposeToChildProcesses)&&t.push(`secrets[${s}] does not match its declared projection`),(typeof i.value!="string"||i.value.length<1||Buffer.byteLength(i.value,"utf8")>1024*1024)&&t.push(`secrets[${s}] value is empty or too large`)}for(let s of e.environment?.secrets??[])s.required&&(!r.has(s.ref)||!o.has(s.ref))&&t.push(`required secret ${s.ref} is absent or unauthorized`);[...r].some(s=>!n.has(s))&&t.push("authority references an undeclared secret")}function qe(e,t){let r=e.expectedBoundary;if(!r){t.push("expectedBoundary is missing");return}let n;try{n=oe({certificationId:r.certificationId,environment:e.environment,authority:e.authority})}catch{t.push("expectedBoundary does not match the hosted execution contract");return}(!ie(r.certificationId)||E(r)!==E(n))&&t.push("expectedBoundary does not match the hosted execution contract")}function b(e,t,r){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,511}$/.test(e))&&r.push(`${t} is invalid`)}function V(e,t,r,n){(typeof e!="string"||e.length<1||e.length>r||e.includes("\0"))&&n.push(`${t} is invalid`)}function B(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function ie(e){return typeof e=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,511}$/.test(e)}function Le(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function E(e){return u(e)}function ee(e){return(0,te.createHash)("sha256").update(E(e)).digest("hex")}function je(e){if(!e)throw new Error("repository source is missing");let t=e.repository.replace(/^\/+|\/+$/g,""),r=e.provider==="github"&&!t.includes("://")?`https://github.com/${t}.git`:e.provider==="gitlab"&&!t.includes("://")?`https://gitlab.com/${t}.git`:e.provider==="bitbucket"&&!t.includes("://")?`https://bitbucket.org/${t}.git`:e.repository,n=new URL(r);if(n.protocol!=="https:"||n.username||n.password||n.hash)throw new Error("repository origin is not credential-free HTTPS");return{hostname:n.hostname.toLowerCase(),port:Number(n.port||443)}}var C=require("node:crypto");var q=1,L=1;function ce(e){let t={schemaVersion:q,kind:"xeno-hosted-control",controlId:l(e.controlId??`hctl_${(0,C.randomUUID)()}`,"controlId"),runId:l(e.runId,"runId"),workspaceId:l(e.workspaceId,"workspaceId"),actorId:l(e.actorId,"actorId"),idempotencyKey:f(e.idempotencyKey,"idempotencyKey",512),createdAt:j(e.createdAt,"createdAt"),action:Fe(e.action)};return{...t,hash:{algorithm:"sha256",value:ue(t)}}}function ze(e){let t=[];try{let{hash:r,schemaVersion:n,kind:o,...s}=e,i=ce(s);(e.schemaVersion!==q||e.kind!=="xeno-hosted-control")&&t.push("Unsupported hosted control command"),v(X(e))!==v(X(i))&&t.push("Hosted control command is not normalized"),(r?.algorithm!=="sha256"||r.value!==i.hash.value)&&t.push("Hosted control command hash mismatch")}catch(r){t.push(r instanceof Error?r.message:String(r))}return{valid:t.length===0,errors:t}}function Ue(e){if(!["accepted","applied","rejected","unsupported"].includes(e.status))throw new Error("Hosted control acknowledgement status is invalid");return{controlId:l(e.controlId,"controlId"),status:e.status,acknowledgedAt:j(e.acknowledgedAt,"acknowledgedAt"),...e.reason?{reason:f(e.reason,"reason",2048)}:{}}}function de(e){let t=e.git?{...e.git.branch?{branch:$(e.git.branch,"git.branch")}:{},...e.git.baseRef?{baseRef:$(e.git.baseRef,"git.baseRef")}:{},...e.git.commit?{commit:$(e.git.commit,"git.commit")}:{}}:void 0,r={schemaVersion:L,kind:"xeno-hosted-run-result",runId:l(e.runId,"runId"),workspaceId:l(e.workspaceId,"workspaceId"),completedAt:j(e.completedAt,"completedAt"),...t&&Object.keys(t).length>0?{git:t}:{},...e.pullRequest?{pullRequest:Ke(e.pullRequest)}:{},artifactIds:ae(e.artifactIds,"artifactIds"),evidenceArtifactIds:ae(e.evidenceArtifactIds,"evidenceArtifactIds")};return{...r,hash:{algorithm:"sha256",value:ue(r)}}}function Je(e){let t=[];try{let{hash:r,schemaVersion:n,kind:o,...s}=e,i=de(s);(e.schemaVersion!==L||e.kind!=="xeno-hosted-run-result")&&t.push("Unsupported hosted run result"),v(X(e))!==v(X(i))&&t.push("Hosted run result is not normalized"),(r?.algorithm!=="sha256"||r.value!==i.hash.value)&&t.push("Hosted run result hash mismatch")}catch(r){t.push(r instanceof Error?r.message:String(r))}return{valid:t.length===0,errors:t}}function Fe(e){if(e?.type==="message")return{type:"message",message:f(e.message,"action.message",32768)};if(e?.type==="approval"){if(e.decision!=="approved"&&e.decision!=="rejected")throw new Error("Hosted approval decision is invalid");return{type:"approval",requestId:l(e.requestId,"action.requestId"),decision:e.decision,scopeHash:Ge(e.scopeHash,"action.scopeHash"),...e.rationale?{rationale:f(e.rationale,"action.rationale",4096)}:{}}}throw new Error("Hosted control action is invalid")}function Ke(e){let t;try{t=new URL(e.url)}catch{throw new Error("pullRequest.url is invalid")}if(t.protocol!=="https:"||t.username||t.password)throw new Error("pullRequest.url must be credential-free HTTPS");if(!Number.isSafeInteger(e.number)||e.number<1)throw new Error("pullRequest.number must be a positive integer");return{provider:l(e.provider,"pullRequest.provider"),repository:f(e.repository,"pullRequest.repository",2048),number:e.number,url:t.toString()}}function ae(e,t){if(!Array.isArray(e)||e.length>1e4)throw new Error(`${t} is invalid`);return[...new Set(e.map((r,n)=>l(r,`${t}[${n}]`)))].sort()}function $(e,t){return f(e,t,512)}function l(e,t){let r=f(e,t,512);if(!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/.test(r))throw new Error(`${t} is invalid`);return r}function f(e,t,r){let n=e?.trim();if(!n||n.length>r||y(n,{allowTab:!0,allowLineBreaks:!0}))throw new Error(`${t} is invalid`);return n}function j(e,t){let r=Date.parse(e);if(!Number.isFinite(r)||new Date(r).toISOString()!==e)throw new Error(`${t} must be ISO-8601 UTC`);return e}function Ge(e,t){let r=e?.trim().toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error(`${t} must be a lowercase SHA-256 digest`);return r}function ue(e){return(0,C.createHash)("sha256").update(v(e)).digest("hex")}function v(e){return u(e)}function X(e){let{hash:t,...r}=e;return r}0&&(module.exports={XENO_HOSTED_CONTROL_SCHEMA_VERSION,XENO_HOSTED_ENVIRONMENT_SCHEMA_VERSION,XENO_HOSTED_EVENT_SCHEMA_VERSION,XENO_HOSTED_EXECUTION_ADAPTER_CERTIFICATION_SCHEMA,XENO_HOSTED_EXECUTION_ADAPTER_MAX_CERTIFICATE_LIFETIME_MS,XENO_HOSTED_EXECUTION_ADAPTER_PROTOCOL_VERSION,XENO_HOSTED_EXECUTION_PROTOCOL_VERSION,XENO_HOSTED_EXECUTION_TOOL_NAMES,XENO_HOSTED_RESULT_SCHEMA_VERSION,XENO_HOSTED_RUN_SCHEMA_VERSION,XENO_HOSTED_TRIGGER_SCHEMA_VERSION,assertValidXenoHostedExecutionJob,createXenoHostedControlCommand,createXenoHostedEnvironmentManifest,createXenoHostedEvent,createXenoHostedExecutionBoundaryReceipt,createXenoHostedRunResult,deriveHostedIdempotencyKey,hostedEnvironmentIdentity,normalizeXenoHostedControlAcknowledgement,verifyXenoHostedControlCommand,verifyXenoHostedEnvironmentManifest,verifyXenoHostedEventChain,verifyXenoHostedExecutionAdapterCertification,verifyXenoHostedExecutionJob,verifyXenoHostedRunResult,verifyXenoHostedWebhook,xenoHostedExecutionAdapterSigningPayload});
1
+ "use strict";var O=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var pe=Object.prototype.hasOwnProperty;var ge=(e,t)=>{for(var r in t)O(e,r,{get:t[r],enumerable:!0})},fe=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of me(t))!pe.call(e,o)&&o!==r&&O(e,o,{get:()=>t[o],enumerable:!(n=le(t,o))||n.enumerable});return e};var he=e=>fe(O({},"__esModule",{value:!0}),e);var We={};ge(We,{XENO_HOSTED_CONTROL_SCHEMA_VERSION:()=>q,XENO_HOSTED_ENVIRONMENT_SCHEMA_VERSION:()=>k,XENO_HOSTED_EVENT_SCHEMA_VERSION:()=>P,XENO_HOSTED_EXECUTION_ADAPTER_CERTIFICATION_SCHEMA:()=>w,XENO_HOSTED_EXECUTION_ADAPTER_MAX_CERTIFICATE_LIFETIME_MS:()=>W,XENO_HOSTED_EXECUTION_ADAPTER_PROTOCOL_VERSION:()=>M,XENO_HOSTED_EXECUTION_PROTOCOL_VERSION:()=>re,XENO_HOSTED_EXECUTION_TOOL_NAMES:()=>ne,XENO_HOSTED_RESULT_SCHEMA_VERSION:()=>L,XENO_HOSTED_RUN_SCHEMA_VERSION:()=>Qe,XENO_HOSTED_TRIGGER_SCHEMA_VERSION:()=>Ye,assertValidXenoHostedExecutionJob:()=>Me,createXenoHostedControlCommand:()=>ce,createXenoHostedEnvironmentManifest:()=>ye,createXenoHostedEvent:()=>xe,createXenoHostedExecutionBoundaryReceipt:()=>oe,createXenoHostedRunResult:()=>de,deriveHostedIdempotencyKey:()=>Ee,hostedEnvironmentIdentity:()=>be,normalizeXenoHostedControlAcknowledgement:()=>Ue,verifyXenoHostedControlCommand:()=>ze,verifyXenoHostedEnvironmentManifest:()=>I,verifyXenoHostedEventChain:()=>we,verifyXenoHostedExecutionAdapterCertification:()=>Oe,verifyXenoHostedExecutionJob:()=>se,verifyXenoHostedRunResult:()=>Je,verifyXenoHostedWebhook:()=>Ae,xenoHostedExecutionAdapterSigningPayload:()=>Ce});module.exports=he(We);var k=1,Qe=1,P=1,Ye=1;var x=require("node:crypto");function u(e){return JSON.stringify(N(e,new Set))}function N(e,t){if(e===null||typeof e!="object"){if(typeof e=="number"&&!Number.isFinite(e))throw new TypeError("Artifact JSON cannot contain non-finite numbers");return e}if(t.has(e))throw new TypeError("Artifact JSON cannot contain cycles");if(t.add(e),Array.isArray(e)){let n=e.map(o=>N(o,t));return t.delete(e),n}let r={};for(let n of Object.keys(e).sort((o,s)=>o.localeCompare(s))){let o=e[n];if(o===void 0)throw new TypeError(`Artifact JSON property ${n} is undefined`);r[n]=N(o,t)}return t.delete(e),r}function y(e,t={}){for(let r of e){let n=r.codePointAt(0);if(n===127)return!0;if(!(n>31)&&!(n===9&&t.allowTab===!0)&&!((n===10||n===13)&&t.allowLineBreaks===!0))return!0}return!1}function ye(e){let t={...J(e),schemaVersion:1,kind:"xeno-hosted-environment"};return{...t,checksum:{algorithm:"sha256",value:S(t)}}}function I(e){let t=[];if(e?.schemaVersion!==1||e.kind!=="xeno-hosted-environment")return t.push("Unsupported hosted environment manifest"),{valid:!1,errors:t};let r;try{let{checksum:n,schemaVersion:o,kind:s,...i}=e;r={...J(i),schemaVersion:1,kind:"xeno-hosted-environment"}}catch(n){return t.push(n instanceof Error?n.message:String(n)),{valid:!1,errors:t}}return u(r)!==u(ve(e))&&t.push("Hosted environment manifest is not normalized"),(e.checksum?.algorithm!=="sha256"||e.checksum.value!==S(r))&&t.push("Hosted environment checksum mismatch"),{valid:t.length===0,errors:t}}function xe(e){let t=p(e.streamId,"streamId"),r=K(e.sequence,"sequence");if(e.previous){if(e.previous.streamId!==t)throw new Error("Previous event belongs to another stream");if(e.previous.sequence+1!==r)throw new Error("Hosted event sequence must be contiguous")}else if(r!==1)throw new Error("The first hosted event sequence must be 1");let n={schemaVersion:1,kind:"xeno-hosted-event",eventId:p(e.eventId??`hevt_${(0,x.randomUUID)()}`,"eventId"),streamId:t,sequence:r,timestamp:G(e.timestamp??new Date().toISOString(),"timestamp"),type:F(e.type,"type"),actorId:p(e.actorId,"actorId"),...e.idempotencyKey?{idempotencyKey:c(e.idempotencyKey,"idempotencyKey",512)}:{},payload:ke(e.payload??{},"payload"),previousHash:e.previous?.hash??null};return{...n,hash:S(n)}}function we(e,t){let r=[],n,o=t?t.afterSequence+1:1,s=t?.lastHash??null;for(let a of e){if(a.schemaVersion!==1||a.kind!=="xeno-hosted-event"){r.push(`Unsupported hosted event at sequence ${String(a.sequence)}`);continue}a.sequence!==o&&r.push(`Hosted event sequence gap at ${a.sequence}; expected ${o}`),a.previousHash!==s&&r.push(`Hosted event previous hash mismatch at ${a.sequence}`);let{hash:m,...h}=a;m!==S(h)&&r.push(`Hosted event hash mismatch at ${a.sequence}`),n&&n.streamId!==a.streamId&&r.push(`Hosted event stream changed at ${a.sequence}`),n=a,o=a.sequence+1,s=a.hash}let i=e.at(-1);return{valid:r.length===0,errors:r,cursor:i?{streamId:i.streamId,afterSequence:i.sequence,lastHash:i.hash}:t??null}}function be(e){let t=I(e);if(!t.valid)throw new Error(t.errors.join("; "));return`${e.environmentId}@${e.revision}:${e.checksum.value}`}function Ee(...e){if(e.length===0)throw new Error("At least one idempotency-key part is required");let t=e.map((r,n)=>He(r,`parts[${n}]`));return`xeno:${(0,x.createHash)("sha256").update(t.join("\0")).digest("hex")}`}function J(e){let t=e.secrets.map((o,s)=>({ref:p(o.ref,`secrets[${s}].ref`),target:o.target.kind==="environment"?{kind:"environment",name:Se(o.target.name)}:{kind:"file",path:H(o.target.path,`secrets[${s}].target.path`)},required:!!o.required,exposeToChildProcesses:!!o.exposeToChildProcesses})),r=new Set,n=new Set;for(let o of t){if(r.has(o.ref))throw new Error(`Duplicate secret ref: ${o.ref}`);r.add(o.ref);let s=`${o.target.kind}:${o.target.kind==="environment"?o.target.name:o.target.path}`;if(n.has(s))throw new Error(`Duplicate secret target: ${s}`);n.add(s)}if(e.network.default!=="deny")throw new Error("Hosted network policy must be default-deny");return{environmentId:p(e.environmentId,"environmentId"),revision:K(e.revision,"revision"),createdAt:G(e.createdAt,"createdAt"),createdBy:p(e.createdBy,"createdBy"),workspaceId:p(e.workspaceId,"workspaceId"),name:c(e.name,"name",160),repository:{provider:e.repository.provider,repository:c(e.repository.repository,"repository.repository",2048),ref:c(e.repository.ref,"repository.ref",512),...e.repository.commit?{commit:Te(e.repository.commit,"repository.commit")}:{},...e.repository.subdirectory?{subdirectory:H(e.repository.subdirectory,"repository.subdirectory")}:{},...e.repository.shallow!==void 0?{shallow:!!e.repository.shallow}:{}},image:{reference:c(e.image.reference,"image.reference",2048),digest:_e(e.image.digest),os:e.image.os,architecture:e.image.architecture},setup:e.setup.map((o,s)=>({id:p(o.id,`setup[${s}].id`),command:c(o.command,`setup[${s}].command`,32768),...o.workingDirectory?{workingDirectory:H(o.workingDirectory,`setup[${s}].workingDirectory`)}:{},timeoutMs:d(o.timeoutMs,`setup[${s}].timeoutMs`,1e3,36e5),network:o.network})),caches:e.caches.map((o,s)=>({key:c(o.key,`caches[${s}].key`,512),path:H(o.path,`caches[${s}].path`),...o.restoreKeys?.length?{restoreKeys:Re(o.restoreKeys,`caches[${s}].restoreKeys`,512)}:{},...o.readOnly!==void 0?{readOnly:!!o.readOnly}:{},...o.maxBytes!==void 0?{maxBytes:d(o.maxBytes,`caches[${s}].maxBytes`,1,Number.MAX_SAFE_INTEGER)}:{}})),network:{default:"deny",dns:e.network.dns,destinations:e.network.destinations.map((o,s)=>({host:Ie(o.host,`network.destinations[${s}].host`),...o.ports?.length?{ports:[...new Set(o.ports.map(i=>d(i,"port",1,65535)))].sort((i,a)=>i-a)}:{},...o.protocols?.length?{protocols:[...new Set(o.protocols)].sort()}:{},reason:c(o.reason,`network.destinations[${s}].reason`,500)})).sort((o,s)=>o.host.localeCompare(s.host)),...e.network.maxResponseBytes!==void 0?{maxResponseBytes:d(e.network.maxResponseBytes,"network.maxResponseBytes",1,Number.MAX_SAFE_INTEGER)}:{}},secrets:t,resources:{cpuMillis:d(e.resources.cpuMillis,"resources.cpuMillis",10,1e6),memoryBytes:d(e.resources.memoryBytes,"resources.memoryBytes",16*1024*1024,Number.MAX_SAFE_INTEGER),diskBytes:d(e.resources.diskBytes,"resources.diskBytes",16*1024*1024,Number.MAX_SAFE_INTEGER),processLimit:d(e.resources.processLimit,"resources.processLimit",1,65535),wallTimeMs:d(e.resources.wallTimeMs,"resources.wallTimeMs",1e3,10080*60*1e3)},retention:{workspaceTtlMs:d(e.retention.workspaceTtlMs,"retention.workspaceTtlMs",0,365*24*60*60*1e3),eventTtlMs:d(e.retention.eventTtlMs,"retention.eventTtlMs",6e4,365*24*60*60*1e3),artifactTtlMs:d(e.retention.artifactTtlMs,"retention.artifactTtlMs",6e4,365*24*60*60*1e3),wipeWorkspace:!!e.retention.wipeWorkspace},labels:Object.fromEntries(Object.entries(e.labels).map(([o,s])=>[F(o,"label key"),c(s,`labels.${o}`,500)]).sort(([o],[s])=>o.localeCompare(s)))}}function ve(e){let{checksum:t,...r}=e;return r}function S(e){return(0,x.createHash)("sha256").update(u(e)).digest("hex")}function ke(e,t){let r=u(e);if(Buffer.byteLength(r,"utf8")>256*1024)throw new Error(`${t} exceeds 262144 bytes`);return JSON.parse(r)}function p(e,t){let r=c(e,t,512);if(!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/.test(r))throw new Error(`${t} is invalid`);return r}function F(e,t){let r=c(e,t,160);if(!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(r))throw new Error(`${t} is invalid`);return r}function c(e,t,r){let n=e.trim();if(!n||n.length>r||y(n,{allowTab:!0,allowLineBreaks:!0}))throw new Error(`${t} is invalid`);return n}function He(e,t){let r=e.trim();if(r.length>4096||y(r,{allowTab:!0,allowLineBreaks:!0}))throw new Error(`${t} is invalid`);return r}function K(e,t){return d(e,t,1,Number.MAX_SAFE_INTEGER)}function d(e,t,r,n){if(!Number.isSafeInteger(e)||e<r||e>n)throw new Error(`${t} must be an integer between ${r} and ${n}`);return e}function G(e,t){let r=Date.parse(e);if(!Number.isFinite(r)||new Date(r).toISOString()!==e)throw new Error(`${t} must be an ISO-8601 UTC timestamp`);return e}function Ie(e,t){let r=c(e.toLowerCase(),t,253);if(r==="localhost"||/^(?:\d{1,3}\.){3}\d{1,3}$/.test(r)||r.includes(":")||!/^(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(r))throw new Error(`${t} must be a public DNS hostname or wildcard hostname`);return r}function H(e,t){let r=c(e.replaceAll("\\","/"),t,4096);if(r.startsWith("/")||/^[A-Za-z]:\//.test(r)||r.split("/").includes(".."))throw new Error(`${t} must be workspace-relative`);return r.replace(/^\.\//,"")}function Se(e){let t=c(e,"secret environment name",256);if(!/^[A-Z_][A-Z0-9_]*$/.test(t))throw new Error("Secret environment target must be an uppercase environment variable name");return t}function _e(e){let t=e.trim().toLowerCase();if(!/^sha256:[a-f0-9]{64}$/.test(t))throw new Error("image.digest must be a sha256 OCI digest");return t}function Te(e,t){return c(e,t,512)}function Re(e,t,r){return[...new Set(e.map((n,o)=>c(n,`${t}[${o}]`,r)))]}var g=require("node:crypto");function Ae(e){let t=typeof e.body=="string"?Buffer.from(e.body,"utf8"):Buffer.from(e.body),r=(0,g.createHash)("sha256").update(t).digest("hex"),n=e.signature?.trim();if(!n)return{valid:!1,source:e.source,bodySha256:r,error:"missing-signature"};if(!e.secret||e.secret.length<16)throw new Error("Webhook secret must contain at least 16 characters");let o,s=n;if(e.source==="slack"){if(!e.timestamp||!/^\d+$/.test(e.timestamp))return{valid:!1,source:e.source,bodySha256:r,error:"invalid-timestamp"};let a=Number(e.timestamp)*1e3,m=Math.abs((e.now??new Date).getTime()-a);if(!Number.isFinite(a)||m>(e.maxClockSkewMs??5*6e4))return{valid:!1,source:e.source,bodySha256:r,timestamp:e.timestamp,error:"stale-timestamp"};o=`v0=${(0,g.createHmac)("sha256",e.secret).update(`v0:${e.timestamp}:`).update(t).digest("hex")}`}else e.source==="gitlab"?o=e.secret:e.source==="teams"?o=`HMAC ${(0,g.createHmac)("sha256",Buffer.from(e.secret,"base64")).update(t).digest("base64")}`:(o=`${e.source==="github"||e.source==="jira"?"sha256=":e.source==="xeno"?"v1=":""}${(0,g.createHmac)("sha256",e.secret).update(t).digest("hex")}`,e.source==="linear"&&s.startsWith("sha256=")&&(s=s.slice(7)));let i=Xe(o,s);return{valid:i,source:e.source,bodySha256:r,...e.timestamp?{timestamp:e.timestamp}:{},...i?{}:{error:"invalid-signature"}}}function Xe(e,t){let r=Buffer.from(e,"utf8"),n=Buffer.from(t,"utf8");return r.length===n.length&&(0,g.timingSafeEqual)(r,n)}var A=require("node:crypto");var w="xeno.hosted-execution-adapter-certification.v2",M=2,W=744*60*60*1e3;function Ce(e){return Z(e),Buffer.from(D(e),"utf8")}function Oe(e,t){if(e?.schemaVersion!==w)throw new Error(`Hosted execution adapter certificate must use ${w}`);let{signature:r,...n}=e;if(Z(n),r?.algorithm!=="ed25519")throw new Error("Hosted execution adapter signature must use ed25519");let o=T(t.executableSha256,"executableSha256"),s=T(t.controlPlaneCandidateSha256,"controlPlaneCandidateSha256");if(n.adapter.executableSha256!==o)throw new Error("Hosted execution adapter executable does not match its signed certificate");if(n.controlPlaneCandidateSha256!==s)throw new Error("Hosted execution adapter certificate is bound to another control-plane candidate");let i=t.platform??process.platform,a=t.architecture??process.arch;if(n.platform.os!==i||n.platform.architecture!==a)throw new Error(`Hosted execution adapter certificate targets ${n.platform.os}-${n.platform.architecture}, not ${i}-${a}`);let m=R(n.issuedAt,"issuedAt"),h=R(n.expiresAt,"expiresAt"),z=(t.now??new Date).getTime();if(m>z+5*6e4)throw new Error("Hosted execution adapter certificate is not yet valid");if(h<=z)throw new Error("Hosted execution adapter certificate has expired");if(h<=m||h-m>W)throw new Error("Hosted execution adapter certificate lifetime must be positive and at most 31 days");let U=t.trustedKeys[n.reviewer.keyId];if(!U)throw new Error(`Hosted execution adapter reviewer key is not trusted: ${n.reviewer.keyId}`);if(!(0,A.verify)(null,Buffer.from(D(n),"utf8"),U,Pe(r.value,"signature.value")))throw new Error("Hosted execution adapter certificate signature is invalid");return{certificationId:n.certificationId,adapterName:n.adapter.name,adapterVersion:n.adapter.version,protocolVersion:n.adapter.protocolVersion,executableSha256:o,controlPlaneCandidateSha256:s,certificateSha256:(0,A.createHash)("sha256").update(D(e)).digest("hex"),expiresAt:n.expiresAt,reviewerKeyId:n.reviewer.keyId}}function Z(e){if(e.schemaVersion!==w)throw new Error(`Hosted execution adapter certificate must use ${w}`);if(_(e.certificationId,"certificationId"),_(e.adapter?.name,"adapter.name"),_(e.adapter?.version,"adapter.version"),e.adapter?.protocolVersion!==M)throw new Error(`Hosted execution adapter protocol must be ${M}`);T(e.adapter.executableSha256,"adapter.executableSha256"),T(e.controlPlaneCandidateSha256,"controlPlaneCandidateSha256"),_(e.reviewer?.keyId,"reviewer.keyId");let t=["immutableImages","filesystemIsolation","networkDefaultDeny","destinationAllowlist","secretProjection","nonRootExecution","readOnlyRoot","processTreeCleanup","resourceLimits","interactiveControl","artifactProtocol","gitResultReporting"];if(!e.capabilities||t.some(r=>e.capabilities[r]!==!0))throw new Error("Hosted execution adapter certificate does not attest every required containment capability");R(e.issuedAt,"issuedAt"),R(e.expiresAt,"expiresAt")}function D(e){return u(e)}function T(e,t){let r=e?.trim().toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error(`${t} must be a lowercase SHA-256 digest`);return r}function _(e,t){let r=e?.trim();if(!r||r.length>256||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/.test(r))throw new Error(`${t} is invalid`);return r}function R(e,t){let r=Date.parse(e);if(!Number.isFinite(r)||new Date(r).toISOString()!==e)throw new Error(`${t} must be an ISO-8601 UTC timestamp`);return r}function Pe(e,t){if(typeof e!="string"||e.length===0||e.length>4096||!/^[A-Za-z0-9+/]+={0,2}$/.test(e))throw new Error(`${t} must be bounded base64`);let r=Buffer.from(e,"base64");if(r.toString("base64")!==e)throw new Error(`${t} is not canonical base64`);return r}var te=require("node:crypto");var Q=["low","medium","high","xhigh","max"],Y=["default","plan","acceptEdits","auto","dontAsk","bypassPermissions"];var re=2,ne=["Read","Write","Edit","Glob","Grep","WebFetch"],Ne=new Set(ne);function oe(e){if(!ie(e.certificationId))throw new Error("certificationId is invalid");let t=new Set(e.authority.secretRefs);return{certificationId:e.certificationId,environmentChecksum:e.environment.checksum.value,imageDigest:e.environment.image.digest,networkPolicySha256:ee({authority:e.authority.network,policy:e.environment.network}),secretProjectionSha256:ee(e.environment.secrets.filter(r=>t.has(r.ref))),filesystem:e.authority.filesystem,network:e.authority.network==="deny"?"deny":"allowlist",immutableImage:!0,readOnlyRoot:!0,nonRoot:!0,processTreeCleanup:!0,resourceLimits:!0,inferenceGateway:"brokered"}}function se(e){let t=[];if(!Le(e))return{valid:!1,errors:["Hosted execution job must be an object"]};let r=e;if(r.protocolVersion!==re||r.kind!=="xeno-hosted-execution-job")return t.push("Unsupported hosted execution protocol"),{valid:!1,errors:t};b(r.runId,"runId",t),b(r.userId,"userId",t),b(r.workspaceId,"workspaceId",t),V(r.workspaceHostPath,"workspaceHostPath",4096,t),V(r.prompt,"prompt",512*1024,t),V(r.model,"model",512,t),r.effort!==void 0&&!Q.includes(r.effort)&&t.push("effort is invalid"),Y.includes(r.permissionMode)||t.push("permissionMode is invalid"),(typeof r.runScopedToken!="string"||!r.runScopedToken.startsWith("xrun_")||r.runScopedToken.length>16*1024)&&t.push("runScopedToken is not a bounded run-scoped token");let n;try{n=new URL(r.inferenceBaseUrl),(n.protocol!=="https:"||n.username||n.password||n.hash)&&t.push("inferenceBaseUrl must be credential-free HTTPS")}catch{t.push("inferenceBaseUrl is invalid")}let o=I(r.environment);t.push(...o.errors.map(i=>`environment: ${i}`)),r.environment?.workspaceId!==r.workspaceId&&t.push("environment workspace does not match the job"),r.environment?.image?.os!=="linux"&&t.push("hosted execution image must target Linux");let s=r.environment?.repository?.commit;(typeof s!="string"||!/^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/.test(s))&&t.push("environment repository requires a full 40- or 64-character commit object id"),De(r.authority,t),Ve(r.budget,r.environment,t),Be(r.allowedTools,t),$e(r,t),qe(r,t),n&&!r.environment?.network?.destinations?.some(i=>{let a=i.ports?.length?i.ports:[443];return i.host.toLowerCase()===n.hostname.toLowerCase()&&a.includes(Number(n.port||443))})&&t.push("inference origin is absent from the environment network allowlist");try{let i=je(r.environment?.repository);r.environment?.network?.destinations?.some(a=>{let m=a.ports?.length?a.ports:[443];return a.host.toLowerCase()===i.hostname&&m.includes(i.port)})||t.push("repository origin is absent from the environment network allowlist")}catch{t.push("environment repository must resolve to a credential-free HTTPS origin")}return{valid:t.length===0,errors:t}}function Me(e){let t=se(e);if(!t.valid)throw new Error(`Invalid hosted execution job: ${t.errors.join("; ")}`)}function De(e,t){(!e||!["read","workspace-write"].includes(e.filesystem))&&t.push("authority.filesystem is invalid"),(!e||!["deny","environment-policy"].includes(e.network))&&t.push("authority.network is invalid"),(!e||!["deny","approval-required"].includes(e.externalActions))&&t.push("authority.externalActions is invalid"),!Array.isArray(e?.secretRefs)||new Set(e.secretRefs).size!==e.secretRefs.length?t.push("authority.secretRefs must be a unique array"):e.secretRefs.forEach((r,n)=>b(r,`authority.secretRefs[${n}]`,t))}function Ve(e,t,r){(!e||!Number.isFinite(e.maxCredits)||e.maxCredits<=0)&&r.push("budget.maxCredits is invalid"),(!e||!B(e.maxDurationMs)||e.maxDurationMs>(t?.resources?.wallTimeMs??0))&&r.push("budget.maxDurationMs is invalid or exceeds the environment limit"),e?.maxTokens!==void 0&&!B(e.maxTokens)&&r.push("budget.maxTokens is invalid"),e?.maxToolCalls!==void 0&&!B(e.maxToolCalls)&&r.push("budget.maxToolCalls is invalid")}function Be(e,t){if(!Array.isArray(e)||e.length<1||e.length>512||new Set(e).size!==e.length){t.push("allowedTools must contain 1..512 unique tool names");return}e.forEach((r,n)=>{b(r,`allowedTools[${n}]`,t),Ne.has(r)||t.push(`allowedTools[${n}] is not in the hosted v0.1 registry`)})}function $e(e,t){if(!Array.isArray(e.secrets)||e.secrets.length>128){t.push("secrets must be a bounded array");return}let r=new Set(e.authority?.secretRefs??[]),n=new Map((e.environment?.secrets??[]).map(s=>[s.ref,s])),o=new Set;for(let[s,i]of e.secrets.entries()){let a=n.get(i.ref);if(!a||!r.has(i.ref)||o.has(i.ref)){t.push(`secrets[${s}] is undeclared, unauthorized, or duplicated`);continue}o.add(i.ref),(E(a.target)!==E(i.target)||a.exposeToChildProcesses!==i.exposeToChildProcesses)&&t.push(`secrets[${s}] does not match its declared projection`),(typeof i.value!="string"||i.value.length<1||Buffer.byteLength(i.value,"utf8")>1024*1024)&&t.push(`secrets[${s}] value is empty or too large`)}for(let s of e.environment?.secrets??[])s.required&&(!r.has(s.ref)||!o.has(s.ref))&&t.push(`required secret ${s.ref} is absent or unauthorized`);[...r].some(s=>!n.has(s))&&t.push("authority references an undeclared secret")}function qe(e,t){let r=e.expectedBoundary;if(!r){t.push("expectedBoundary is missing");return}let n;try{n=oe({certificationId:r.certificationId,environment:e.environment,authority:e.authority})}catch{t.push("expectedBoundary does not match the hosted execution contract");return}(!ie(r.certificationId)||E(r)!==E(n))&&t.push("expectedBoundary does not match the hosted execution contract")}function b(e,t,r){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,511}$/.test(e))&&r.push(`${t} is invalid`)}function V(e,t,r,n){(typeof e!="string"||e.length<1||e.length>r||e.includes("\0"))&&n.push(`${t} is invalid`)}function B(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function ie(e){return typeof e=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,511}$/.test(e)}function Le(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function E(e){return u(e)}function ee(e){return(0,te.createHash)("sha256").update(E(e)).digest("hex")}function je(e){if(!e)throw new Error("repository source is missing");let t=e.repository.replace(/^\/+|\/+$/g,""),r=e.provider==="github"&&!t.includes("://")?`https://github.com/${t}.git`:e.provider==="gitlab"&&!t.includes("://")?`https://gitlab.com/${t}.git`:e.provider==="bitbucket"&&!t.includes("://")?`https://bitbucket.org/${t}.git`:e.repository,n=new URL(r);if(n.protocol!=="https:"||n.username||n.password||n.hash)throw new Error("repository origin is not credential-free HTTPS");return{hostname:n.hostname.toLowerCase(),port:Number(n.port||443)}}var C=require("node:crypto");var q=1,L=1;function ce(e){let t={schemaVersion:q,kind:"xeno-hosted-control",controlId:l(e.controlId??`hctl_${(0,C.randomUUID)()}`,"controlId"),runId:l(e.runId,"runId"),workspaceId:l(e.workspaceId,"workspaceId"),actorId:l(e.actorId,"actorId"),idempotencyKey:f(e.idempotencyKey,"idempotencyKey",512),createdAt:j(e.createdAt,"createdAt"),action:Fe(e.action)};return{...t,hash:{algorithm:"sha256",value:ue(t)}}}function ze(e){let t=[];try{let{hash:r,schemaVersion:n,kind:o,...s}=e,i=ce(s);(e.schemaVersion!==q||e.kind!=="xeno-hosted-control")&&t.push("Unsupported hosted control command"),v(X(e))!==v(X(i))&&t.push("Hosted control command is not normalized"),(r?.algorithm!=="sha256"||r.value!==i.hash.value)&&t.push("Hosted control command hash mismatch")}catch(r){t.push(r instanceof Error?r.message:String(r))}return{valid:t.length===0,errors:t}}function Ue(e){if(!["accepted","applied","rejected","unsupported"].includes(e.status))throw new Error("Hosted control acknowledgement status is invalid");return{controlId:l(e.controlId,"controlId"),status:e.status,acknowledgedAt:j(e.acknowledgedAt,"acknowledgedAt"),...e.reason?{reason:f(e.reason,"reason",2048)}:{}}}function de(e){let t=e.git?{...e.git.branch?{branch:$(e.git.branch,"git.branch")}:{},...e.git.baseRef?{baseRef:$(e.git.baseRef,"git.baseRef")}:{},...e.git.commit?{commit:$(e.git.commit,"git.commit")}:{}}:void 0,r={schemaVersion:L,kind:"xeno-hosted-run-result",runId:l(e.runId,"runId"),workspaceId:l(e.workspaceId,"workspaceId"),completedAt:j(e.completedAt,"completedAt"),...t&&Object.keys(t).length>0?{git:t}:{},...e.pullRequest?{pullRequest:Ke(e.pullRequest)}:{},artifactIds:ae(e.artifactIds,"artifactIds"),evidenceArtifactIds:ae(e.evidenceArtifactIds,"evidenceArtifactIds")};return{...r,hash:{algorithm:"sha256",value:ue(r)}}}function Je(e){let t=[];try{let{hash:r,schemaVersion:n,kind:o,...s}=e,i=de(s);(e.schemaVersion!==L||e.kind!=="xeno-hosted-run-result")&&t.push("Unsupported hosted run result"),v(X(e))!==v(X(i))&&t.push("Hosted run result is not normalized"),(r?.algorithm!=="sha256"||r.value!==i.hash.value)&&t.push("Hosted run result hash mismatch")}catch(r){t.push(r instanceof Error?r.message:String(r))}return{valid:t.length===0,errors:t}}function Fe(e){if(e?.type==="message")return{type:"message",message:f(e.message,"action.message",32768)};if(e?.type==="approval"){if(e.decision!=="approved"&&e.decision!=="rejected")throw new Error("Hosted approval decision is invalid");return{type:"approval",requestId:l(e.requestId,"action.requestId"),decision:e.decision,scopeHash:Ge(e.scopeHash,"action.scopeHash"),...e.rationale?{rationale:f(e.rationale,"action.rationale",4096)}:{}}}throw new Error("Hosted control action is invalid")}function Ke(e){let t;try{t=new URL(e.url)}catch{throw new Error("pullRequest.url is invalid")}if(t.protocol!=="https:"||t.username||t.password)throw new Error("pullRequest.url must be credential-free HTTPS");if(!Number.isSafeInteger(e.number)||e.number<1)throw new Error("pullRequest.number must be a positive integer");return{provider:l(e.provider,"pullRequest.provider"),repository:f(e.repository,"pullRequest.repository",2048),number:e.number,url:t.toString()}}function ae(e,t){if(!Array.isArray(e)||e.length>1e4)throw new Error(`${t} is invalid`);return[...new Set(e.map((r,n)=>l(r,`${t}[${n}]`)))].sort()}function $(e,t){return f(e,t,512)}function l(e,t){let r=f(e,t,512);if(!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/.test(r))throw new Error(`${t} is invalid`);return r}function f(e,t,r){let n=e?.trim();if(!n||n.length>r||y(n,{allowTab:!0,allowLineBreaks:!0}))throw new Error(`${t} is invalid`);return n}function j(e,t){let r=Date.parse(e);if(!Number.isFinite(r)||new Date(r).toISOString()!==e)throw new Error(`${t} must be ISO-8601 UTC`);return e}function Ge(e,t){let r=e?.trim().toLowerCase();if(!/^[a-f0-9]{64}$/.test(r))throw new Error(`${t} must be a lowercase SHA-256 digest`);return r}function ue(e){return(0,C.createHash)("sha256").update(v(e)).digest("hex")}function v(e){return u(e)}function X(e){let{hash:t,...r}=e;return r}0&&(module.exports={XENO_HOSTED_CONTROL_SCHEMA_VERSION,XENO_HOSTED_ENVIRONMENT_SCHEMA_VERSION,XENO_HOSTED_EVENT_SCHEMA_VERSION,XENO_HOSTED_EXECUTION_ADAPTER_CERTIFICATION_SCHEMA,XENO_HOSTED_EXECUTION_ADAPTER_MAX_CERTIFICATE_LIFETIME_MS,XENO_HOSTED_EXECUTION_ADAPTER_PROTOCOL_VERSION,XENO_HOSTED_EXECUTION_PROTOCOL_VERSION,XENO_HOSTED_EXECUTION_TOOL_NAMES,XENO_HOSTED_RESULT_SCHEMA_VERSION,XENO_HOSTED_RUN_SCHEMA_VERSION,XENO_HOSTED_TRIGGER_SCHEMA_VERSION,assertValidXenoHostedExecutionJob,createXenoHostedControlCommand,createXenoHostedEnvironmentManifest,createXenoHostedEvent,createXenoHostedExecutionBoundaryReceipt,createXenoHostedRunResult,deriveHostedIdempotencyKey,hostedEnvironmentIdentity,normalizeXenoHostedControlAcknowledgement,verifyXenoHostedControlCommand,verifyXenoHostedEnvironmentManifest,verifyXenoHostedEventChain,verifyXenoHostedExecutionAdapterCertification,verifyXenoHostedExecutionJob,verifyXenoHostedRunResult,verifyXenoHostedWebhook,xenoHostedExecutionAdapterSigningPayload});