@kodax-ai/kodax 0.7.95 → 0.7.96-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +178 -1
- package/LICENSE +158 -158
- package/README.md +149 -24
- package/README_CN.md +117 -24
- package/config-templates/config.example.jsonc +2 -1
- package/config-templates/integrations/a2a.example.jsonc +91 -91
- package/config-templates/integrations/extensions.example.jsonc +7 -7
- package/config-templates/integrations/mcp.example.jsonc +16 -16
- package/dist/builtin/code-review/SKILL.md +82 -82
- package/dist/builtin/git-workflow/SKILL.md +84 -84
- package/dist/builtin/skill-creator/SKILL.md +127 -127
- package/dist/builtin/skill-creator/agents/analyzer.md +12 -12
- package/dist/builtin/skill-creator/agents/comparator.md +13 -13
- package/dist/builtin/skill-creator/agents/grader.md +13 -13
- package/dist/builtin/skill-creator/references/schemas.md +227 -227
- package/dist/builtin/skill-creator/scripts/aggregate-benchmark.d.ts +46 -46
- package/dist/builtin/skill-creator/scripts/aggregate-benchmark.js +208 -208
- package/dist/builtin/skill-creator/scripts/analyze-benchmark.d.ts +46 -46
- package/dist/builtin/skill-creator/scripts/analyze-benchmark.js +286 -286
- package/dist/builtin/skill-creator/scripts/compare-runs.d.ts +62 -62
- package/dist/builtin/skill-creator/scripts/compare-runs.js +330 -330
- package/dist/builtin/skill-creator/scripts/generate-review.d.ts +33 -33
- package/dist/builtin/skill-creator/scripts/generate-review.js +414 -414
- package/dist/builtin/skill-creator/scripts/grade-evals.d.ts +73 -73
- package/dist/builtin/skill-creator/scripts/grade-evals.js +402 -402
- package/dist/builtin/skill-creator/scripts/improve-description.d.ts +23 -23
- package/dist/builtin/skill-creator/scripts/improve-description.js +160 -160
- package/dist/builtin/skill-creator/scripts/init-skill.d.ts +14 -14
- package/dist/builtin/skill-creator/scripts/init-skill.js +155 -155
- package/dist/builtin/skill-creator/scripts/install-skill.d.ts +29 -29
- package/dist/builtin/skill-creator/scripts/install-skill.js +173 -173
- package/dist/builtin/skill-creator/scripts/package-skill.d.ts +38 -38
- package/dist/builtin/skill-creator/scripts/package-skill.js +121 -121
- package/dist/builtin/skill-creator/scripts/quick-validate.d.ts +8 -8
- package/dist/builtin/skill-creator/scripts/quick-validate.js +163 -163
- package/dist/builtin/skill-creator/scripts/run-eval.d.ts +66 -66
- package/dist/builtin/skill-creator/scripts/run-eval.js +353 -353
- package/dist/builtin/skill-creator/scripts/run-loop.d.ts +49 -49
- package/dist/builtin/skill-creator/scripts/run-loop.js +242 -242
- package/dist/builtin/skill-creator/scripts/run-trigger-eval.d.ts +58 -58
- package/dist/builtin/skill-creator/scripts/run-trigger-eval.js +224 -224
- package/dist/builtin/tdd/SKILL.md +56 -56
- package/dist/chunks/agent-4FABF6WK.js +2 -0
- package/dist/chunks/argument-completer-72VHB2VL.js +2 -0
- package/dist/chunks/{chunk-7JXA3533.js → chunk-4OIQZWA5.js} +223 -226
- package/dist/chunks/{chunk-BNVSKIAB.js → chunk-6BVF3HZ7.js} +136 -136
- package/dist/chunks/chunk-7JZZIFZH.js +501 -0
- package/dist/chunks/chunk-AC7Z2OIY.js +2 -0
- package/dist/chunks/{chunk-JS452J2F.js → chunk-C4KYZAFU.js} +2 -2
- package/dist/chunks/chunk-CHUPIWIF.js +251 -0
- package/dist/chunks/{chunk-C4DTUKTR.js → chunk-GYUU7XLH.js} +5 -4
- package/dist/chunks/{chunk-OK4AXDC5.js → chunk-HAX55GOQ.js} +1 -1
- package/dist/chunks/chunk-JKTJCGO2.js +418 -0
- package/dist/chunks/{chunk-O743AJ5V.js → chunk-LQYETRFK.js} +171 -175
- package/dist/chunks/{chunk-2PEDBGKN.js → chunk-LTUZTQ6W.js} +1 -1
- package/dist/chunks/chunk-LYWDUSKO.js +2 -0
- package/dist/chunks/chunk-NGH6T4FD.js +92 -0
- package/dist/chunks/{chunk-SRIJX5ZP.js → chunk-NVRWCSA5.js} +1 -1
- package/dist/chunks/chunk-O4DS7RIQ.js +384 -0
- package/dist/chunks/chunk-ORXU6OWZ.js +2 -0
- package/dist/chunks/chunk-POTW3O65.js +124 -0
- package/dist/chunks/{chunk-2TM3W3GK.js → chunk-RIQSS56Y.js} +1 -1
- package/dist/chunks/chunk-U27XKEN5.js +407 -0
- package/dist/chunks/{chunk-6ABQJUK6.js → chunk-XUX6OUCA.js} +2 -2
- package/dist/chunks/{client-JDOS3YJR.js → client-4C456K4O.js} +1 -1
- package/dist/chunks/compaction-config-3VQRDFF4.js +2 -0
- package/dist/chunks/{construction-bootstrap-YCWHHUYO.js → construction-bootstrap-AHN7EDGG.js} +1 -1
- package/dist/chunks/dist-BCBQXAGI.js +2 -0
- package/dist/chunks/dist-QK2YDWU6.js +2 -0
- package/dist/chunks/host-VIHV7ADG.js +2 -0
- package/dist/chunks/run-manager-NBVMU3KV.js +2 -0
- package/dist/chunks/utils-MEJZ2IGI.js +2 -0
- package/dist/index.d.ts +22 -21
- package/dist/index.js +7 -7
- package/dist/kodax_bootstrap.js +26 -26
- package/dist/kodax_cli.js +1905 -1882
- package/dist/native/darwin-arm64/LICENSE-APACHE.txt +13 -0
- package/dist/native/darwin-arm64/kodax-text-transaction.node +0 -0
- package/dist/native/darwin-arm64/manifest.json +16 -0
- package/dist/native/darwin-x64/LICENSE-APACHE.txt +13 -0
- package/dist/native/darwin-x64/kodax-text-transaction.node +0 -0
- package/dist/native/darwin-x64/manifest.json +16 -0
- package/dist/native/linux-arm64/LICENSE-APACHE.txt +13 -0
- package/dist/native/linux-arm64/kodax-text-transaction.node +0 -0
- package/dist/native/linux-arm64/manifest.json +16 -0
- package/dist/native/linux-x64/LICENSE-APACHE.txt +13 -0
- package/dist/native/linux-x64/kodax-text-transaction.node +0 -0
- package/dist/native/linux-x64/manifest.json +16 -0
- package/dist/native/win32-x64/LICENSE-APACHE.txt +13 -0
- package/dist/native/win32-x64/NOTICE-windows-sandbox.txt +8 -0
- package/dist/native/win32-x64/kodax-windows-sandbox.exe +0 -0
- package/dist/native/win32-x64/kodax-windows-text-transaction.node +0 -0
- package/dist/native/win32-x64/manifest.json +30 -0
- package/dist/provider-capabilities.json +108 -2
- package/dist/runtime-worker.js +1745 -1727
- package/dist/sandbox-network-broker.js +1715 -0
- package/dist/sdk-a2a.d.ts +13 -12
- package/dist/sdk-a2a.js +1 -1
- package/dist/sdk-agent.d.ts +27 -18
- package/dist/sdk-agent.js +1 -1
- package/dist/sdk-coding.d.ts +107 -58
- package/dist/sdk-coding.js +1 -1
- package/dist/sdk-experimental-memory.d.ts +4 -4
- package/dist/sdk-experimental-memory.js +1 -1
- package/dist/sdk-llm.d.ts +9 -10
- package/dist/sdk-llm.js +1 -1
- package/dist/sdk-mcp.js +1 -1
- package/dist/sdk-media.d.ts +1 -1
- package/dist/sdk-media.js +1 -1
- package/dist/sdk-repl.d.ts +25 -17
- package/dist/sdk-repl.js +1 -1
- package/dist/sdk-runtime.d.ts +41 -17
- package/dist/sdk-runtime.js +1 -1
- package/dist/sdk-sandbox.d.ts +17 -3
- package/dist/sdk-sandbox.js +1 -1
- package/dist/sdk-session.d.ts +8 -7
- package/dist/sdk-session.js +1 -1
- package/dist/sdk-skills.js +1 -1
- package/dist/semantic-worker.js +61 -61
- package/dist/types-chunks/{base.d-vopO1rml.d.ts → base.d-COo8E2dk.d.ts} +18 -27
- package/dist/types-chunks/{bash-prefix-extractor.d-B2rxNI4L.d.ts → bash-prefix-extractor.d-DQOlA8cy.d.ts} +72 -52
- package/dist/types-chunks/{capability-learning.d-CE1tm29C.d.ts → capability-learning.d-lRPgA3Or.d.ts} +1 -1
- package/dist/types-chunks/{capsule.d-Y7QRS4J2.d.ts → capsule.d-0zxsgXg_.d.ts} +3 -3
- package/dist/types-chunks/{controller.d-BR-UVeUR.d.ts → controller.d-BTtyIIC1.d.ts} +1 -1
- package/dist/types-chunks/{controller.d-C5noq5-w.d.ts → controller.d-C7tXUcXo.d.ts} +2 -2
- package/dist/types-chunks/{guardrail.d-DqHD-61O.d.ts → guardrail.d-DKTyEHJa.d.ts} +5 -5
- package/dist/types-chunks/{history-retrieval.d-CKU8zmt_.d.ts → history-retrieval.d-CHnL99S7.d.ts} +2 -2
- package/dist/types-chunks/{public-api.d-D7fXaWW8.d.ts → public-api.d-Dx3L3W4Z.d.ts} +7 -4
- package/dist/types-chunks/{repl.d-BYDb14s6.d.ts → repl.d-mO01olIa.d.ts} +5 -5
- package/dist/types-chunks/{resolver.d-CwHUwbdE.d.ts → resolver.d-DlXPjeyx.d.ts} +38 -6
- package/dist/types-chunks/{review-inbox.d-BSgFewyj.d.ts → review-inbox.d-WDSe1nze.d.ts} +1 -1
- package/dist/types-chunks/{run-manager.d-BVJSntpS.d.ts → run-manager.d-DENbbzgR.d.ts} +1 -1
- package/dist/types-chunks/{sdk-session-CqEG84oP.d.ts → sdk-session-DYHGXXH4.d.ts} +3 -3
- package/dist/types-chunks/{shell-command-sets.d-DqaaBwhU.d.ts → shell-command-sets.d-CjFqS4dp.d.ts} +1 -1
- package/dist/types-chunks/{side-query.d-iH0P9ASy.d.ts → side-query.d-j8A3sFv_.d.ts} +2 -2
- package/dist/types-chunks/{types.d-rUOjXych.d.ts → types.d-BbZjR0Wr.d.ts} +1 -1
- package/dist/types-chunks/{types.d-CaTXAW_Q.d.ts → types.d-BkTIKdH6.d.ts} +2 -2
- package/dist/types-chunks/{types.d-C5xQEFcj.d.ts → types.d-DncLrpu_.d.ts} +4 -4
- package/dist/types-chunks/{types.d-CK9A9rpP.d.ts → types.d-Xy0f3x4i.d.ts} +9 -0
- package/dist/types-chunks/{utils.d-CWUyLiXo.d.ts → utils.d-CnxefMos.d.ts} +6 -6
- package/package.json +10 -3
- package/public_docs/README.md +130 -0
- package/public_docs/configuration/sandbox.md +289 -0
- package/public_docs/sdk/embedder-guide.md +6674 -0
- package/scripts/kodax-bin.cjs +28 -28
- package/scripts/production-env.cjs +25 -25
- package/dist/chunks/agent-XXZMXKKA.js +0 -2
- package/dist/chunks/argument-completer-KCYDGTQW.js +0 -2
- package/dist/chunks/chunk-77PNP27P.js +0 -92
- package/dist/chunks/chunk-7QBWHCIZ.js +0 -2
- package/dist/chunks/chunk-BHE66SP3.js +0 -123
- package/dist/chunks/chunk-BR2OSB2I.js +0 -722
- package/dist/chunks/chunk-DSMONSVB.js +0 -407
- package/dist/chunks/chunk-Q5VRWSKG.js +0 -418
- package/dist/chunks/chunk-XWRPOGJN.js +0 -4
- package/dist/chunks/chunk-Y5VIQBT6.js +0 -383
- package/dist/chunks/compaction-config-EGS4577X.js +0 -2
- package/dist/chunks/dist-ITTXQHRJ.js +0 -2
- package/dist/chunks/dist-KFYN3OKD.js +0 -2
- package/dist/chunks/host-VAYADIPW.js +0 -2
- package/dist/chunks/run-manager-52IJZMZJ.js +0 -2
- package/dist/chunks/utils-P7PBSL3R.js +0 -2
- package/dist/sandbox-workspace-session.js +0 -1705
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
+
import{p as o}from"./chunk-POTW3O65.js";import{a as i}from"./chunk-ONUPGMER.js";function r(u){let e=o(u?.llm);if(!e)return;let t={};return e.requestTimeoutMs!==void 0&&(t.requestTimeoutMs=e.requestTimeoutMs),e.streamIdleTimeoutMs!==void 0&&(t.streamIdleTimeoutMs=e.streamIdleTimeoutMs),e.chunkTimeoutMs!==void 0&&(t.chunkTimeoutMs=e.chunkTimeoutMs),e.maxRetryDelayMs!==void 0&&(t.maxRetryDelayMs=e.maxRetryDelayMs),Object.keys(t).length>0?t:void 0}i(r,"providerResilienceConfigFromTimeouts");export{r as a};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{
|
|
2
|
+
import{Ee as Qe,Ob as Ke,Pb as Le,Sb as ze,Tb as Je,se as ge,te as Ge,ve as Xe,we as Ye,xe as Ze}from"./chunk-4OIQZWA5.js";import{R as Ne}from"./chunk-POTW3O65.js";import{Bg as me,Hg as pe,Ig as B,Jg as we,Kg as Ue,Rg as Ve,Sg as Be,Tg as He,rg as re,ug as De,v as fe,vg as je,xg as Z}from"./chunk-6BVF3HZ7.js";import{a as i}from"./chunk-ONUPGMER.js";import{basename as kr,dirname as vr}from"node:path";import{execFile as Qt}from"node:child_process";import oe from"node:path";import{promisify as en}from"node:util";var tn=en(Qt),nn=1e4,at=2,et=new Set(["write","edit","multi_edit","insert_after_anchor"]),tt=new Set(["read"]);function rn(e,t){if(t.includes("*"))return e;if(e.includes("*"))return t;let n=new Set(t);return e.filter(r=>n.has(r))}i(rn,"intersectWorkflowToolCeilings");var on=/^\s*(?:let me|i will|i'll|i am going to)\b[\s\S]{0,120}\b(?:start|create|implement|write|build|plan)\b|^\s*(?:我将|让我|接下来)[\s\S]{0,80}(?:开始|创建|编写|实现|制定)/i;function an(e){if(e?.timeoutMs!==void 0){if(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0)throw new Error("workflow wait timeoutMs must be a positive number");return Math.floor(e.timeoutMs)}}i(an,"normalizeWaitTimeoutMs");function he(e){return e?.requiresMutation===!0||(e?.requiredChangedPaths?.length??0)>0}i(he,"hasVerificationWork");function H(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").trim()}i(H,"normalizeWorkspacePath");function ye(e,t){let n=t.gitRoot?oe.resolve(t.gitRoot):void 0,r=oe.isAbsolute(e)&&n?oe.relative(n,oe.resolve(e)):e;return H(r)}i(ye,"normalizeRequiredPath");function sn(e){let t=(e.readOnly??!1)===!1?{enforcement:"warn",requiresMutation:!0,rejectPreparatoryFinalText:!0}:void 0;if(e.verification!==void 0){let n={...t??{},...e.verification,enforcement:e.verification.enforcement??"hard"},r=e.verification.requiredChangedPaths;return{verification:{...n,...r!==void 0&&r.length>0&&n.requiresMutation===void 0?{requiresMutation:!0}:{}}}}return{verification:t}}i(sn,"resolveVerificationForInput");function cn(e,t){if(t===!0&&e.readOnly===!1)throw new Error(`workflow manifest readOnly=true cannot spawn write-capable child "${e.name}"; set the workflow manifest readOnly=false or use child readOnly:true`);let n=e.readOnly??t??!1;return e.readOnly===n?e:{...e,readOnly:n}}i(cn,"resolveSpawnAgentInput");function st(e){let t=e.trim();return t.length>0&&on.test(t)}i(st,"isPreparatoryOnlyText");function dn(e,t){let n=e.trim(),r=t?.trim();return r&&(n.length===0||st(n))?r:e}i(dn,"selectWorkflowFinalText");async function ie(e,t){return(await tn("git",[...e],{cwd:t,timeout:nn,windowsHide:!0,maxBuffer:4194304})).stdout.toString()}i(ie,"runGit");async function un(e){let t=e.gitRoot??e.executionCwd??process.cwd(),n=(await ie(["rev-parse","--show-toplevel"],t)).trim(),r=await Promise.all([ie(["diff","--name-only","--"],n),ie(["diff","--cached","--name-only","--"],n),ie(["ls-files","--others","--exclude-standard"],n)]);return[...new Set(r.flatMap(a=>a.split(/\r?\n/)).map(H).filter(a=>a.length>0))]}i(un,"listGitChangedFiles");async function ke(e,t){try{return{paths:(await t(e)).map(H).filter(r=>r.length>0)}}catch(n){return{paths:[],error:n instanceof Error?n.message:String(n)}}}i(ke,"captureChangedPaths");function ln(){return{toolNameById:new Map,toolPathById:new Map,succeededToolCalls:[],succeededPaths:[],readPathById:new Map,succeededReadPaths:[]}}i(ln,"createMutationRecorder");function nt(e){if(e)for(let t of["path","file_path","target_path"]){let n=e[t];if(typeof n=="string"&&n.trim().length>0)return H(n)}}i(nt,"readMutationPath");function fn(e,t){return{...e??{},onToolUseStart:i((n,r)=>{if(et.has(n.name)){t.toolNameById.set(n.id,n.name);let a=nt(n.input);a!==void 0&&t.toolPathById.set(n.id,a)}if(tt.has(n.name)){let a=nt(n.input);a!==void 0&&t.readPathById.set(n.id,a)}e?.onToolUseStart?.(n,r)},"onToolUseStart"),onToolResult:i((n,r)=>{let a=t.toolNameById.get(n.id)??n.name;if(et.has(a)&&!n.content.trimStart().startsWith("[Tool Error]")){t.succeededToolCalls.push(a);let o=t.toolPathById.get(n.id);o!==void 0&&t.succeededPaths.push(o)}if(tt.has(a)&&!n.content.trimStart().startsWith("[Tool Error]")){let o=t.readPathById.get(n.id);o!==void 0&&t.succeededReadPaths.push(o)}e?.onToolResult?.(n,r)},"onToolResult")}}i(fn,"wrapEventsForMutationRecording");function ae(e){return[...new Set(e.filter(t=>t.trim().length>0))]}i(ae,"uniqueItems");function rt(e){let t=e.verification;if(!t)return;let n=[],r=new Set(e.before.paths.map(H)),a=ae(e.after.paths.map(H)),o=a.filter(m=>!r.has(m)),s=ae(e.mutationRecorder.succeededToolCalls),d=e.acceptToolMutationEvidence?s:[],g=e.acceptToolMutationEvidence?ae(e.mutationRecorder.succeededPaths.map(H)):[],h=o.length>0||d.length>0,y=t.enforcement??"hard",p=(t.requiredChangedPaths??[]).map(m=>ye(m,e.ctx)),b=ae(e.mutationRecorder.succeededReadPaths.map(m=>ye(m,e.ctx))),v=(t.requiredReadPaths??[]).map(m=>ye(m,e.ctx));t.requiresMutation===!0&&(e.before.error!==void 0||e.after.error!==void 0?n.push(`workspace mutation verification could not read changed files: ${e.after.error??e.before.error}`):h||n.push(e.acceptToolMutationEvidence||s.length===0?"expected file mutations, but no new workspace changes or successful write tools were observed":"write tools ran in an isolated worktree, but no main workspace changes were present after cleanup")),e.term.limitReached===!0&&!h&&n.push("workflow child reached its iteration limit before satisfying the task");for(let m of p)!a.includes(m)&&!g.includes(m)&&n.push(`required changed path was not present in workspace changes: ${m}`);for(let m of v)b.includes(m)||n.push(`required review evidence was not read: ${m}`);let W=t.minFinalTextChars;return W!==void 0&&!h&&e.term.finalText.trim().length<W&&n.push(`finalText was shorter than the required ${W} characters`),t.rejectPreparatoryFinalText===!0&&!h&&st(e.term.finalText)&&n.push("finalText looks preparatory instead of terminal"),{ok:n.length===0,enforcement:y,reasons:n,changedPaths:a,mutationToolCalls:s,mutationEvidence:h,...b.length>0?{readPaths:b}:{}}}i(rt,"evaluateVerification");function ve(e,t){if(t.ok)return e;let r=[t.enforcement==="warn"?"[Workflow task completed without verification]":"[Workflow task verification failed]",...t.reasons.map(a=>`- ${a}`)].join(`
|
|
3
3
|
`);return e.trim().length>0?`${e}
|
|
4
4
|
|
|
5
5
|
${r}`:r}i(ve,"appendVerificationFailure");function ot(){return{ok:!1,enforcement:"warn",reasons:["workflow child reached its iteration limit before satisfying the task"],mutationEvidence:!1}}i(ot,"limitReachedWarningVerification");function mn(e){return e.entry.bundle.readOnly!==!0&&e.entry.repairAttempts<at&&e.term.status==="completed"&&e.verification!==void 0&&e.verification.ok!==!0&&e.verification.enforcement!=="warn"}i(mn,"shouldRepairVerificationFailure");function pn(e){let t=e.verification.reasons.map(r=>`- ${r}`).join(`
|
|
@@ -13,7 +13,7 @@ ${s.text}`),rubric:t.rubric??vn}))).text,findings:r,degraded:a}}i(Pn,"runParalle
|
|
|
13
13
|
`).trim().replace(/[\t\n\f\r ]+/g," ")}i(j,"normalizeText");function lt(e){return j(e).replace(/\\/g,"/")}i(lt,"normalizeLocation");function se(e){return[...new Set(e.map(j).filter(Boolean))].sort((t,n)=>t<n?-1:t>n?1:0)}i(se,"uniqueSorted");function An(e,t,n){return Mn("sha256").update(`${e}\0${lt(t)}\0${j(n)}`,"utf8").digest("hex")}i(An,"findingId");function ft(e,t,n){if(!t&&n.specVerdict!=="not-verifiable")throw new Error('review result must use specVerdict "not-verifiable" when requirements are absent');return{specVerdict:n.specVerdict,qualityVerdict:n.qualityVerdict,findings:n.findings.map(r=>{let a=lt(r.location),o=j(r.claim),s=j(r.evidence);return{findingId:An(e,a,o),severity:r.severity,location:a,claim:o,evidence:s,...r.suggestedFix?{suggestedFix:j(r.suggestedFix)}:{}}}).sort((r,a)=>r.findingId<a.findingId?-1:r.findingId>a.findingId?1:0),unverifiedRequirements:se(n.unverifiedRequirements)}}i(ft,"normalizeScopedReviewResult");var ut={low:0,medium:1,high:2,critical:3};function En(e){return e.reduce((t,n)=>ut[n]>ut[t]?n:t,"low")}i(En,"maxSeverity");function mt(e){if(e.length===0)throw new Error("at least one primary review result is required");let t=new Map;for(let a of e)for(let o of a.findings)t.set(o.findingId,[...t.get(o.findingId)??[],o]);let n=[...t.entries()].map(([a,o])=>({findingId:a,severity:En(o.map(s=>s.severity)),location:o[0].location,claim:o[0].claim,evidence:se(o.map(s=>s.evidence)),suggestedFixes:se(o.flatMap(s=>s.suggestedFix?[s.suggestedFix]:[]))})).sort((a,o)=>a.findingId<o.findingId?-1:a.findingId>o.findingId?1:0);return{specVerdict:e.some(a=>a.specVerdict==="issues")?"issues":e.some(a=>a.specVerdict==="not-verifiable")?"not-verifiable":"compliant",qualityVerdict:e.some(a=>a.qualityVerdict==="needs-fixes")?"needs-fixes":"approved",findings:n,unverifiedRequirements:se(e.flatMap(a=>a.unverifiedRequirements))}}i(mt,"mergeScopedReviewResults");function pt(e,t){let n=new Set(e.findings.map(s=>s.findingId)),r=new Set;for(let s of t.findings){if(!n.has(s.findingId)||r.has(s.findingId))throw new Error("verifier must return every input findingId exactly once");r.add(s.findingId)}if(r.size!==n.size)throw new Error("verifier must return every input findingId exactly once");let a=new Map(t.findings.map(s=>[s.findingId,s])),o=e.findings.flatMap(s=>{let d=a.get(s.findingId);if(d.disposition==="refuted")return[];let g=d.severityReason?.trim(),h=d.effectiveSeverity!==void 0&&!!g;return[{...s,disposition:d.disposition,severity:h?d.effectiveSeverity:s.severity,verificationEvidence:j(d.evidence),...g?{severityReason:j(g)}:{}}]});return{specVerdict:e.specVerdict,qualityVerdict:e.qualityVerdict,unverifiedRequirements:e.unverifiedRequirements,actionable:o,audit:t,unqualifiedApprovalAllowed:o.length===0&&e.unverifiedRequirements.length===0&&e.specVerdict==="compliant"&&e.qualityVerdict==="approved"}}i(pt,"applyFindingVerification");var Wn={type:"object",additionalProperties:!1,required:["summary"],properties:{summary:{type:"string"}}};function gt(e){return[e.packetPath,...e.evidenceChunks.map(t=>t.path)]}i(gt,"evidencePaths");function Fn(e){let t=ge(e,Se);if(t.length>0)throw new Error(`primary reviewer structured result is invalid: ${t.join("; ")}`);return e}i(Fn,"rawReview");function On(e){let t=ge(e,Re);if(t.length>0)throw new Error(`finding verifier structured result is invalid: ${t.join("; ")}`);return e}i(On,"rawVerification");function be(e,t){if(e===null||e.status!=="completed")throw new Error(`${t} did not complete; no verdict was accepted`);if(e.verification!==void 0&&!e.verification.ok)throw new Error(`${t} did not read every required packet path; no verdict was accepted`);return e}i(be,"resultOrThrow");function qn(e,t,n){return["Review one immutable KodaX packet as an independent third-party reviewer.",`Packet manifest: ${e.packetPath}`,...e.evidenceChunks.map(r=>`Evidence chunk: ${r.path}`),`This packet has binding requirements: ${e.requirementsPresent?"yes":"no"}.`,t?"This is the additional high-risk primary. Actively seek a disagreement with the first reader; do not assume it was correct.":"Own both specification and implementation-quality verdicts for this scope.",n.lean?"Also identify unnecessary additions, but never remove validation, security, data-loss protection, accessibility, or requested behavior.":"",n.reviewFocus?`Additional user focus: ${n.reviewFocus}`:"","Read the manifest and every listed chunk with the read tool before deciding.","Begin with the required JSON result. No preamble or process narration.","The findings array contains only actionable defects, never approval evidence or positive observations.","When the scope is compliant and approved with no actionable defect, findings must be empty.","If a named requirement cannot be proven compliant or violated from surfaced evidence, use specVerdict not-verifiable, list it in unverifiedRequirements, and emit no finding for that uncertainty; absence of evidence is not proof of a defect.","If requirements are absent, specVerdict must be not-verifiable."].filter(Boolean).join(`
|
|
14
14
|
`)}i(qn,"buildScopedReviewPrimaryPrompt");function Cn(e,t){return["Independently attempt to refute every candidate finding in this batch.",`Packet manifest: ${e.packetPath}`,...e.evidenceChunks.map(n=>`Evidence chunk: ${n.path}`),`Canonical candidates: ${JSON.stringify(t.findings)}`,"Read the packet evidence. You may run one focused check after naming the concrete doubt.","Return every findingId exactly once. A severity change requires severityReason.","Begin with the required JSON result; no preamble."].join(`
|
|
15
15
|
`)}i(Cn,"buildScopedReviewVerificationPrompt");function $n(e){return["Synthesize the structured review results below without rereading packet bodies.","Lead with confirmed findings, keep unresolved findings visibly unresolved, omit refuted findings from the actionable list, and never silently downgrade severity.","Cite locations and state explicitly when no actionable issue was confirmed.",JSON.stringify(e)].join(`
|
|
16
|
-
`)}i($n,"buildScopedReviewFinalPrompt");async function wt(e,t,n,r){let a=be(await e.runAgent({name:`${n?"high-risk-":""}primary-${t.partitionKey}`,phase:"primary-review",prompt:qn(t,n,r),scopeSummary:`${t.partitionKey}: ${t.scopePaths.join(", ")}`,constraints:["read every required packet path","return both verdicts","cite evidence at each finding"],readOnly:!0,modelHint:n?"deep":"balanced",verification:{enforcement:"hard",requiredReadPaths:gt(t)},outputSchema:Se,terseResult:!0}),"primary reviewer");return e.log({message:`primary read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"primary",contentHash:t.contentHash}}),Fn(a.structured)}i(wt,"runPrimary");async function _n(e,t,n){if(n.findings.length===0)return{specVerdict:n.specVerdict,qualityVerdict:n.qualityVerdict,unverifiedRequirements:n.unverifiedRequirements,actionable:[],audit:{findings:[]},unqualifiedApprovalAllowed:n.unverifiedRequirements.length===0&&n.specVerdict==="compliant"&&n.qualityVerdict==="approved"};let r=be(await e.runAgent({name:`verify-${t.partitionKey}`,phase:"verifier",prompt:Cn(t,n),scopeSummary:`verify ${n.findings.length} candidate finding(s) in ${t.partitionKey}`,constraints:["fresh context","attempt refutation","one disposition per findingId"],readOnly:!0,modelHint:"deep",verification:{enforcement:"hard",requiredReadPaths:gt(t)},outputSchema:Re,terseResult:!0}),"finding verifier");return e.log({message:`verification read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"verification",contentHash:t.contentHash,reason:"candidate findings"}}),pt(n,On(r.structured))}i(_n,"verifyFindings");async function Nn(e,t,n){let r=[await wt(e,t,!1,n)];t.riskFlags.includes("routing-high")&&r.push(await wt(e,t,!0,n));let a=r.map(d=>ft(t.contentHash,t.requirementsPresent,d)),o=mt(a),s=await _n(e,t,o);return e.log({message:`quality gate completed for ${t.partitionKey}`,data:{kind:"review_quality_gate",contentHash:t.contentHash,actionableFindings:s.actionable.length,unresolvedFindings:s.actionable.filter(d=>d.disposition==="unresolved").length,unqualifiedApprovalAllowed:s.unqualifiedApprovalAllowed}}),{contentHash:t.contentHash,result:s}}i(Nn,"reviewPacket");async function Dn(e,t){if(!Array.isArray(t.packets)||t.packets.length===0)throw new Error("scoped-review requires at least one review packet");let n=await e.parallel(t.packets.map(d=>()=>Nn(e,d,t)),{concurrency:4});if(n.some(d=>d===null))throw new Error("one or more scope packets failed review; no final verdict was accepted");let r=n.filter(d=>d!==null);await e.artifact("scoped-review-audit",r);let a=be(await e.runAgent({name:"final-review-synthesis",phase:"final-synthesis",prompt:$n(r),scopeSummary:`cross-scope synthesis for ${r.length} packet(s)`,constraints:["preserve severity","preserve unresolved uncertainty","do not invent evidence"],readOnly:!0,modelHint:"deep",outputSchema:Wn,terseResult:!0}),"final synthesis"),o=a.structured;return{summary:typeof o?.summary=="string"?o.summary:a.finalText,packetResults:r}}i(Dn,"runScopedReview");var ht={meta:{name:"scoped-review",description:"Review immutable scope packets once, verify only candidate findings, then synthesize.",readOnly:!0,phases:["primary-review","verifier","final-synthesis"],maxAgents:64,maxConcurrency:4},run:Dn};function yt(e){return{meta:e.meta,run:i((t,n)=>e.run(t,n),"run")}}i(yt,"erase");var kt=[yt(dt),yt(ht)];function vt(e){return kt.find(t=>t.meta.name===e)}i(vt,"getBuiltinWorkflow");function no(){return kt.map(e=>e.meta)}i(no,"listBuiltinWorkflows");import{mkdir as Tt,readdir as jn,readFile as Q,rename as Un,unlink as Pe,writeFile as Me}from"node:fs/promises";import{basename as Vn,dirname as Ie,join as K}from"node:path";import{pathToFileURL as Bn}from"node:url";var It=[".workflow.json",".ts",".mjs",".js"],ee="0.7.49";function Pt(){return"0.7.
|
|
16
|
+
`)}i($n,"buildScopedReviewFinalPrompt");async function wt(e,t,n,r){let a=be(await e.runAgent({name:`${n?"high-risk-":""}primary-${t.partitionKey}`,phase:"primary-review",prompt:qn(t,n,r),scopeSummary:`${t.partitionKey}: ${t.scopePaths.join(", ")}`,constraints:["read every required packet path","return both verdicts","cite evidence at each finding"],readOnly:!0,modelHint:n?"deep":"balanced",verification:{enforcement:"hard",requiredReadPaths:gt(t)},outputSchema:Se,terseResult:!0}),"primary reviewer");return e.log({message:`primary read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"primary",contentHash:t.contentHash}}),Fn(a.structured)}i(wt,"runPrimary");async function _n(e,t,n){if(n.findings.length===0)return{specVerdict:n.specVerdict,qualityVerdict:n.qualityVerdict,unverifiedRequirements:n.unverifiedRequirements,actionable:[],audit:{findings:[]},unqualifiedApprovalAllowed:n.unverifiedRequirements.length===0&&n.specVerdict==="compliant"&&n.qualityVerdict==="approved"};let r=be(await e.runAgent({name:`verify-${t.partitionKey}`,phase:"verifier",prompt:Cn(t,n),scopeSummary:`verify ${n.findings.length} candidate finding(s) in ${t.partitionKey}`,constraints:["fresh context","attempt refutation","one disposition per findingId"],readOnly:!0,modelHint:"deep",verification:{enforcement:"hard",requiredReadPaths:gt(t)},outputSchema:Re,terseResult:!0}),"finding verifier");return e.log({message:`verification read accepted for ${t.partitionKey}`,data:{kind:"review_packet_read",role:"verification",contentHash:t.contentHash,reason:"candidate findings"}}),pt(n,On(r.structured))}i(_n,"verifyFindings");async function Nn(e,t,n){let r=[await wt(e,t,!1,n)];t.riskFlags.includes("routing-high")&&r.push(await wt(e,t,!0,n));let a=r.map(d=>ft(t.contentHash,t.requirementsPresent,d)),o=mt(a),s=await _n(e,t,o);return e.log({message:`quality gate completed for ${t.partitionKey}`,data:{kind:"review_quality_gate",contentHash:t.contentHash,actionableFindings:s.actionable.length,unresolvedFindings:s.actionable.filter(d=>d.disposition==="unresolved").length,unqualifiedApprovalAllowed:s.unqualifiedApprovalAllowed}}),{contentHash:t.contentHash,result:s}}i(Nn,"reviewPacket");async function Dn(e,t){if(!Array.isArray(t.packets)||t.packets.length===0)throw new Error("scoped-review requires at least one review packet");let n=await e.parallel(t.packets.map(d=>()=>Nn(e,d,t)),{concurrency:4});if(n.some(d=>d===null))throw new Error("one or more scope packets failed review; no final verdict was accepted");let r=n.filter(d=>d!==null);await e.artifact("scoped-review-audit",r);let a=be(await e.runAgent({name:"final-review-synthesis",phase:"final-synthesis",prompt:$n(r),scopeSummary:`cross-scope synthesis for ${r.length} packet(s)`,constraints:["preserve severity","preserve unresolved uncertainty","do not invent evidence"],readOnly:!0,modelHint:"deep",outputSchema:Wn,terseResult:!0}),"final synthesis"),o=a.structured;return{summary:typeof o?.summary=="string"?o.summary:a.finalText,packetResults:r}}i(Dn,"runScopedReview");var ht={meta:{name:"scoped-review",description:"Review immutable scope packets once, verify only candidate findings, then synthesize.",readOnly:!0,phases:["primary-review","verifier","final-synthesis"],maxAgents:64,maxConcurrency:4},run:Dn};function yt(e){return{meta:e.meta,run:i((t,n)=>e.run(t,n),"run")}}i(yt,"erase");var kt=[yt(dt),yt(ht)];function vt(e){return kt.find(t=>t.meta.name===e)}i(vt,"getBuiltinWorkflow");function no(){return kt.map(e=>e.meta)}i(no,"listBuiltinWorkflows");import{mkdir as Tt,readdir as jn,readFile as Q,rename as Un,unlink as Pe,writeFile as Me}from"node:fs/promises";import{basename as Vn,dirname as Ie,join as K}from"node:path";import{pathToFileURL as Bn}from"node:url";var It=[".workflow.json",".ts",".mjs",".js"],ee="0.7.49";function Pt(){return"0.7.96-alpha.2"}i(Pt,"currentKodaxWorkflowVersion");function Hn(e){return e.endsWith(".workflow.json")?"capability-generated":"trusted-local"}i(Hn,"executionForPath");function Kn(e){let t=It.find(n=>e.endsWith(n));return t?e.slice(0,-t.length):void 0}i(Kn,"stripWorkflowSuffix");function Ae(e){let t=e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").slice(0,80);if(!t||t==="."||t==="..")throw new Error("workflow name must contain at least one safe filename character");return t}i(Ae,"safeWorkflowName");function Ee(e){return typeof e=="object"&&e!==null}i(Ee,"isRecord");function xt(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`workflow run.json missing ${t}`);return n}i(xt,"readRequiredString");async function St(e,t){if(!e)return[];let n;try{n=await jn(e)}catch{return[]}let r=new Map;for(let a of It)for(let o of n){if(!o.endsWith(a))continue;let s=Kn(o);if(!s||s.length===0||r.has(s))continue;let d=K(e,o);r.set(s,{name:s,path:d,source:t,execution:Hn(d)})}return[...r.values()]}i(St,"scanDir");async function te(e){let t=await St(e.personal,"personal"),n=await St(e.project,"project"),r=new Map;for(let a of t)r.set(a.name,a);for(let a of n)r.set(a.name,a);return[...r.values()].sort((a,o)=>a.name.localeCompare(o.name))}i(te,"discoverSavedWorkflows");function Ln(e){return typeof e=="object"&&e!==null&&"meta"in e&&"run"in e&&typeof e.run=="function"}i(Ln,"isWorkflowModule");function zn(e){let t=e.default;if(Ln(t))return t;let n=typeof t=="function"?t:e.run,r=e.workflow??e.meta;if(typeof n=="function"&&typeof r=="object"&&r!==null&&"name"in r)return{meta:r,run:n};throw new Error("invalid workflow module: expected a `{ meta, run }` default export, or `export const workflow = {...}` + a default run function")}i(zn,"normalizeWorkflowModule");function Jn(e){let t=JSON.parse(e);if(!Ee(t))throw new Error("generated workflow file must be an object");if(t.format!==void 0&&t.format!=="kodax.workflow")throw new Error(`unsupported workflow capsule format: ${String(t.format)}`);if(t.format==="kodax.workflow"){let a=pe(t);return{manifest:a.manifest,source:a.source,capsule:a,legacy:!1}}let n=t.source;if(typeof n!="string"||n.trim().length===0)throw new Error("generated workflow file source must be a non-empty string");let r=Z(t.manifest);return{manifest:r,source:n,capsule:B({minKodaxVersion:ee,manifest:r,source:n}),legacy:!0}}i(Jn,"parseGeneratedWorkflowFile");async function We(e){let t=Jn(await Q(e,"utf8"));return t.capsule??B({minKodaxVersion:ee,manifest:t.manifest,source:t.source})}i(We,"loadSavedWorkflowCapsule");async function Mt(e){if(e.endsWith(".workflow.json"))return we(await We(e));let t=await import(Bn(e).href);return zn(t)}i(Mt,"loadSavedWorkflow");function Fe(e){if(e.mayUseWorktree===!0)return{environment:["git-repo","worktree-capable"]}}i(Fe,"deriveRequirements");function ce(e,t){me(t,{filename:`${e.name}.workflow.js`,requireAsyncRun:!0})}i(ce,"assertGeneratedCapsuleSource");async function Gn(e){let t=Ae(e.name),n=Z(e.manifest);ce(n,e.source);let r=e.requires??Fe(n),a=B({minKodaxVersion:e.minKodaxVersion??ee,manifest:n,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...r!==void 0?{requires:r}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}});await Tt(e.dir,{recursive:!0});let o=K(e.dir,`${t}.workflow.json`);return await Me(o,`${JSON.stringify(a,null,2)}
|
|
17
17
|
`,"utf8"),{name:t,path:o,source:"project",execution:"capability-generated"}}i(Gn,"saveGeneratedWorkflow");async function Rt(e,t){await Me(e,`${JSON.stringify(t,null,2)}
|
|
18
18
|
`,"utf8")}i(Rt,"writeCapsuleFile");async function Xn(e){try{return await Q(e,"utf8"),!0}catch{return!1}}i(Xn,"fileExists");async function uo(e){let t=(await te(e.dirs)).filter(d=>d.name===e.name).filter(d=>e.source===void 0||d.source===e.source);if(t.length===0)throw new Error(`saved workflow not found: ${e.name}`);if(t.length>1)throw new Error(`ambiguous saved workflow name: ${e.name}`);let n=t[0];if(!n.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be renamed");let r=Ae(e.newName),a=K(Ie(n.path),`${r}.workflow.json`);if(a!==n.path&&await Xn(a))throw new Error(`saved workflow already exists: ${r}`);let o=await We(n.path);ce(o.manifest,o.source);let s=B({minKodaxVersion:o.minKodaxVersion,manifest:{...o.manifest,name:r},source:o.source,...o.intent!==void 0?{intent:o.intent}:{},...o.inputs!==void 0?{inputs:o.inputs}:{},...o.requires!==void 0?{requires:o.requires}:{},...o.provenance!==void 0?{provenance:o.provenance}:{}});return await Me(a,`${JSON.stringify(s,null,2)}
|
|
19
19
|
`,"utf8"),a!==n.path&&await Pe(n.path),{name:r,path:a,source:n.source,execution:"capability-generated"}}i(uo,"renameSavedWorkflow");async function lo(e){let t=(await te(e.dirs)).filter(r=>r.name===e.name).filter(r=>e.source===void 0||r.source===e.source);if(t.length===0)throw new Error(`saved workflow not found: ${e.name}`);if(t.length>1)throw new Error(`ambiguous saved workflow name: ${e.name}`);let n=t[0];if(!n.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be deleted");return await Pe(n.path),n}i(lo,"deleteSavedWorkflow");async function fo(e){let t=Ae(e.name),n=(await te(e.dirs)).filter(v=>v.name===t).filter(v=>e.savedSource===void 0||v.source===e.savedSource);if(n.length===0)throw new Error(`saved workflow not found: ${t}`);if(n.length>1)throw new Error(`ambiguous saved workflow name: ${t}`);let r=n[0];if(!r.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be replaced");let a=Z({...e.manifest,name:t});ce(a,e.source);let o=e.requires??Fe(a),s=B({minKodaxVersion:e.minKodaxVersion??ee,manifest:a,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...o!==void 0?{requires:o}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}}),d=await We(r.path),g=new Date().toISOString().replace(/[:.]/g,"-"),h=K(Ie(r.path),".revisions",t),y=`${g}-${process.hrtime.bigint().toString(36)}`,p=K(h,`${t}-${y}.workflow.json`),b=K(Ie(r.path),`.${t}.${process.pid}.${Date.now().toString(36)}.tmp`);await Tt(h,{recursive:!0}),await Rt(p,d);try{await Rt(b,s),await Un(b,r.path)}catch(v){try{await Pe(b)}catch{}throw v}return{name:t,path:r.path,source:r.source,execution:"capability-generated",previousPath:p}}i(fo,"replaceSavedWorkflow");function Yn(e){if(!Ee(e))return;let t=e.request;if(typeof t=="string"&&t.trim().length>0)return t;let n=e.question;if(typeof n=="string"&&n.trim().length>0)return n}i(Yn,"readOptionalOriginalRequest");function At(e){return Zn(e)}i(At,"buildCapsuleFromRun");async function Zn(e){let t=JSON.parse(await Q(K(e.runDir,"run.json"),"utf8"));if(!Ee(t))throw new Error("workflow run.json must be an object");let n=xt(t,"scriptSnapshotPath"),r=xt(t,"manifestSnapshotPath"),a=await Q(n,"utf8"),o=Z(JSON.parse(await Q(r,"utf8")));ce(o,a);let s=typeof t.runId=="string"&&t.runId.length>0?t.runId:Vn(e.runDir),d=Yn(t.args),g=Fe(o),h=Ue(o,d!==void 0?{originalRequest:d}:{}),y={description:"Provide new workflow args matching the generated request shape.",..."args"in t?{examples:[t.args]}:{}};return B({minKodaxVersion:ee,manifest:o,source:a,intent:h,inputs:y,...g!==void 0?{requires:g}:{},provenance:{fromRunId:s,createdAt:new Date().toISOString(),kodaxVersion:Pt()}})}i(Zn,"readCapsuleFromRun");async function mo(e){let t=await At(e);return{capsule:t,module:we(t)}}i(mo,"loadGeneratedWorkflowFromRun");async function po(e){let t=await At(e);return Gn({dir:e.targetDir,name:e.name,manifest:t.manifest,source:t.source,...t.intent!==void 0?{intent:t.intent}:{},...t.inputs!==void 0?{inputs:t.inputs}:{},...t.requires!==void 0?{requires:t.requires}:{},...t.provenance!==void 0?{provenance:t.provenance}:{},minKodaxVersion:t.minKodaxVersion})}i(po,"saveGeneratedWorkflowFromRun");function U(e,t,n,r){e.push({severity:t,requirement:n,message:r})}i(U,"addRequirementIssue");function bt(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e.trim());if(t)return[Number(t[1]),Number(t[2]),Number(t[3])]}i(bt,"parseSemver");function Qn(e,t){for(let n=0;n<3;n+=1){let r=e[n]-t[n];if(r!==0)return r}return 0}i(Qn,"compareSemver");function er(e,t,n){let r=bt(t),a=bt(n);if(!r){U(e,"error","kodax:min-version",`workflow minKodaxVersion is not valid semver: ${t}`);return}if(!a){U(e,"warning","kodax:min-version",`cannot verify workflow minKodaxVersion ${t}; current version is unknown`);return}Qn(a,r)<0&&U(e,"error","kodax:min-version",`workflow requires KodaX >= ${t}, current version is ${n}`)}i(er,"addMinVersionIssue");function Te(e,t,n,r){if(!n)return;if(!r){for(let o of n)U(e,"warning",`${t}:${o}`,`workflow requires ${t}:${o}, but no ${t} inventory was provided`);return}let a=new Set(r);for(let o of n)a.has(o)||U(e,"error",`${t}:${o}`,`missing required workflow ${t}: ${o}`)}i(Te,"addMissingItems");function wo(e,t={}){let n=pe(e),r=[],a=n.requires;er(r,n.minKodaxVersion,t.kodaxVersion??Pt()),a?.environment?.includes("git-repo")&&t.isGitRepo===!1&&U(r,"error","environment:git-repo","workflow requires a git repository"),a?.environment?.includes("worktree-capable")&&t.worktreeCapable===!1&&U(r,"error","environment:worktree-capable","workflow may request git worktree isolation");try{me(n.source,{filename:`${n.manifest.name}.workflow.js`,requireAsyncRun:!0})}catch(o){let s=o instanceof Error?o.message:String(o);U(r,"error","workflow:source",s)}return Te(r,"tools",a?.tools,t.availableTools),Te(r,"mcp",a?.mcp,t.availableMcp),Te(r,"skills",a?.skills,t.availableSkills),{ok:!r.some(o=>o.severity==="error"),issues:r}}i(wo,"preflightWorkflowCapsule");function nr(e){return{project:Et(e,".kodax","workflows"),personal:Et(tr(),".kodax","workflows")}}i(nr,"defaultSavedWorkflowDirs");async function rr(e,t){let r=(await te(t)).find(a=>a.name===e);if(r)return Mt(r.path)}i(rr,"resolveSavedByName");function Wt(e){let t=nr(e);return async n=>vt(n)??await rr(n,t)}i(Wt,"createNestedWorkflowResolver");import{existsSync as or,mkdirSync as ir,readFileSync as ar,writeFileSync as Ft}from"node:fs";import{join as ne}from"node:path";var Ot="results";function qt(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}i(qt,"safeKey");function Ct(e,t){let n=ne(e,t);if(or(n))try{return JSON.parse(ar(n,"utf8"))}catch{return}}i(Ct,"readResult");function $t(e,t={}){let n=ne(e,Ot);ir(n,{recursive:!0});let r=t.readFrom?ne(t.readFrom,Ot):void 0;return{get:i(a=>{let o=`${qt(a)}.json`,s=Ct(n,o);if(s!==void 0)return s;if(r===void 0)return;let d=Ct(r,o);if(d!==void 0){try{Ft(ne(n,o),JSON.stringify(d),"utf8")}catch{}return d}},"get"),set:i((a,o)=>{try{Ft(ne(n,`${qt(a)}.json`),JSON.stringify(o),"utf8")}catch{}},"set")}}i($t,"createFsResultCache");import{mkdirSync as sr,appendFileSync as cr,writeFileSync as ue}from"node:fs";import{join as J}from"node:path";function de(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}i(de,"record");function F(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0}i(F,"finiteNumber");function _t(e){let t=new Map,n=new Set,r=[],a=[],o=new Set,s=[],d=[],g=0,h=0,y=0,p=0,b=0,v=0,W=0,m=0,T={},$=[];for(let C of e){let M=C.data??{};if(C.type==="agent_spawned"){let u=typeof M.taskId=="string"?M.taskId:void 0;u&&t.set(u,M),M.role==="primary-review"&&(v+=1);let w=typeof M.role=="string"?M.role:"agent",S=typeof M.requestedTier=="string"?M.requestedTier:"inherited",I=`${w}/${S}`;T[I]=(T[I]??0)+1;continue}if(C.type==="agent_completed"||C.type==="agent_unverified"||C.type==="agent_failed"){let u=typeof M.taskId=="string"?M.taskId:void 0;if(!u||n.has(u))continue;n.add(u);let w=de(M.usage);!w||typeof w.totalTokens!="number"?typeof t.get(u)?.externalTarget=="string"?a.push(u):r.push(u):(g+=F(w.totalTokens),h+=F(w.inputTokens),y+=F(w.cacheReadTokens??w.cachedReadTokens),p+=F(w.outputTokens));let S=de(M.digestUsage);b+=F(S?.totalTokens),h+=F(S?.inputTokens),p+=F(S?.outputTokens),y+=F(S?.cacheReadTokens??S?.cachedReadTokens),W+=F(M.iterations);continue}if(C.type==="agent_summary_updated"){let u=de(M.usage),w=M.summaryKind;if((w==="digest"||w==="digest-failed")&&u){let S=F(u.totalTokens);g+=S,b+=S,h+=F(u.inputTokens),p+=F(u.outputTokens),y+=F(u.cacheReadTokens??u.cachedReadTokens)}continue}if(C.type!=="workflow_log")continue;let f=de(M.data);if(f?.kind==="review_quality_gate"&&typeof f.contentHash=="string"){$.push({contentHash:f.contentHash,actionableFindings:F(f.actionableFindings),unresolvedFindings:F(f.unresolvedFindings),unqualifiedApprovalAllowed:f.unqualifiedApprovalAllowed===!0});continue}if(f?.kind!=="review_packet_read"||typeof f.contentHash!="string")continue;let l={contentHash:f.contentHash,...typeof f.reason=="string"?{reason:f.reason}:{}};f.role==="primary"?(o.has(f.contentHash)&&(m+=1),o.add(f.contentHash)):f.role==="verification"?s.push(l):f.role==="synthesis"&&d.push(l)}for(let C of t.keys())n.has(C)||r.push(C);let G=[...new Set(r)].sort();return{totalModelTokens:g,inputTokens:h,cacheReadTokens:y,outputTokens:p,digestTokens:b,agentStarts:t.size,childTurns:W,agentStartsByRoleTier:T,primaryReviewStarts:v,duplicatePrimaryPacketReads:m,verificationPacketReads:s,synthesisPacketReads:d,reviewWaves:v>0?1:0,fixWaves:0,rereviewWaves:0,qualityGateOutcomes:$,tokenCoverage:{ok:G.length===0,missingTaskIds:G},excludedExternalTaskIds:[...new Set(a)].sort()}}i(_t,"buildWorkflowCostReport");function dr(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,120);return t.length>0?t:"artifact"}i(dr,"safeWorkflowArtifactName");function Nt(e,t={}){let n=t.now??(()=>Date.now()),r=J(e,"artifacts");sr(r,{recursive:!0});let a=J(e,"events.jsonl");return{runDir:e,onEvent:i(o=>{cr(a,`${JSON.stringify({...o,ts:n()})}
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
+
import{Ka as A}from"./chunk-6BVF3HZ7.js";import{a}from"./chunk-ONUPGMER.js";import{spawnSync as I}from"node:child_process";import{createHash as g}from"node:crypto";import c from"node:fs";import X from"node:os";import o from"node:path";import{fileURLToPath as P}from"node:url";var O=64*1024*1024,B="v2";function R(){{let e=JSON.parse('{"darwin-arm64":"{\\n \\"version\\": 1,\\n \\"platform\\": \\"darwin\\",\\n \\"arch\\": \\"arm64\\",\\n \\"textTransaction\\": {\\n \\"file\\": \\"kodax-text-transaction.node\\",\\n \\"protocol\\": 4,\\n \\"sha256\\": \\"1e97f7b76ef08446be731e3dad2c50b2c9040aa1f590f59d366bcab3f42ab37b\\"\\n },\\n \\"legal\\": [\\n {\\n \\"file\\": \\"LICENSE-APACHE.txt\\",\\n \\"sha256\\": \\"6bdadfab6d5d2b0d4e0ccea244f5e412d1597dc84c56db645556ce192b131e98\\"\\n }\\n ]\\n}\\n","darwin-x64":"{\\n \\"version\\": 1,\\n \\"platform\\": \\"darwin\\",\\n \\"arch\\": \\"x64\\",\\n \\"textTransaction\\": {\\n \\"file\\": \\"kodax-text-transaction.node\\",\\n \\"protocol\\": 4,\\n \\"sha256\\": \\"e8869134d922b402ddf28a5b0363fdf5cd4062a3691f271b9abc7e7f31d76c01\\"\\n },\\n \\"legal\\": [\\n {\\n \\"file\\": \\"LICENSE-APACHE.txt\\",\\n \\"sha256\\": \\"6bdadfab6d5d2b0d4e0ccea244f5e412d1597dc84c56db645556ce192b131e98\\"\\n }\\n ]\\n}\\n","linux-arm64":"{\\n \\"version\\": 1,\\n \\"platform\\": \\"linux\\",\\n \\"arch\\": \\"arm64\\",\\n \\"textTransaction\\": {\\n \\"file\\": \\"kodax-text-transaction.node\\",\\n \\"protocol\\": 4,\\n \\"sha256\\": \\"7ead104d167fd65560bfe1d24ea222d85d4ca53bfe91245a004e87d4d7f29d84\\"\\n },\\n \\"legal\\": [\\n {\\n \\"file\\": \\"LICENSE-APACHE.txt\\",\\n \\"sha256\\": \\"6bdadfab6d5d2b0d4e0ccea244f5e412d1597dc84c56db645556ce192b131e98\\"\\n }\\n ]\\n}\\n","linux-x64":"{\\n \\"version\\": 1,\\n \\"platform\\": \\"linux\\",\\n \\"arch\\": \\"x64\\",\\n \\"textTransaction\\": {\\n \\"file\\": \\"kodax-text-transaction.node\\",\\n \\"protocol\\": 4,\\n \\"sha256\\": \\"6cef66472facf03fad1796764f4e7c76c710ec89baafcb12197a7466b0ce7f56\\"\\n },\\n \\"legal\\": [\\n {\\n \\"file\\": \\"LICENSE-APACHE.txt\\",\\n \\"sha256\\": \\"6bdadfab6d5d2b0d4e0ccea244f5e412d1597dc84c56db645556ce192b131e98\\"\\n }\\n ]\\n}\\n","win32-x64":"{\\n \\"version\\": 1,\\n \\"platform\\": \\"win32\\",\\n \\"arch\\": \\"x64\\",\\n \\"textTransaction\\": {\\n \\"file\\": \\"kodax-windows-text-transaction.node\\",\\n \\"protocol\\": 4,\\n \\"sha256\\": \\"c88742e5d91c25908d30686111c704caf2f72c40628e990a00f1a1a169d52487\\"\\n },\\n \\"legal\\": [\\n {\\n \\"file\\": \\"LICENSE-APACHE.txt\\",\\n \\"sha256\\": \\"f8dd90eb71a7af4048bde3ff1d18b7d7280522e0a429ff71b7270a4189cf3568\\"\\n },\\n {\\n \\"file\\": \\"NOTICE-windows-sandbox.txt\\",\\n \\"sha256\\": \\"78723eb162f0782c5e27928f46c681996edc1907d552eba9d0f7f53e014c20c9\\"\\n }\\n ],\\n \\"shellSandbox\\": {\\n \\"file\\": \\"kodax-windows-sandbox.exe\\",\\n \\"protocol\\": 7,\\n \\"sha256\\": \\"907cc02e8586913780fa228d7eca08073a8231f702b81f7ca813709197d26245\\"\\n },\\n \\"asrtRunner\\": {\\n \\"file\\": \\"srt-win.exe\\",\\n \\"version\\": \\"0.0.65\\",\\n \\"sha256\\": \\"777736e17d6cf9b4280f155f5cda731fdff0f789fa16e6cb3adc0006073e241a\\"\\n }\\n}\\n"}');if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("embedded native manifest map is invalid");let t=e[`${process.platform}-${process.arch}`];if(typeof t!="string"||t==="")throw new Error(`embedded native manifest is missing for ${process.platform}-${process.arch}`);return t}return process.platform==="win32",`{
|
|
3
|
+
"version": 1,
|
|
4
|
+
"platform": "linux",
|
|
5
|
+
"arch": "x64",
|
|
6
|
+
"textTransaction": {
|
|
7
|
+
"file": "kodax-text-transaction.node",
|
|
8
|
+
"protocol": 4,
|
|
9
|
+
"sha256": "6cef66472facf03fad1796764f4e7c76c710ec89baafcb12197a7466b0ce7f56"
|
|
10
|
+
},
|
|
11
|
+
"legal": [
|
|
12
|
+
{
|
|
13
|
+
"file": "LICENSE-APACHE.txt",
|
|
14
|
+
"sha256": "6bdadfab6d5d2b0d4e0ccea244f5e412d1597dc84c56db645556ce192b131e98"
|
|
15
|
+
}
|
|
16
|
+
]
|
|
17
|
+
}
|
|
18
|
+
`}a(R,"embeddedNativeManifestText");function x(e){let t=o.resolve(e),r=o.parse(t),n=t.slice(r.root.length).split(o.sep).filter(Boolean),i=n.findIndex(l=>l.toLowerCase()==="app.asar");if(i<0)return t;let s=[...n];s[i]=`${n[i]}.unpacked`;let u=o.join(r.root,...s);return c.existsSync(u)?u:t}a(x,"physicalElectronArtifactPath");function F(e,t=!1){let r=o.dirname(P(e)),n=`win32-${process.arch}`;return[...new Set([o.join(r,"native",n),o.join(r,"..","native",n),o.join(r,"..","dist","native",n),o.join(o.dirname(process.execPath),"vendor","kodax-native",n)].map(i=>{let s=o.resolve(i);return t?x(s):s}))]}a(F,"artifactDirectories");function W(e){let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("manifest root is not an object");return t}a(W,"manifestObject");function D(e){if(e.version!==1||e.platform!=="win32"||e.arch!==process.arch)throw new Error("manifest platform, architecture, or version is incompatible")}a(D,"assertManifestHeader");function L(e,t){let r=e[t];if(typeof r?.file!="string"||o.basename(r.file)!==r.file||!Number.isSafeInteger(r.protocol)||!/^[0-9a-f]{64}$/i.test(r.sha256??""))throw new Error(`manifest ${t} entry is invalid`);return r}a(L,"assertManifestEntry");function H(e){let t=e.asrtRunner;if(t?.file!=="srt-win.exe"||typeof t.version!="string"||t.version===""||!/^[0-9a-f]{64}$/i.test(t.sha256??""))throw new Error("manifest asrtRunner entry is invalid");return t}a(H,"assertManifestAsrtRunner");function q(e){let t=W(e);D(t);for(let r of["textTransaction","shellSandbox"])L(t,r);return H(t),t}a(q,"parseManifestText");function z(e,t){let r=W(e);D(r);let n=L(r,t);return{manifest:r,entry:n}}a(z,"parseManifestEntryText");function h(e,t){let r=process.platform==="win32"?o.win32:o.posix,n=r.relative(r.resolve(e),r.resolve(t));return n===""||!n.startsWith("..")&&!r.isAbsolute(n)}a(h,"sameOrInside");function S(e,t){let r=p(e);if(t.map(p).some(n=>h(n,r)||h(r,n)))throw new Error(`native artifact source overlaps a writable Runtime root: ${e}. Use a production bundle with an embedded native manifest.`)}a(S,"assertDevelopmentSourceIsOutsideWriteRoots");function v(e,t){return e.dev===t.dev&&e.ino===t.ino}a(v,"sameFileIdentity");function _(e,t){let r=c.lstatSync(e),n=a(s=>!s.isFile()||s.isSymbolicLink()||t&&s.nlink!==1||s.size>O,"invalid");if(n(r))throw new Error(`native artifact is not a bounded ordinary file: ${e}`);let i=c.openSync(e,c.constants.O_RDONLY);try{let s=c.fstatSync(i),u=c.lstatSync(e);if(n(s)||n(u)||!v(r,s)||!v(s,u))throw new Error(`native artifact is not a stable bounded ordinary file: ${e}`);let l=Buffer.allocUnsafe(s.size+1),f=0;for(;f<l.byteLength;){let y=c.readSync(i,l,f,l.byteLength-f,null);if(y===0)break;f+=y}let d=c.fstatSync(i);if(f!==s.size||n(d)||!v(s,d))throw new Error(`native artifact changed during bounded read: ${e}`);return l.subarray(0,f)}finally{c.closeSync(i)}}a(_,"readBoundedOrdinaryFile");function M(e,t,r){let n=_(e,r);if(g("sha256").update(n).digest("hex")!==t.toLowerCase())throw new Error(`native artifact hash mismatch: ${e}`);return n}a(M,"readHashPinnedArtifact");function m(e,t){return M(e,t,!0)}a(m,"readVerifiedArtifact");function w(){let e=process.env.LOCALAPPDATA??o.join(X.homedir(),"AppData","Local");return o.join(o.resolve(e),"KodaXNativeArtifactsV3")}a(w,"windowsNativeArtifactCacheRoot");function k(){return o.join(w(),"control-v1")}a(k,"windowsSandboxControlDirectory");function Se(e){let t=p(k()),r=[...e.allowRead,...e.allowWrite].find(i=>{let s=p(i);return h(t,s)||h(s,t)});if(r!==void 0)throw new Error(`Windows policy overlaps protected native shell control state: ${r}`);let n=[...e.denyRead,...e.denyWrite].find(i=>h(t,p(i)));if(n!==void 0)throw new Error(`Windows deny policy targets protected native shell control state: ${n}`)}a(Se,"assertWindowsSandboxControlStateNotDirectlyAccessible");function j(e){let t=p(w()),r=e.find(n=>{let i=p(n);return h(t,i)||h(i,t)});if(r!==void 0)throw new Error(`Windows write policy targets protected native state: ${r}`)}a(j,"assertWindowsNativeArtifactStoreNotDirectlyWritable");function Y(){return o.join(E(),"artifacts-v1")}a(Y,"unixNativeArtifactCacheRoot");function E(){return o.join(o.resolve(A()),"native-text-state-v1")}a(E,"unixTrustedTextStateRoot");function K(){let e=process.geteuid?.();if(e===void 0)throw new Error("Unix trusted text coordination requires an effective user identity");let t=process.platform==="darwin"?"/private/tmp":"/tmp";return o.join(t,`kodax-native-text-coordination-v1-${e}`)}a(K,"unixTrustedTextCoordinationRoot");function Q(){return process.platform==="win32"?[w()]:[E(),K()]}a(Q,"trustedTextNativeArtifactStateRoots");function Z(e){V(e,"write")}a(Z,"assertTrustedTextNativeStateNotDirectlyWritable");function me(e){V(e,"read")}a(me,"assertTrustedTextNativeStateNotDirectlyReadable");function V(e,t){let r=(process.platform==="win32"?Q():[U(),ne()]).map(p),n=e.map(p);for(let i of r){let s=n.find(u=>h(i,u)||h(u,i));if(s!==void 0)throw new Error(`Runtime ${t} policy targets protected native text state: ${s}`)}}a(V,"assertTrustedTextNativeStateNotDirectlyAccessible");function p(e){let t=o.resolve(e),r=[];for(;;){try{c.lstatSync(t)}catch(n){let i=n instanceof Error&&"code"in n?n.code:void 0;if(i!=="ENOENT"&&i!=="ENOTDIR")throw new Error(`Unable to inspect Runtime filesystem policy root: ${e}`,{cause:n});let s=o.dirname(t);if(s===t)throw new Error(`Runtime filesystem policy root has no existing ancestor: ${e}`);r.unshift(o.basename(t)),t=s;continue}try{return o.resolve(c.realpathSync.native(t),...r)}catch(n){throw new Error(`Unable to canonicalize Runtime filesystem policy root: ${e}`,{cause:n})}}}a(p,"canonicalExistingPath");function ee(e,t){let r=o.dirname(P(e)),n=`${process.platform}-${process.arch}`;return[...new Set([o.join(r,"native",n),o.join(r,"..","native",n),o.join(r,"..","dist","native",n),o.join(o.dirname(process.execPath),"vendor","kodax-native",n)].map(i=>{let s=o.resolve(i);return t?x(s):s}))]}a(ee,"portableTextArtifactDirectories");function te(e){let t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("native text manifest root is not an object");let r=t,n=r.textTransaction;if(r.version!==1||r.platform!==process.platform||r.arch!==process.arch||typeof n?.file!="string"||o.basename(n.file)!==n.file||!Number.isSafeInteger(n.protocol)||!/^[0-9a-f]{64}$/i.test(n.sha256??""))throw new Error("native text manifest is incompatible");return r}a(te,"parsePortableTextManifest");function C(e){let t=c.lstatSync(e),r=process.geteuid?.();if(!t.isDirectory()||t.isSymbolicLink()||r!==void 0&&t.uid!==r||(t.mode&63)!==0)throw new Error(`native text state directory is not private and host-owned: ${e}`)}a(C,"assertPrivateUnixDirectory");function re(e){let t=U(),r=o.relative(t,e);if(r.startsWith("..")||o.isAbsolute(r))throw new Error("native text artifact escaped its cache root");let n=t;for(let i of r.split(o.sep).filter(Boolean)){n=o.join(n,i);try{c.mkdirSync(n,{mode:448})}catch(s){if(s.code!=="EEXIST")throw s}C(n)}}a(re,"ensurePrivateUnixDirectory");function U(){let e=o.resolve(A());if(T(e),c.mkdirSync(e,{recursive:!0,mode:448}),T(e),c.realpathSync.native(e)!==e)throw new Error("Agent home must not resolve through a symbolic-link alias");let t=E();try{c.mkdirSync(t,{mode:448})}catch(r){if(r.code!=="EEXIST")throw r}return C(t),c.realpathSync.native(t)}a(U,"ensureUnixTrustedTextStateRoot");function ne(){let e=K();try{c.mkdirSync(e,{mode:448})}catch(t){if(t.code!=="EEXIST")throw t}return C(e),c.realpathSync.native(e)}a(ne,"ensureUnixTrustedTextCoordinationRoot");function T(e){let t=o.resolve(e),r=o.parse(t),n=r.root;for(let i of t.slice(r.root.length).split(o.sep).filter(Boolean)){n=o.join(n,i);try{if(c.lstatSync(n).isSymbolicLink())throw new Error(`Agent home path contains a symbolic-link ancestor: ${n}`)}catch(s){if(s.code==="ENOENT")return;throw s}}}a(T,"assertNoUnixSymlinkAncestor");function oe(e,t){let r=o.join(Y(),`${process.platform}-${process.arch}`,"textTransaction",e.sha256.toLowerCase());re(r);let n=o.join(r,e.file);if(!c.existsSync(n)){let u=o.join(r,`.${process.pid}-${Date.now()}.tmp`),l;try{l=c.openSync(u,c.constants.O_CREAT|c.constants.O_EXCL|c.constants.O_WRONLY|c.constants.O_NOFOLLOW,320);let f=0;for(;f<t.length;){let d=c.writeSync(l,t,f,t.length-f,f);if(d===0)throw new Error("native text artifact write made no progress");f+=d}c.fsyncSync(l),c.closeSync(l),l=void 0;try{c.linkSync(u,n)}catch(d){if(d.code!=="EEXIST")throw d}}finally{l!==void 0&&c.closeSync(l),c.rmSync(u,{force:!0})}}let i=c.lstatSync(n),s=process.geteuid?.();if(!i.isFile()||i.isSymbolicLink()||i.nlink!==1||s!==void 0&&i.uid!==s||(i.mode&511)!==320)throw new Error("protected native text artifact has an unsafe identity or mode");return m(n,e.sha256),c.realpathSync.native(n)}a(oe,"provisionUnixTextArtifact");function Ae(e,t,r){if(Z(r),process.platform==="win32")return le(e,"textTransaction",t,{untrustedWriteRoots:r}).path;if(process.platform!=="linux"&&process.platform!=="darwin")throw new Error(`Trusted text transactions are unavailable on ${process.platform}.`);let n=R(),i=[];for(let s of ee(e,n!==void 0)){let u=o.join(s,"manifest.json");try{S(s,r);let l=te(n??c.readFileSync(u,"utf8"));if(l.textTransaction.protocol!==t)throw new Error(`textTransaction protocol ${l.textTransaction.protocol} does not match ${t}`);let f=o.join(s,l.textTransaction.file),d=m(f,l.textTransaction.sha256);return oe(l.textTransaction,d)}catch(l){i.push(`${u}: ${l instanceof Error?l.message:String(l)}`)}}throw new Error(`A compatible KodaX text transaction artifact is unavailable. ${i.join(" | ")}`)}a(Ae,"resolveTrustedTextNativeArtifact");function ie(e,t,r,n=!1){let i=n?"local-users":r===void 0?"host-only":`sandbox-${g("sha256").update(r.toUpperCase()).digest("hex").slice(0,16)}`;return o.join(w(),B,`win32-${process.arch}`,e,i,t.toLowerCase())}a(ie,"protectedArtifactDirectory");var se=String.raw`
|
|
19
|
+
$ErrorActionPreference = 'Stop'
|
|
20
|
+
$payloadText = [Console]::In.ReadToEnd()
|
|
21
|
+
if ([Text.Encoding]::UTF8.GetByteCount($payloadText) -gt 90000000) { throw 'payload exceeds bound' }
|
|
22
|
+
$payload = $payloadText | ConvertFrom-Json
|
|
23
|
+
$hostSid = [Security.Principal.WindowsIdentity]::GetCurrent().User
|
|
24
|
+
$systemSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
|
|
25
|
+
$usersSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-545')
|
|
26
|
+
$sandboxSid = if ([string]::IsNullOrEmpty([string]$payload.sandboxReadSid)) { $null } else { [Security.Principal.SecurityIdentifier]::new([string]$payload.sandboxReadSid) }
|
|
27
|
+
$localUsersReadExecute = [bool]$payload.localUsersReadExecute
|
|
28
|
+
$inherit = [Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit
|
|
29
|
+
$none = [Security.AccessControl.PropagationFlags]::None
|
|
30
|
+
$allow = [Security.AccessControl.AccessControlType]::Allow
|
|
31
|
+
function New-DirectorySecurity {
|
|
32
|
+
$security = [Security.AccessControl.DirectorySecurity]::new()
|
|
33
|
+
$security.SetAccessRuleProtection($true, $false)
|
|
34
|
+
$security.SetOwner($hostSid)
|
|
35
|
+
[void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($hostSid, [Security.AccessControl.FileSystemRights]::FullControl, $inherit, $none, $allow))
|
|
36
|
+
[void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($systemSid, [Security.AccessControl.FileSystemRights]::FullControl, $inherit, $none, $allow))
|
|
37
|
+
[void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($usersSid, [Security.AccessControl.FileSystemRights]::ReadAndExecute, $inherit, $none, $allow))
|
|
38
|
+
return $security
|
|
39
|
+
}
|
|
40
|
+
function New-FileSecurity {
|
|
41
|
+
$security = [Security.AccessControl.FileSecurity]::new()
|
|
42
|
+
$security.SetAccessRuleProtection($true, $false)
|
|
43
|
+
$security.SetOwner($hostSid)
|
|
44
|
+
[void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($hostSid, [Security.AccessControl.FileSystemRights]::FullControl, $allow))
|
|
45
|
+
[void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($systemSid, [Security.AccessControl.FileSystemRights]::FullControl, $allow))
|
|
46
|
+
if ($localUsersReadExecute) { [void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($usersSid, [Security.AccessControl.FileSystemRights]::ReadAndExecute, $allow)) }
|
|
47
|
+
elseif ($null -ne $sandboxSid) { [void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sandboxSid, [Security.AccessControl.FileSystemRights]::ReadAndExecute, $allow)) }
|
|
48
|
+
return $security
|
|
49
|
+
}
|
|
50
|
+
function Assert-NoReparse([string]$candidate) {
|
|
51
|
+
$item = Get-Item -LiteralPath $candidate -Force
|
|
52
|
+
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw "reparse artifact path: $candidate" }
|
|
53
|
+
}
|
|
54
|
+
function Assert-AclShape($acl, [bool]$directory, [string]$candidate) {
|
|
55
|
+
if (-not $acl.AreAccessRulesProtected -or $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $hostSid.Value) { throw 'artifact ACL is not protected and host-owned' }
|
|
56
|
+
$expected = @{}
|
|
57
|
+
$expected[$hostSid.Value] = [int][Security.AccessControl.FileSystemRights]::FullControl
|
|
58
|
+
$expected[$systemSid.Value] = [int][Security.AccessControl.FileSystemRights]::FullControl
|
|
59
|
+
$readExecuteMask = [int]([Security.AccessControl.FileSystemRights]::ReadAndExecute -bor [Security.AccessControl.FileSystemRights]::Synchronize)
|
|
60
|
+
if ($directory) { $expected[$usersSid.Value] = $readExecuteMask }
|
|
61
|
+
if (-not $directory -and $localUsersReadExecute) { $expected[$usersSid.Value] = $readExecuteMask }
|
|
62
|
+
elseif (-not $directory -and $null -ne $sandboxSid) { $expected[$sandboxSid.Value] = $readExecuteMask }
|
|
63
|
+
$observed = @{}
|
|
64
|
+
foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {
|
|
65
|
+
if ($rule.IsInherited) { throw 'artifact ACL contains an inherited rule' }
|
|
66
|
+
# Native v2 appends execution-specific DENY ACEs to deny-write roots. A
|
|
67
|
+
# DENY cannot widen access, so it is safe to retain while the exact ALLOW
|
|
68
|
+
# surface below remains closed and fully verified.
|
|
69
|
+
if ($rule.AccessControlType -eq [Security.AccessControl.AccessControlType]::Deny) { continue }
|
|
70
|
+
$sid = $rule.IdentityReference.Value
|
|
71
|
+
if (-not $expected.ContainsKey($sid) -or $observed.ContainsKey($sid)) { throw "artifact ACL contains an unexpected allow rule for $sid at $candidate" }
|
|
72
|
+
if ([int]$rule.FileSystemRights -ne $expected[$sid]) { throw "artifact ACL allow mask is invalid for $sid at $candidate" }
|
|
73
|
+
if ($directory) {
|
|
74
|
+
if ($rule.InheritanceFlags -ne $inherit -or $rule.PropagationFlags -ne $none) { throw 'artifact directory ACL inheritance is invalid' }
|
|
75
|
+
} elseif ($rule.InheritanceFlags -ne [Security.AccessControl.InheritanceFlags]::None) {
|
|
76
|
+
throw 'artifact file ACL inheritance is invalid'
|
|
77
|
+
}
|
|
78
|
+
$observed[$sid] = $true
|
|
79
|
+
}
|
|
80
|
+
foreach ($sid in $expected.Keys) { if (-not $observed.ContainsKey($sid)) { throw 'artifact ACL is missing a required allow rule' } }
|
|
81
|
+
}
|
|
82
|
+
function Ensure-ProtectedDirectory([string]$candidate) {
|
|
83
|
+
if (Test-Path -LiteralPath $candidate) {
|
|
84
|
+
Assert-NoReparse $candidate
|
|
85
|
+
Assert-AclShape ([IO.Directory]::GetAccessControl($candidate)) $true $candidate
|
|
86
|
+
return
|
|
87
|
+
}
|
|
88
|
+
[void][IO.Directory]::CreateDirectory($candidate, (New-DirectorySecurity))
|
|
89
|
+
Assert-NoReparse $candidate
|
|
90
|
+
Assert-AclShape ([IO.Directory]::GetAccessControl($candidate)) $true $candidate
|
|
91
|
+
}
|
|
92
|
+
$cacheRoot = [IO.Path]::GetFullPath([string]$payload.cacheRoot)
|
|
93
|
+
$anchor = [IO.Path]::GetFullPath([string]$payload.anchor)
|
|
94
|
+
$destinationDirectory = [IO.Path]::GetFullPath([string]$payload.destinationDirectory)
|
|
95
|
+
if (-not $cacheRoot.StartsWith($anchor + [IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase)) { throw 'cache root escaped host LocalAppData' }
|
|
96
|
+
if (-not $destinationDirectory.StartsWith($cacheRoot + [IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase)) { throw 'destination escaped cache root' }
|
|
97
|
+
Assert-NoReparse $anchor
|
|
98
|
+
$current = $anchor
|
|
99
|
+
$relative = $destinationDirectory.Substring($anchor.Length).TrimStart([IO.Path]::DirectorySeparatorChar)
|
|
100
|
+
foreach ($part in ($relative -split '[\\/]')) {
|
|
101
|
+
if ([string]::IsNullOrEmpty($part)) { continue }
|
|
102
|
+
$current = [IO.Path]::Combine($current, $part)
|
|
103
|
+
Ensure-ProtectedDirectory $current
|
|
104
|
+
}
|
|
105
|
+
$bytes = [Convert]::FromBase64String([string]$payload.bytes)
|
|
106
|
+
$hash = [Security.Cryptography.SHA256]::Create()
|
|
107
|
+
try { $actual = ([BitConverter]::ToString($hash.ComputeHash($bytes))).Replace('-', '').ToLowerInvariant() } finally { $hash.Dispose() }
|
|
108
|
+
if ($actual -ne ([string]$payload.sha256).ToLowerInvariant()) { throw 'provisioning payload hash mismatch' }
|
|
109
|
+
$destination = [IO.Path]::Combine($destinationDirectory, [string]$payload.file)
|
|
110
|
+
# Keep the CreateNew staging name short. PowerShell 5.1 FileStream still hits
|
|
111
|
+
# MAX_PATH on otherwise valid LocalAppData roots before long-path policy is
|
|
112
|
+
# enabled, while GetRandomFileName retains cross-process collision resistance.
|
|
113
|
+
$temporary = [IO.Path]::Combine($destinationDirectory, '.' + [IO.Path]::GetRandomFileName() + '.tmp')
|
|
114
|
+
try {
|
|
115
|
+
if (-not (Test-Path -LiteralPath $destination)) {
|
|
116
|
+
$stream = [IO.FileStream]::new($temporary, [IO.FileMode]::CreateNew, [Security.AccessControl.FileSystemRights]::FullControl, [IO.FileShare]::None, 65536, [IO.FileOptions]::WriteThrough, (New-FileSecurity))
|
|
117
|
+
try { $stream.Write($bytes, 0, $bytes.Length); $stream.Flush($true) } finally { $stream.Dispose() }
|
|
118
|
+
try { [IO.File]::Move($temporary, $destination) } catch { if (-not (Test-Path -LiteralPath $destination)) { throw } }
|
|
119
|
+
}
|
|
120
|
+
Assert-NoReparse $destination
|
|
121
|
+
Assert-AclShape ([IO.File]::GetAccessControl($destination)) $false $destination
|
|
122
|
+
# A sibling Runtime may already be executing this content-addressed image.
|
|
123
|
+
# Verification must share an immutable published file for read/delete or
|
|
124
|
+
# artifact provisioning itself becomes a cross-Runtime admission lock.
|
|
125
|
+
$share = [IO.FileShare]::Read -bor [IO.FileShare]::Delete
|
|
126
|
+
$stream = [IO.FileStream]::new($destination, [IO.FileMode]::Open, [IO.FileAccess]::Read, $share)
|
|
127
|
+
try {
|
|
128
|
+
$publishedHasher = [Security.Cryptography.SHA256]::Create()
|
|
129
|
+
try { $publishedHash = ([BitConverter]::ToString($publishedHasher.ComputeHash($stream))).Replace('-', '').ToLowerInvariant() } finally { $publishedHasher.Dispose() }
|
|
130
|
+
} finally { $stream.Dispose() }
|
|
131
|
+
if ($publishedHash -ne $actual) { throw 'published artifact hash mismatch' }
|
|
132
|
+
[Console]::Out.Write($destination)
|
|
133
|
+
} finally {
|
|
134
|
+
if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary -Force }
|
|
135
|
+
}
|
|
136
|
+
`,ae=String.raw`
|
|
137
|
+
$ErrorActionPreference = 'Stop'
|
|
138
|
+
$payload = ([Console]::In.ReadToEnd() | ConvertFrom-Json)
|
|
139
|
+
$hostSid = [Security.Principal.WindowsIdentity]::GetCurrent().User
|
|
140
|
+
$systemSid = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
|
|
141
|
+
$inherit = [Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit
|
|
142
|
+
$none = [Security.AccessControl.PropagationFlags]::None
|
|
143
|
+
$allow = [Security.AccessControl.AccessControlType]::Allow
|
|
144
|
+
function Assert-NoReparse([string]$candidate) {
|
|
145
|
+
$item = Get-Item -LiteralPath $candidate -Force
|
|
146
|
+
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw "reparse control path: $candidate" }
|
|
147
|
+
}
|
|
148
|
+
function New-ControlSecurity {
|
|
149
|
+
$security = [Security.AccessControl.DirectorySecurity]::new()
|
|
150
|
+
$security.SetAccessRuleProtection($true, $false)
|
|
151
|
+
$security.SetOwner($hostSid)
|
|
152
|
+
[void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($hostSid, [Security.AccessControl.FileSystemRights]::FullControl, $inherit, $none, $allow))
|
|
153
|
+
[void]$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($systemSid, [Security.AccessControl.FileSystemRights]::FullControl, $inherit, $none, $allow))
|
|
154
|
+
return $security
|
|
155
|
+
}
|
|
156
|
+
function Assert-ControlSecurity([string]$candidate) {
|
|
157
|
+
$acl = [IO.Directory]::GetAccessControl($candidate)
|
|
158
|
+
if (-not $acl.AreAccessRulesProtected -or $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $hostSid.Value) {
|
|
159
|
+
throw 'control directory ACL is not protected and host-owned'
|
|
160
|
+
}
|
|
161
|
+
$expected = @{}
|
|
162
|
+
$expected[$hostSid.Value] = $true
|
|
163
|
+
$expected[$systemSid.Value] = $true
|
|
164
|
+
$observed = @{}
|
|
165
|
+
foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {
|
|
166
|
+
if ($rule.IsInherited -or $rule.AccessControlType -ne $allow) { throw 'control directory ACL contains an unexpected rule' }
|
|
167
|
+
$sid = $rule.IdentityReference.Value
|
|
168
|
+
if (-not $expected.ContainsKey($sid) -or $observed.ContainsKey($sid)) { throw 'control directory ACL contains an unexpected principal' }
|
|
169
|
+
if ($rule.FileSystemRights -ne [Security.AccessControl.FileSystemRights]::FullControl -or $rule.InheritanceFlags -ne $inherit -or $rule.PropagationFlags -ne $none) {
|
|
170
|
+
throw 'control directory ACL rule shape is invalid'
|
|
171
|
+
}
|
|
172
|
+
$observed[$sid] = $true
|
|
173
|
+
}
|
|
174
|
+
foreach ($sid in $expected.Keys) { if (-not $observed.ContainsKey($sid)) { throw 'control directory ACL is missing a required principal' } }
|
|
175
|
+
}
|
|
176
|
+
function Test-ControlOwnerProcessAlive([uint32]$processId) {
|
|
177
|
+
if ($processId -gt [int]::MaxValue) { return $false }
|
|
178
|
+
try {
|
|
179
|
+
return $null -ne [Diagnostics.Process]::GetProcessById([int]$processId)
|
|
180
|
+
} catch [ArgumentException] {
|
|
181
|
+
return $false
|
|
182
|
+
} catch {
|
|
183
|
+
return $true
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
function Remove-ProvenStaleControlEntries([string]$candidate) {
|
|
187
|
+
$now = [DateTimeOffset]::UtcNow
|
|
188
|
+
foreach ($entry in [IO.Directory]::EnumerateFiles($candidate)) {
|
|
189
|
+
$item = Get-Item -LiteralPath $entry -Force
|
|
190
|
+
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 -or $item.Length -gt 1048576) { continue }
|
|
191
|
+
$match = [regex]::Match($item.Name, '^windows-(shell|network|terminal)-([0-9]+)-[0-9a-fA-F-]{36}\.json$')
|
|
192
|
+
if (-not $match.Success) { continue }
|
|
193
|
+
$ownerPid = 0L
|
|
194
|
+
if (-not [long]::TryParse($match.Groups[2].Value, [ref]$ownerPid) -or $ownerPid -le 0 -or $ownerPid -gt [uint32]::MaxValue) { continue }
|
|
195
|
+
if (Test-ControlOwnerProcessAlive ([uint32]$ownerPid)) { continue }
|
|
196
|
+
$kind = $match.Groups[1].Value
|
|
197
|
+
$retire = $false
|
|
198
|
+
if ($kind -eq 'network') {
|
|
199
|
+
# A network request is deleted as soon as its broker reads it. A dead
|
|
200
|
+
# creator plus two launch budgets proves this file was never admitted.
|
|
201
|
+
$retire = $item.LastWriteTimeUtc -lt $now.UtcDateTime.AddMinutes(-1)
|
|
202
|
+
} else {
|
|
203
|
+
try { $record = ([IO.File]::ReadAllText($entry) | ConvertFrom-Json) } catch { continue }
|
|
204
|
+
if ($kind -eq 'shell') {
|
|
205
|
+
$deadline = 0L
|
|
206
|
+
$retire = [long]::TryParse([string]$record.operationDeadlineUnixMs, [ref]$deadline) -and $deadline -lt $now.ToUnixTimeMilliseconds()
|
|
207
|
+
} else {
|
|
208
|
+
# A terminal record is disposable only after native Job drainage was
|
|
209
|
+
# durably observed. Unknown or partial records remain fail-closed.
|
|
210
|
+
$retire = $record.jobDrained -eq $true
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if ($retire) { [IO.File]::Delete($entry) }
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
$cacheRoot = [IO.Path]::GetFullPath([string]$payload.cacheRoot)
|
|
217
|
+
$controlRoot = [IO.Path]::GetFullPath([string]$payload.controlRoot)
|
|
218
|
+
$action = [string]$payload.action
|
|
219
|
+
if ([IO.Path]::GetDirectoryName($controlRoot) -ne $cacheRoot) { throw 'control directory escaped native cache root' }
|
|
220
|
+
if (-not (Test-Path -LiteralPath $cacheRoot -PathType Container)) { throw 'protected native cache root is unavailable' }
|
|
221
|
+
Assert-NoReparse $cacheRoot
|
|
222
|
+
if ($action -eq 'verify') {
|
|
223
|
+
if (-not (Test-Path -LiteralPath $controlRoot -PathType Container)) { throw 'protected native shell control state is not initialized; run kodax sandbox setup' }
|
|
224
|
+
Assert-NoReparse $controlRoot
|
|
225
|
+
} elseif ($action -eq 'ensure') {
|
|
226
|
+
if (Test-Path -LiteralPath $controlRoot) {
|
|
227
|
+
Assert-NoReparse $controlRoot
|
|
228
|
+
} else {
|
|
229
|
+
[void][IO.Directory]::CreateDirectory($controlRoot, (New-ControlSecurity))
|
|
230
|
+
Assert-NoReparse $controlRoot
|
|
231
|
+
}
|
|
232
|
+
} elseif ($action -eq 'repair') {
|
|
233
|
+
if (Test-Path -LiteralPath $controlRoot) {
|
|
234
|
+
Assert-NoReparse $controlRoot
|
|
235
|
+
$existing = [IO.Directory]::GetAccessControl($controlRoot)
|
|
236
|
+
if ($existing.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $hostSid.Value) { throw 'refusing to repair native shell control state not owned by the host' }
|
|
237
|
+
Remove-ProvenStaleControlEntries $controlRoot
|
|
238
|
+
$entries = [IO.Directory]::EnumerateFileSystemEntries($controlRoot).GetEnumerator()
|
|
239
|
+
try { $notEmpty = $entries.MoveNext() } finally { $entries.Dispose() }
|
|
240
|
+
if ($notEmpty) { throw 'refusing to repair non-empty native shell control state; close KodaX and remove the directory manually' }
|
|
241
|
+
[IO.Directory]::SetAccessControl($controlRoot, (New-ControlSecurity))
|
|
242
|
+
} else {
|
|
243
|
+
[void][IO.Directory]::CreateDirectory($controlRoot, (New-ControlSecurity))
|
|
244
|
+
}
|
|
245
|
+
Assert-NoReparse $controlRoot
|
|
246
|
+
} else {
|
|
247
|
+
throw 'invalid native shell control state action'
|
|
248
|
+
}
|
|
249
|
+
Assert-ControlSecurity $controlRoot
|
|
250
|
+
[Console]::Out.Write($controlRoot)
|
|
251
|
+
`;function b(e){if(process.platform!=="win32")throw new Error("KodaX Windows native shell control state is unavailable on this platform.");let t=w(),r=k(),n=o.join(process.env.SystemRoot??String.raw`C:\Windows`,"System32","WindowsPowerShell","v1.0","powershell.exe"),i=I(n,["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(ae,"utf16le").toString("base64")],{input:JSON.stringify({action:e,cacheRoot:t,controlRoot:r}),encoding:"utf8",env:process.env,shell:!1,windowsHide:!0,timeout:3e4,maxBuffer:1024*1024});if(i.error!==void 0||i.status!==0){let l=i.error?.message??(i.stderr.trim()||`exit ${String(i.status)}`);throw new Error(`Cannot ${e} protected KodaX native shell control state: ${l}`)}if(i.stdout.trim().toLowerCase()!==r.toLowerCase())throw new Error("Native shell control verifier returned an unexpected path.");let s=c.realpathSync.native(t),u=c.realpathSync.native(r);if(!h(s,u))throw new Error("Native shell control state escaped its physical cache root.");return u}a(b,"runWindowsSandboxControlDirectoryAction");function ve(){return b("verify")}a(ve,"verifyWindowsSandboxControlDirectory");function ge(){return b("ensure")}a(ge,"ensureWindowsSandboxControlDirectory");function Re(){return b("repair")}a(Re,"repairWindowsSandboxControlDirectory");function G(e){if(e.sandboxReadSid!==void 0&&!/^S-\d+(?:-\d+)+$/i.test(e.sandboxReadSid))throw new Error("Native artifact sandbox-read SID is invalid.");let t=w(),r=o.dirname(t),n=ie(e.kind,e.entry.sha256,e.sandboxReadSid,e.localUsersReadExecute===!0),i=o.join(process.env.SystemRoot??String.raw`C:\Windows`,"System32","WindowsPowerShell","v1.0","powershell.exe"),s=I(i,["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(se,"utf16le").toString("base64")],{input:JSON.stringify({cacheRoot:t,anchor:r,destinationDirectory:n,file:e.entry.file,sha256:e.entry.sha256,bytes:e.bytes.toString("base64"),sandboxReadSid:e.sandboxReadSid??"",localUsersReadExecute:e.localUsersReadExecute===!0}),encoding:"utf8",env:process.env,shell:!1,windowsHide:!0,timeout:3e4,maxBuffer:1024*1024});if(s.error!==void 0||s.status!==0){let y=s.error?.message??(s.stderr.trim()||`exit ${String(s.status)}`);throw new Error(`Cannot provision protected KodaX native artifact: ${y}`)}let u=s.stdout.trim(),l=o.join(n,e.entry.file);if(u.toLowerCase()!==l.toLowerCase())throw new Error("Native artifact provisioner returned an unexpected path.");m(u,e.entry.sha256);let f=c.realpathSync.native(t),d=c.realpathSync.native(u);if(!h(f,d))throw new Error("Protected native artifact escaped its physical cache root.");return d}a(G,"provisionProtectedArtifact");function ce(e,t){if(process.platform!=="win32")throw new Error("The protected ASRT Windows runner is unavailable on this platform.");if(e.byteLength===0||e.byteLength>O)throw new Error("The ASRT Windows runner has an invalid size.");if(!/^[0-9a-f]{64}$/i.test(t))throw new Error("The ASRT Windows runner trusted digest is invalid.");let r=g("sha256").update(e).digest("hex");if(r!==t.toLowerCase())throw new Error("The ASRT Windows runner does not match its trusted release digest.");return{path:G({kind:"asrtRunner",entry:{file:"srt-win.exe",sha256:r},bytes:e,localUsersReadExecute:!0}),sha256:r}}a(ce,"provisionWindowsAsrtRunner");function xe(e,t,r,n={}){if(process.platform!=="win32")throw new Error("The protected ASRT Windows runner is unavailable on this platform.");j(n.untrustedWriteRoots??[]);let i=R(),s=i===void 0?o.resolve(t):x(t),u=o.dirname(s),l=i===void 0?F(e).map(d=>({manifestPath:o.join(d,"manifest.json"),manifestText:void 0,developmentTrustRoots:[d,u]})):[{manifestPath:"<embedded native manifest>",manifestText:i,developmentTrustRoots:[]}],f=[];for(let d of l)try{for(let J of d.developmentTrustRoots)S(J,n.untrustedWriteRoots??[]);let y=d.manifestText!==void 0,$=q(d.manifestText??_(d.manifestPath,!0).toString("utf8"));if($.asrtRunner.version!==r)throw new Error(`asrtRunner version ${$.asrtRunner.version} does not match ${r}`);let N=M(s,$.asrtRunner.sha256,!y);return{...ce(N,$.asrtRunner.sha256),developmentTrustRoots:d.developmentTrustRoots}}catch(y){f.push(`${d.manifestPath}: ${y instanceof Error?y.message:String(y)}`)}throw new Error(`A trusted ASRT Windows runner is unavailable. ${f.join(" | ")}`)}a(xe,"resolveWindowsAsrtRunnerArtifact");function Ee(e,t){for(let r of e)S(r,t)}a(Ee,"assertWindowsAsrtRunnerTrustOutsideWriteRoots");function le(e,t,r,n={}){if(process.platform!=="win32")throw new Error("KodaX Windows native artifacts are unavailable on this platform.");j(n.untrustedWriteRoots??[]);let i=R(),s=[];for(let u of F(e,i!==void 0)){let l=o.join(u,"manifest.json");try{S(u,n.untrustedWriteRoots??[]);let{manifest:f,entry:d}=z(i??c.readFileSync(l,"utf8"),t);if(d.protocol!==r)throw new Error(`${t} protocol ${d.protocol} does not match ${r}`);let y=o.join(u,d.file),$=m(y,d.sha256);return{path:G({kind:t,entry:d,bytes:$,...n.sandboxReadSid===void 0?{}:{sandboxReadSid:n.sandboxReadSid}}),entry:d,manifest:f}}catch(f){s.push(`${l}: ${f instanceof Error?f.message:String(f)}`)}}throw new Error(`A compatible KodaX ${t} native artifact is unavailable. ${s.join(" | ")}`)}a(le,"resolveWindowsNativeArtifact");export{w as a,k as b,Se as c,j as d,Q as e,Z as f,me as g,ne as h,Ae as i,ve as j,ge as k,Re as l,xe as m,Ee as n,le as o};
|