@kodax-ai/kodax 0.7.60 → 0.7.62

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 (50) hide show
  1. package/CHANGELOG.md +82 -2
  2. package/README.md +2 -0
  3. package/README_CN.md +2 -0
  4. package/dist/chunks/{agent-L5FC3YOY.js → agent-4ZMCIEGD.js} +1 -1
  5. package/dist/chunks/argument-completer-5PWSKFKI.js +2 -0
  6. package/dist/chunks/{chunk-5TRQBMPR.js → chunk-2F4R7WM7.js} +1 -1
  7. package/dist/chunks/chunk-3KD26NCI.js +310 -0
  8. package/dist/chunks/chunk-6HTR3GHZ.js +624 -0
  9. package/dist/chunks/{chunk-XULI4U7I.js → chunk-AY3BLB4Q.js} +96 -96
  10. package/dist/chunks/chunk-E2Q4RIOD.js +731 -0
  11. package/dist/chunks/{chunk-SGNM3UP6.js → chunk-HO6P6CPU.js} +1 -1
  12. package/dist/chunks/{chunk-2RLIKZOZ.js → chunk-JILSZHCQ.js} +2 -2
  13. package/dist/chunks/chunk-OGRJQGKO.js +19 -0
  14. package/dist/chunks/{chunk-QFCF3GNT.js → chunk-S4ISEA6F.js} +171 -156
  15. package/dist/chunks/chunk-WFE6FBQ2.js +326 -0
  16. package/dist/chunks/{compaction-config-E4LN3M53.js → compaction-config-SP3REMFR.js} +1 -1
  17. package/dist/chunks/{construction-bootstrap-GIFDM4L5.js → construction-bootstrap-4ZNFZFX2.js} +3 -3
  18. package/dist/chunks/{dist-7PXDYX2R.js → dist-IKWRJW6J.js} +1 -1
  19. package/dist/chunks/host-XL5CH7QP.js +2 -0
  20. package/dist/chunks/{run-manager-IU5COC6X.js → run-manager-UXIPDVVF.js} +1 -1
  21. package/dist/chunks/{utils-NP42DKL3.js → utils-XKWEVPE3.js} +1 -1
  22. package/dist/index.d.ts +7 -7
  23. package/dist/index.js +1 -1
  24. package/dist/kodax_cli.js +1021 -970
  25. package/dist/sdk-agent.d.ts +67 -8
  26. package/dist/sdk-agent.js +1 -1
  27. package/dist/sdk-coding.d.ts +15 -13
  28. package/dist/sdk-coding.js +1 -1
  29. package/dist/sdk-mcp.js +1 -1
  30. package/dist/sdk-repl.d.ts +9 -9
  31. package/dist/sdk-repl.js +1 -1
  32. package/dist/sdk-session.d.ts +4 -4
  33. package/dist/sdk-session.js +1 -1
  34. package/dist/sdk-skills.js +1 -1
  35. package/dist/types-chunks/{bash-prefix-extractor.d-Ds1THKeH.d.ts → bash-prefix-extractor.d-Do_TCAmA.d.ts} +19 -9
  36. package/dist/types-chunks/{guardrail.d-CdqJwwN7.d.ts → guardrail.d-DRp0Lqvx.d.ts} +2 -2
  37. package/dist/types-chunks/{process.d-C93UMgPK.d.ts → process.d-DXkRD7hj.d.ts} +265 -13
  38. package/dist/types-chunks/{run-manager.d-DLK3ed-T.d.ts → run-manager.d-CYY3pZeJ.d.ts} +18 -4
  39. package/dist/types-chunks/{sdk-session-CtwN7iBO.d.ts → sdk-session-BGGOC0cT.d.ts} +3 -3
  40. package/dist/types-chunks/{storage.d-DlZS0g8w.d.ts → storage.d-C3umBC4g.d.ts} +2 -2
  41. package/dist/types-chunks/{types.d-CSZAMmU-.d.ts → types.d-DFf4Sfys.d.ts} +1 -1
  42. package/dist/types-chunks/{utils.d-Boz9k2HB.d.ts → utils.d-ChOEH3NF.d.ts} +4 -4
  43. package/package.json +1 -1
  44. package/dist/chunks/argument-completer-BQDAYT7W.js +0 -2
  45. package/dist/chunks/chunk-4K5BDO7S.js +0 -721
  46. package/dist/chunks/chunk-6DWXUZMO.js +0 -600
  47. package/dist/chunks/chunk-IJN6ZJVI.js +0 -310
  48. package/dist/chunks/chunk-U6BNMGSK.js +0 -17
  49. package/dist/chunks/chunk-ZPD7IUKW.js +0 -322
  50. package/dist/chunks/host-FLG7FJZT.js +0 -2
@@ -1,2 +1,2 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{wa as e}from"./chunk-4K5BDO7S.js";import{a as n}from"./chunk-V4WSBIXB.js";import{readFile as i}from"fs/promises";var c={enabled:!0,triggerPercent:75};async function g(o){let t=e("config.json");try{let r=await a(t);if(r?.compaction)return{...c,...r.compaction}}catch{}return c}n(g,"loadCompactionConfig");async function a(o){try{let t=await i(o,"utf-8");return JSON.parse(t)}catch{return null}}n(a,"readConfigFile");export{g as a};
2
+ import{wa as e}from"./chunk-E2Q4RIOD.js";import{a as n}from"./chunk-V4WSBIXB.js";import{readFile as i}from"fs/promises";var c={enabled:!0,triggerPercent:75};async function g(o){let t=e("config.json");try{let r=await a(t);if(r?.compaction)return{...c,...r.compaction}}catch{}return c}n(g,"loadCompactionConfig");async function a(o){try{let t=await i(o,"utf-8");return JSON.parse(t)}catch{return null}}n(a,"readConfigFile");export{g as a};
@@ -1,5 +1,5 @@
1
1
  // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Ab as Te,Bb as X,Cb as Ee,Db as Ae,Fa as We,Jc as Pe,Kc as Oe}from"./chunk-QFCF3GNT.js";import{N as ge}from"./chunk-S4GVQO3W.js";import{Va as G,Zd as ve,_d as Se,ae as F,ce as z,db as ye,ie as J,je as W,ke as H,le as xe,se as Me,te as Re,ue as be}from"./chunk-4K5BDO7S.js";import{B as ke}from"./chunk-ZL5CEANW.js";import{a}from"./chunk-V4WSBIXB.js";import{basename as bn,dirname as Wn}from"node:path";import{execFile as yt}from"node:child_process";import j from"node:path";import{promisify as vt}from"node:util";var St=vt(yt),xt=1e4,De=2,Fe=new Set(["write","edit","multi_edit","insert_after_anchor"]),Mt=/^\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 Rt(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)}}a(Rt,"normalizeWaitTimeoutMs");function Y(e){return e?.requiresMutation===!0||(e?.requiredChangedPaths?.length??0)>0}a(Y,"hasVerificationWork");function T(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").trim()}a(T,"normalizeWorkspacePath");function bt(e,t){let n=t.gitRoot?j.resolve(t.gitRoot):void 0,o=j.isAbsolute(e)&&n?j.relative(n,j.resolve(e)):e;return T(o)}a(bt,"normalizeRequiredPath");function Wt(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"},o=e.verification.requiredChangedPaths;return{verification:{...n,...o!==void 0&&o.length>0&&n.requiresMutation===void 0?{requiresMutation:!0}:{}}}}return{verification:t}}a(Wt,"resolveVerificationForInput");function Tt(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}}a(Tt,"resolveSpawnAgentInput");function _e(e){let t=e.trim();return t.length>0&&Mt.test(t)}a(_e,"isPreparatoryOnlyText");function Et(e,t){let n=e.trim(),o=t?.trim();return o&&(n.length===0||_e(n))?o:e}a(Et,"selectWorkflowFinalText");async function B(e,t){return(await St("git",[...e],{cwd:t,timeout:xt,windowsHide:!0,maxBuffer:4194304})).stdout.toString()}a(B,"runGit");async function At(e){let t=e.gitRoot??e.executionCwd??process.cwd(),n=(await B(["rev-parse","--show-toplevel"],t)).trim(),o=await Promise.all([B(["diff","--name-only","--"],n),B(["diff","--cached","--name-only","--"],n),B(["ls-files","--others","--exclude-standard"],n)]);return[...new Set(o.flatMap(i=>i.split(/\r?\n/)).map(T).filter(i=>i.length>0))]}a(At,"listGitChangedFiles");async function Z(e,t){try{return{paths:(await t(e)).map(T).filter(o=>o.length>0)}}catch(n){return{paths:[],error:n instanceof Error?n.message:String(n)}}}a(Z,"captureChangedPaths");function Pt(){return{toolNameById:new Map,toolPathById:new Map,succeededToolCalls:[],succeededPaths:[]}}a(Pt,"createMutationRecorder");function Ot(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 T(n)}}a(Ot,"readMutationPath");function Ft(e,t){return{...e??{},onToolUseStart:a((n,o)=>{if(Fe.has(n.name)){t.toolNameById.set(n.id,n.name);let i=Ot(n.input);i!==void 0&&t.toolPathById.set(n.id,i)}e?.onToolUseStart?.(n,o)},"onToolUseStart"),onToolResult:a((n,o)=>{let i=t.toolNameById.get(n.id)??n.name;if(Fe.has(i)&&!n.content.trimStart().startsWith("[Tool Error]")){t.succeededToolCalls.push(i);let r=t.toolPathById.get(n.id);r!==void 0&&t.succeededPaths.push(r)}e?.onToolResult?.(n,o)},"onToolResult")}}a(Ft,"wrapEventsForMutationRecording");function Q(e){return[...new Set(e.filter(t=>t.trim().length>0))]}a(Q,"uniqueItems");function Ie(e){let t=e.verification;if(!t)return;let n=[],o=new Set(e.before.paths.map(T)),i=Q(e.after.paths.map(T)),r=i.filter(m=>!o.has(m)),s=Q(e.mutationRecorder.succeededToolCalls),c=e.acceptToolMutationEvidence?s:[],p=e.acceptToolMutationEvidence?Q(e.mutationRecorder.succeededPaths.map(T)):[],l=r.length>0||c.length>0,h=t.enforcement??"hard",v=(t.requiredChangedPaths??[]).map(m=>bt(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}`):l||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&&!l&&n.push("workflow child reached its iteration limit before satisfying the task");for(let m of v)!i.includes(m)&&!p.includes(m)&&n.push(`required changed path was not present in workspace changes: ${m}`);let k=t.minFinalTextChars;return k!==void 0&&!l&&e.term.finalText.trim().length<k&&n.push(`finalText was shorter than the required ${k} characters`),t.rejectPreparatoryFinalText===!0&&!l&&_e(e.term.finalText)&&n.push("finalText looks preparatory instead of terminal"),{ok:n.length===0,enforcement:h,reasons:n,changedPaths:i,mutationToolCalls:s,mutationEvidence:l}}a(Ie,"evaluateVerification");function ee(e,t){if(t.ok)return e;let o=[t.enforcement==="warn"?"[Workflow task completed without verification]":"[Workflow task verification failed]",...t.reasons.map(i=>`- ${i}`)].join(`
2
+ import{Ab as Te,Bb as X,Cb as Ee,Db as Ae,Fa as We,Jc as Pe,Kc as Oe}from"./chunk-S4ISEA6F.js";import{N as ge}from"./chunk-S4GVQO3W.js";import{Ae as be,Xa as G,be as ve,ce as Se,ee as F,fb as ye,ie as z,oe as J,pe as W,qe as H,re as xe,ye as Me,ze as Re}from"./chunk-E2Q4RIOD.js";import{B as ke}from"./chunk-ZL5CEANW.js";import{a}from"./chunk-V4WSBIXB.js";import{basename as bn,dirname as Wn}from"node:path";import{execFile as yt}from"node:child_process";import j from"node:path";import{promisify as vt}from"node:util";var St=vt(yt),xt=1e4,De=2,Fe=new Set(["write","edit","multi_edit","insert_after_anchor"]),Mt=/^\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 Rt(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)}}a(Rt,"normalizeWaitTimeoutMs");function Y(e){return e?.requiresMutation===!0||(e?.requiredChangedPaths?.length??0)>0}a(Y,"hasVerificationWork");function T(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").trim()}a(T,"normalizeWorkspacePath");function bt(e,t){let n=t.gitRoot?j.resolve(t.gitRoot):void 0,o=j.isAbsolute(e)&&n?j.relative(n,j.resolve(e)):e;return T(o)}a(bt,"normalizeRequiredPath");function Wt(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"},o=e.verification.requiredChangedPaths;return{verification:{...n,...o!==void 0&&o.length>0&&n.requiresMutation===void 0?{requiresMutation:!0}:{}}}}return{verification:t}}a(Wt,"resolveVerificationForInput");function Tt(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}}a(Tt,"resolveSpawnAgentInput");function _e(e){let t=e.trim();return t.length>0&&Mt.test(t)}a(_e,"isPreparatoryOnlyText");function Et(e,t){let n=e.trim(),o=t?.trim();return o&&(n.length===0||_e(n))?o:e}a(Et,"selectWorkflowFinalText");async function B(e,t){return(await St("git",[...e],{cwd:t,timeout:xt,windowsHide:!0,maxBuffer:4194304})).stdout.toString()}a(B,"runGit");async function At(e){let t=e.gitRoot??e.executionCwd??process.cwd(),n=(await B(["rev-parse","--show-toplevel"],t)).trim(),o=await Promise.all([B(["diff","--name-only","--"],n),B(["diff","--cached","--name-only","--"],n),B(["ls-files","--others","--exclude-standard"],n)]);return[...new Set(o.flatMap(i=>i.split(/\r?\n/)).map(T).filter(i=>i.length>0))]}a(At,"listGitChangedFiles");async function Z(e,t){try{return{paths:(await t(e)).map(T).filter(o=>o.length>0)}}catch(n){return{paths:[],error:n instanceof Error?n.message:String(n)}}}a(Z,"captureChangedPaths");function Pt(){return{toolNameById:new Map,toolPathById:new Map,succeededToolCalls:[],succeededPaths:[]}}a(Pt,"createMutationRecorder");function Ot(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 T(n)}}a(Ot,"readMutationPath");function Ft(e,t){return{...e??{},onToolUseStart:a((n,o)=>{if(Fe.has(n.name)){t.toolNameById.set(n.id,n.name);let i=Ot(n.input);i!==void 0&&t.toolPathById.set(n.id,i)}e?.onToolUseStart?.(n,o)},"onToolUseStart"),onToolResult:a((n,o)=>{let i=t.toolNameById.get(n.id)??n.name;if(Fe.has(i)&&!n.content.trimStart().startsWith("[Tool Error]")){t.succeededToolCalls.push(i);let r=t.toolPathById.get(n.id);r!==void 0&&t.succeededPaths.push(r)}e?.onToolResult?.(n,o)},"onToolResult")}}a(Ft,"wrapEventsForMutationRecording");function Q(e){return[...new Set(e.filter(t=>t.trim().length>0))]}a(Q,"uniqueItems");function Ie(e){let t=e.verification;if(!t)return;let n=[],o=new Set(e.before.paths.map(T)),i=Q(e.after.paths.map(T)),r=i.filter(m=>!o.has(m)),s=Q(e.mutationRecorder.succeededToolCalls),c=e.acceptToolMutationEvidence?s:[],p=e.acceptToolMutationEvidence?Q(e.mutationRecorder.succeededPaths.map(T)):[],l=r.length>0||c.length>0,h=t.enforcement??"hard",v=(t.requiredChangedPaths??[]).map(m=>bt(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}`):l||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&&!l&&n.push("workflow child reached its iteration limit before satisfying the task");for(let m of v)!i.includes(m)&&!p.includes(m)&&n.push(`required changed path was not present in workspace changes: ${m}`);let k=t.minFinalTextChars;return k!==void 0&&!l&&e.term.finalText.trim().length<k&&n.push(`finalText was shorter than the required ${k} characters`),t.rejectPreparatoryFinalText===!0&&!l&&_e(e.term.finalText)&&n.push("finalText looks preparatory instead of terminal"),{ok:n.length===0,enforcement:h,reasons:n,changedPaths:i,mutationToolCalls:s,mutationEvidence:l}}a(Ie,"evaluateVerification");function ee(e,t){if(t.ok)return e;let o=[t.enforcement==="warn"?"[Workflow task completed without verification]":"[Workflow task verification failed]",...t.reasons.map(i=>`- ${i}`)].join(`
3
3
  `);return e.trim().length>0?`${e}
4
4
 
5
5
  ${o}`:o}a(ee,"appendVerificationFailure");function Ce(){return{ok:!1,enforcement:"warn",reasons:["workflow child reached its iteration limit before satisfying the task"],mutationEvidence:!1}}a(Ce,"limitReachedWarningVerification");function It(e){return e.entry.bundle.readOnly!==!0&&e.entry.repairAttempts<De&&e.term.status==="completed"&&e.verification!==void 0&&e.verification.ok!==!0&&e.verification.enforcement!=="warn"}a(It,"shouldRepairVerificationFailure");function Ct(e){let t=e.verification.reasons.map(o=>`- ${o}`).join(`
@@ -9,7 +9,7 @@ ${e.verification.changedPaths?.map(o=>`- ${o}`).join(`
9
9
  `)??""}`:"";return[e.originalPrompt,"","[Workflow verification repair]",`Repair attempt ${e.attempt}/${De}.`,"The previous attempt did not satisfy the workflow postconditions.","Do not stop at analysis, planning, or a promise to begin. Complete the required file writes in the real workspace now.","Use the available file editing tools when a file change is required, then report the exact files changed.","","Verification failures:",t,n,"","Previous terminal response:",e.previousFinalText.trim()||"(empty)"].join(`
10
10
  `)}a(Ct,"buildVerificationRepairPrompt");async function $e(e,t,n,o,i=n){if(n===void 0)return e;let r;try{return await Promise.race([e,new Promise((s,c)=>{r=setTimeout(()=>{o.childAbortControllers?.get(t)?.abort(),c(new Error(`workflow task ${t} timed out after ${i??n}ms`))},n)})])}finally{r&&clearTimeout(r)}}a($e,"waitForChildPromise");function Ne(e,t,n){return t.outputSchema!==void 0&&We(t.outputSchema),Oe(t.name,t.evidenceRefs,n),{id:e,fanoutClass:"evidence-scan",objective:t.prompt,readOnly:t.readOnly??!1,evidenceRefs:t.evidenceRefs?[...t.evidenceRefs]:[],constraints:[],...t.modelHint?{modelHint:t.modelHint}:{},...t.isolation?{isolation:t.isolation}:{},...t.subagentType?{specialistName:t.subagentType}:{},...t.outputSchema!==void 0?{outputSchema:t.outputSchema}:{},...t.effort?{effort:t.effort}:{}}}a(Ne,"buildBundle");function te(e,t){if(e.cancelledChildren.includes(t))return{status:"stopped",snapStatus:"aborted",finalText:""};let n=e.results[0],o=Et(n?.summary??"",n?.digest);return n?.status==="completed"?{status:"completed",snapStatus:"completed",finalText:o,...n.digest?{digest:n.digest}:{},...n.digestFailed?{digestFailed:!0}:{},...n.digestPending?{digestPending:!0}:{},...n.limitReached?{limitReached:!0}:{},...n.provider?{provider:n.provider}:{},...n.model?{model:n.model}:{},...n.structured!==void 0?{structured:n.structured}:{}}:{status:"failed",snapStatus:"failed",finalText:o,...n?.limitReached?{limitReached:!0}:{},...n?.provider?{provider:n.provider}:{},...n?.model?{model:n.model}:{}}}a(te,"deriveTerminal");function qe(e){let{ctx:t,childOptions:n}=e,o=e.runChild??Pe,i=e.queue??ke(),r=e.listChangedFiles??At,s=e.now??(()=>Date.now()),c=0,p=e.generateId??(()=>`wf-child-${c+=1}`),l=new Map,h=new Set,v=new Map,k=a(()=>e.onTaskSummary!==void 0||h.size>0,"hasTaskSummaryObservers"),m=a((d,g)=>{try{e.onTaskSummary?.(d,g)}catch{}for(let f of h)try{f(d,g)}catch{}},"notifyTaskSummary");return{spawn:a(async d=>{let g=Tt(d,e.defaultChildReadOnly),f=p(),S=Ne(f,g,new Set(l.keys())),O=Wt(g).verification,R=Pt(),D=g.isolation!=="worktree",u=Y(O)?Z(t,r):Promise.resolve({paths:[]}),w=t.childProgressSnapshots,x=a(async A=>{let he=new AbortController;t.childAbortControllers?.set(f,he),w&&Te(w,{childId:f,startedAt:s(),maxIterations:n.maxIterationsPerChild,parentRole:n.parentRole,readOnly:A.readOnly,specialistName:A.specialistName});let kt={...n,parentOptions:{...n.parentOptions,events:Ft(n.parentOptions.events,R)},maxParallel:1,workflowChild:!0,...e.runId!==void 0?{workflowCorrelation:{workflowRunId:e.runId,childAgentId:f,itemId:`agent:${f}`}}:{},childActivityName:g.name,workflowDigestMode:k()?"async":"blocking",...k()?{onWorkflowChildDigest:a(y=>{m(y.childId,{...y.digest?{summary:y.digest}:{},summaryKind:y.digest?"digest":"digest-failed",...y.totalTokensUsed>0?{usage:{totalTokens:y.totalTokensUsed}}:{}})},"onWorkflowChildDigest")}:{},abortSignal:he.signal,snapshotUpdater:w?y=>Ee(w,f,y):void 0},q;try{return await u,q=await o([A],t,kt),q}finally{if(t.childAbortControllers?.delete(f),w){let y=q?te(q,f):{snapStatus:"failed",finalText:""};X(w,f,{status:y.snapStatus,finalText:y.finalText,endedAt:s()})}}},"runBundle"),_=x(S);return l.set(f,{name:g.name,input:g,bundle:S,promise:_,runBundle:x,verification:O,changedPathBaseline:u,mutationRecorder:R,acceptToolMutationEvidence:D,repairAttempts:0}),G(v,f,_),{taskId:f,name:g.name}},"spawn"),wait:a(async(d,g)=>{let f=l.get(d);if(!f)throw new Error(`unknown workflow task: ${d}`);let S=Rt(g),pe=Date.now(),O=a(async x=>{if(S===void 0)return $e(x,d,void 0,t);let _=Date.now()-pe,A=S-_;if(A<=0)throw t.childAbortControllers?.get(d)?.abort(),new Error(`workflow task ${d} timed out after ${S}ms`);return $e(x,d,Math.max(1,Math.floor(A)),t,S)},"waitForAttempt"),R=await O(f.promise),D=R.totalTokensUsed,u=te(R,d),w=f.verification?Ie({verification:f.verification,term:u,before:await f.changedPathBaseline,after:Y(f.verification)?await Z(t,r):{paths:[]},mutationRecorder:f.mutationRecorder,ctx:t,acceptToolMutationEvidence:f.acceptToolMutationEvidence}):void 0;for(u.limitReached===!0&&w===void 0&&u.status==="completed"&&(w=Ce(),u={...u,status:"completed_unverified",snapStatus:"completed",finalText:ee(u.finalText,w)});It({entry:f,term:u,verification:w});){f.repairAttempts+=1;let x=Ne(d,{...f.input,prompt:Ct({originalPrompt:f.input.prompt,previousFinalText:u.finalText,verification:w,attempt:f.repairAttempts})});f.promise=f.runBundle(x),G(v,d,f.promise),R=await O(f.promise),D+=R.totalTokensUsed,u=te(R,d),w=f.verification?Ie({verification:f.verification,term:u,before:await f.changedPathBaseline,after:Y(f.verification)?await Z(t,r):{paths:[]},mutationRecorder:f.mutationRecorder,ctx:t,acceptToolMutationEvidence:f.acceptToolMutationEvidence}):void 0,u.limitReached===!0&&w===void 0&&u.status==="completed"&&(w=Ce(),u={...u,status:"completed_unverified",snapStatus:"completed",finalText:ee(u.finalText,w)})}if(w!==void 0&&!w.ok&&u.status==="completed"){let x=w.enforcement==="warn";u={...u,status:x?"completed_unverified":"failed",snapStatus:x?"completed":"failed",finalText:ee(u.finalText,w)}}return X(t.childProgressSnapshots,d,{status:u.snapStatus,finalText:u.finalText,endedAt:s()}),{taskId:d,name:f.name,status:u.status,finalText:u.finalText,...u.digest?{digest:u.digest}:{},...u.digestFailed?{digestFailed:!0}:{},...u.digestPending?{digestPending:!0}:{},...w!==void 0?{verification:w}:{},...u.limitReached?{limitReached:!0}:{},...u.provider?{provider:u.provider}:{},...u.model?{model:u.model}:{},...u.structured!==void 0?{structured:u.structured}:{},usage:{totalTokens:D}}},"wait"),output:a(async d=>{if(!l.has(d))throw new Error(`unknown workflow task: ${d}`);let g=l.get(d)?.name??d,f=t.childProgressSnapshots?.get(d);if(!f)return{taskId:d,name:g,status:"running"};let S=f.status==="aborted"?"stopped":f.status;return f.finalText!==void 0?{taskId:d,name:g,status:S,lastText:f.finalText}:{taskId:d,name:g,status:S}},"output"),send:a(async(d,g)=>{if(!l.has(d))throw new Error(`unknown workflow task: ${d}`);ye({to:d,priority:"user",mode:"prompt",content:g,registry:v,queue:i})},"send"),stop:a(async d=>{if(!l.has(d))throw new Error(`unknown workflow task: ${d}`);t.childAbortControllers?.get(d)?.abort()},"stop"),subscribeTaskSummaryUpdates:a(d=>(h.add(d),()=>{h.delete(d)}),"subscribeTaskSummaryUpdates")}}a(qe,"createCodingWorkflowBackend");import{homedir as sn}from"node:os";import{join as Ze}from"node:path";var $t=["structure, entry points, and control flow","edge cases, error handling, and failure modes","tests, validation, and existing coverage"],Nt="Deduplicate overlapping findings, keep concrete evidence (file:line), rank by relevance to the question, and explicitly note gaps left by any failed investigation.",Dt={type:"object",additionalProperties:!1,required:["finding"],properties:{finding:{type:"string",description:"Your concrete findings for this focus, with file:line evidence. If nothing relevant was found, a brief note saying so."}}};function _t(e){if(e!==null&&typeof e=="object"&&"finding"in e){let t=e.finding;if(typeof t=="string"&&t.trim().length>0)return t}}a(_t,"readStructuredFinding");function qt(e){let t=_t(e.structured);if(t)return t;let n=e.finalText?.trim();return n&&n.length>0?e.finalText:"[no finding text was returned \u2014 the investigator may have ended on a tool call without a closing summary]"}a(qt,"pickFindingText");function jt(e,t){return["Investigate the following question (READ-ONLY \u2014 do not modify any files):",e,"",`Focus your investigation on: ${t}`,"","Report concrete findings backed by evidence (cite file:line). If you find nothing relevant for this focus, say so briefly."].join(`
11
11
  `)}a(jt,"buildInvestigatorPrompt");function Bt(e){let t=Math.max(1,(e.maxAgents??8)-1);return(e.targets&&e.targets.length>0?e.targets:$t).slice(0,t).map((o,i)=>({name:`investigate-${i+1}`,prompt:jt(e.question,o)}))}a(Bt,"resolveAngles");async function Lt(e,t){try{let n=await e.runAgent({name:t.name,prompt:t.prompt,readOnly:!0,outputSchema:Dt});return n===null?{angle:t.name,status:"failed",text:"[investigation failed] agent did not complete"}:{angle:t.name,status:n.status==="completed"?"completed":"failed",text:qt(n)}}catch(n){let o=n instanceof Error?n.message:String(n);return{angle:t.name,status:"failed",text:`[investigation failed] ${o}`}}}a(Lt,"investigate");async function Ut(e,t){let n=Bt(t),o=(await e.phase("investigate",()=>e.parallel(n.map(s=>()=>Lt(e,s)),t.maxConcurrency!==void 0?{concurrency:t.maxConcurrency}:void 0))).filter(s=>s!==null),i=o.some(s=>s.status!=="completed");return{synthesis:(await e.phase("synthesize",()=>e.synthesize({inputs:o.map(s=>`### ${s.angle} (${s.status})
12
- ${s.text}`),rubric:t.rubric??Nt}))).text,findings:o,degraded:i}}a(Ut,"runParallelInvestigation");var je={meta:{name:"parallel-investigation",description:"Fan out read-only investigators over a question (split by target areas), then synthesize ranked, evidence-keeping findings.",maxAgents:8,maxConcurrency:4,readOnly:!0,phases:["investigate","synthesize"]},run:Ut};function Vt(e){return{meta:e.meta,run:a((t,n)=>e.run(t,n),"run")}}a(Vt,"erase");var Be=[Vt(je)];function Le(e){return Be.find(t=>t.meta.name===e)}a(Le,"getBuiltinWorkflow");function Qn(){return Be.map(e=>e.meta)}a(Qn,"listBuiltinWorkflows");import{mkdir as ze,readdir as Kt,readFile as I,rename as Gt,unlink as oe,writeFile as ae}from"node:fs/promises";import{basename as zt,dirname as re,join as E}from"node:path";import{pathToFileURL as Jt}from"node:url";var Je=[".workflow.json",".ts",".mjs",".js"],C="0.7.49";function He(){return"0.7.60"}a(He,"currentKodaxWorkflowVersion");function Ht(e){return e.endsWith(".workflow.json")?"capability-generated":"trusted-local"}a(Ht,"executionForPath");function Xt(e){let t=Je.find(n=>e.endsWith(n));return t?e.slice(0,-t.length):void 0}a(Xt,"stripWorkflowSuffix");function ie(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}a(ie,"safeWorkflowName");function se(e){return typeof e=="object"&&e!==null}a(se,"isRecord");function Ue(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`workflow run.json missing ${t}`);return n}a(Ue,"readRequiredString");async function Ve(e,t){if(!e)return[];let n;try{n=await Kt(e)}catch{return[]}let o=new Map;for(let i of Je)for(let r of n){if(!r.endsWith(i))continue;let s=Xt(r);if(!s||s.length===0||o.has(s))continue;let c=E(e,r);o.set(s,{name:s,path:c,source:t,execution:Ht(c)})}return[...o.values()]}a(Ve,"scanDir");async function $(e){let t=await Ve(e.personal,"personal"),n=await Ve(e.project,"project"),o=new Map;for(let i of t)o.set(i.name,i);for(let i of n)o.set(i.name,i);return[...o.values()].sort((i,r)=>i.name.localeCompare(r.name))}a($,"discoverSavedWorkflows");function Yt(e){return typeof e=="object"&&e!==null&&"meta"in e&&"run"in e&&typeof e.run=="function"}a(Yt,"isWorkflowModule");function Zt(e){let t=e.default;if(Yt(t))return t;let n=typeof t=="function"?t:e.run,o=e.workflow??e.meta;if(typeof n=="function"&&typeof o=="object"&&o!==null&&"name"in o)return{meta:o,run:n};throw new Error("invalid workflow module: expected a `{ meta, run }` default export, or `export const workflow = {...}` + a default run function")}a(Zt,"normalizeWorkflowModule");function Qt(e){let t=JSON.parse(e);if(!se(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 i=J(t);return{manifest:i.manifest,source:i.source,capsule:i,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 o=F(t.manifest);return{manifest:o,source:n,capsule:W({minKodaxVersion:C,manifest:o,source:n}),legacy:!0}}a(Qt,"parseGeneratedWorkflowFile");async function ce(e){let t=Qt(await I(e,"utf8"));return t.capsule??W({minKodaxVersion:C,manifest:t.manifest,source:t.source})}a(ce,"loadSavedWorkflowCapsule");async function Xe(e){if(e.endsWith(".workflow.json"))return H(await ce(e));let t=await import(Jt(e).href);return Zt(t)}a(Xe,"loadSavedWorkflow");function fe(e){if(e.mayUseWorktree===!0)return{environment:["git-repo","worktree-capable"]}}a(fe,"deriveRequirements");function L(e,t){z(t,{filename:`${e.name}.workflow.js`,requireAsyncRun:!0})}a(L,"assertGeneratedCapsuleSource");async function en(e){let t=ie(e.name),n=F(e.manifest);L(n,e.source);let o=e.requires??fe(n),i=W({minKodaxVersion:e.minKodaxVersion??C,manifest:n,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}:{}});await ze(e.dir,{recursive:!0});let r=E(e.dir,`${t}.workflow.json`);return await ae(r,`${JSON.stringify(i,null,2)}
12
+ ${s.text}`),rubric:t.rubric??Nt}))).text,findings:o,degraded:i}}a(Ut,"runParallelInvestigation");var je={meta:{name:"parallel-investigation",description:"Fan out read-only investigators over a question (split by target areas), then synthesize ranked, evidence-keeping findings.",maxAgents:8,maxConcurrency:4,readOnly:!0,phases:["investigate","synthesize"]},run:Ut};function Vt(e){return{meta:e.meta,run:a((t,n)=>e.run(t,n),"run")}}a(Vt,"erase");var Be=[Vt(je)];function Le(e){return Be.find(t=>t.meta.name===e)}a(Le,"getBuiltinWorkflow");function Qn(){return Be.map(e=>e.meta)}a(Qn,"listBuiltinWorkflows");import{mkdir as ze,readdir as Kt,readFile as I,rename as Gt,unlink as oe,writeFile as ae}from"node:fs/promises";import{basename as zt,dirname as re,join as E}from"node:path";import{pathToFileURL as Jt}from"node:url";var Je=[".workflow.json",".ts",".mjs",".js"],C="0.7.49";function He(){return"0.7.62"}a(He,"currentKodaxWorkflowVersion");function Ht(e){return e.endsWith(".workflow.json")?"capability-generated":"trusted-local"}a(Ht,"executionForPath");function Xt(e){let t=Je.find(n=>e.endsWith(n));return t?e.slice(0,-t.length):void 0}a(Xt,"stripWorkflowSuffix");function ie(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}a(ie,"safeWorkflowName");function se(e){return typeof e=="object"&&e!==null}a(se,"isRecord");function Ue(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`workflow run.json missing ${t}`);return n}a(Ue,"readRequiredString");async function Ve(e,t){if(!e)return[];let n;try{n=await Kt(e)}catch{return[]}let o=new Map;for(let i of Je)for(let r of n){if(!r.endsWith(i))continue;let s=Xt(r);if(!s||s.length===0||o.has(s))continue;let c=E(e,r);o.set(s,{name:s,path:c,source:t,execution:Ht(c)})}return[...o.values()]}a(Ve,"scanDir");async function $(e){let t=await Ve(e.personal,"personal"),n=await Ve(e.project,"project"),o=new Map;for(let i of t)o.set(i.name,i);for(let i of n)o.set(i.name,i);return[...o.values()].sort((i,r)=>i.name.localeCompare(r.name))}a($,"discoverSavedWorkflows");function Yt(e){return typeof e=="object"&&e!==null&&"meta"in e&&"run"in e&&typeof e.run=="function"}a(Yt,"isWorkflowModule");function Zt(e){let t=e.default;if(Yt(t))return t;let n=typeof t=="function"?t:e.run,o=e.workflow??e.meta;if(typeof n=="function"&&typeof o=="object"&&o!==null&&"name"in o)return{meta:o,run:n};throw new Error("invalid workflow module: expected a `{ meta, run }` default export, or `export const workflow = {...}` + a default run function")}a(Zt,"normalizeWorkflowModule");function Qt(e){let t=JSON.parse(e);if(!se(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 i=J(t);return{manifest:i.manifest,source:i.source,capsule:i,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 o=F(t.manifest);return{manifest:o,source:n,capsule:W({minKodaxVersion:C,manifest:o,source:n}),legacy:!0}}a(Qt,"parseGeneratedWorkflowFile");async function ce(e){let t=Qt(await I(e,"utf8"));return t.capsule??W({minKodaxVersion:C,manifest:t.manifest,source:t.source})}a(ce,"loadSavedWorkflowCapsule");async function Xe(e){if(e.endsWith(".workflow.json"))return H(await ce(e));let t=await import(Jt(e).href);return Zt(t)}a(Xe,"loadSavedWorkflow");function fe(e){if(e.mayUseWorktree===!0)return{environment:["git-repo","worktree-capable"]}}a(fe,"deriveRequirements");function L(e,t){z(t,{filename:`${e.name}.workflow.js`,requireAsyncRun:!0})}a(L,"assertGeneratedCapsuleSource");async function en(e){let t=ie(e.name),n=F(e.manifest);L(n,e.source);let o=e.requires??fe(n),i=W({minKodaxVersion:e.minKodaxVersion??C,manifest:n,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}:{}});await ze(e.dir,{recursive:!0});let r=E(e.dir,`${t}.workflow.json`);return await ae(r,`${JSON.stringify(i,null,2)}
13
13
  `,"utf8"),{name:t,path:r,source:"project",execution:"capability-generated"}}a(en,"saveGeneratedWorkflow");async function Ke(e,t){await ae(e,`${JSON.stringify(t,null,2)}
14
14
  `,"utf8")}a(Ke,"writeCapsuleFile");async function tn(e){try{return await I(e,"utf8"),!0}catch{return!1}}a(tn,"fileExists");async function ir(e){let t=(await $(e.dirs)).filter(c=>c.name===e.name).filter(c=>e.source===void 0||c.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 o=ie(e.newName),i=E(re(n.path),`${o}.workflow.json`);if(i!==n.path&&await tn(i))throw new Error(`saved workflow already exists: ${o}`);let r=await ce(n.path);L(r.manifest,r.source);let s=W({minKodaxVersion:r.minKodaxVersion,manifest:{...r.manifest,name:o},source:r.source,...r.intent!==void 0?{intent:r.intent}:{},...r.inputs!==void 0?{inputs:r.inputs}:{},...r.requires!==void 0?{requires:r.requires}:{},...r.provenance!==void 0?{provenance:r.provenance}:{}});return await ae(i,`${JSON.stringify(s,null,2)}
15
15
  `,"utf8"),i!==n.path&&await oe(n.path),{name:o,path:i,source:n.source,execution:"capability-generated"}}a(ir,"renameSavedWorkflow");async function sr(e){let t=(await $(e.dirs)).filter(o=>o.name===e.name).filter(o=>e.source===void 0||o.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 oe(n.path),n}a(sr,"deleteSavedWorkflow");async function cr(e){let t=ie(e.name),n=(await $(e.dirs)).filter(m=>m.name===t).filter(m=>e.savedSource===void 0||m.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 o=n[0];if(!o.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be replaced");let i=F({...e.manifest,name:t});L(i,e.source);let r=e.requires??fe(i),s=W({minKodaxVersion:e.minKodaxVersion??C,manifest:i,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}:{}}),c=await ce(o.path),p=new Date().toISOString().replace(/[:.]/g,"-"),l=E(re(o.path),".revisions",t),h=`${p}-${process.hrtime.bigint().toString(36)}`,v=E(l,`${t}-${h}.workflow.json`),k=E(re(o.path),`.${t}.${process.pid}.${Date.now().toString(36)}.tmp`);await ze(l,{recursive:!0}),await Ke(v,c);try{await Ke(k,s),await Gt(k,o.path)}catch(m){try{await oe(k)}catch{}throw m}return{name:t,path:o.path,source:o.source,execution:"capability-generated",previousPath:v}}a(cr,"replaceSavedWorkflow");function nn(e){if(!se(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}a(nn,"readOptionalOriginalRequest");function Ye(e){return rn(e)}a(Ye,"buildCapsuleFromRun");async function rn(e){let t=JSON.parse(await I(E(e.runDir,"run.json"),"utf8"));if(!se(t))throw new Error("workflow run.json must be an object");let n=Ue(t,"scriptSnapshotPath"),o=Ue(t,"manifestSnapshotPath"),i=await I(n,"utf8"),r=F(JSON.parse(await I(o,"utf8")));L(r,i);let s=typeof t.runId=="string"&&t.runId.length>0?t.runId:zt(e.runDir),c=nn(t.args),p=fe(r),l=xe(r,c!==void 0?{originalRequest:c}:{}),h={description:"Provide new workflow args matching the generated request shape.",..."args"in t?{examples:[t.args]}:{}};return W({minKodaxVersion:C,manifest:r,source:i,intent:l,inputs:h,...p!==void 0?{requires:p}:{},provenance:{fromRunId:s,createdAt:new Date().toISOString(),kodaxVersion:He()}})}a(rn,"readCapsuleFromRun");async function fr(e){let t=await Ye(e);return{capsule:t,module:H(t)}}a(fr,"loadGeneratedWorkflowFromRun");async function dr(e){let t=await Ye(e);return en({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})}a(dr,"saveGeneratedWorkflowFromRun");function b(e,t,n,o){e.push({severity:t,requirement:n,message:o})}a(b,"addRequirementIssue");function Ge(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e.trim());if(t)return[Number(t[1]),Number(t[2]),Number(t[3])]}a(Ge,"parseSemver");function on(e,t){for(let n=0;n<3;n+=1){let o=e[n]-t[n];if(o!==0)return o}return 0}a(on,"compareSemver");function an(e,t,n){let o=Ge(t),i=Ge(n);if(!o){b(e,"error","kodax:min-version",`workflow minKodaxVersion is not valid semver: ${t}`);return}if(!i){b(e,"warning","kodax:min-version",`cannot verify workflow minKodaxVersion ${t}; current version is unknown`);return}on(i,o)<0&&b(e,"error","kodax:min-version",`workflow requires KodaX >= ${t}, current version is ${n}`)}a(an,"addMinVersionIssue");function ne(e,t,n,o){if(!n)return;if(!o){for(let r of n)b(e,"warning",`${t}:${r}`,`workflow requires ${t}:${r}, but no ${t} inventory was provided`);return}let i=new Set(o);for(let r of n)i.has(r)||b(e,"error",`${t}:${r}`,`missing required workflow ${t}: ${r}`)}a(ne,"addMissingItems");function ur(e,t={}){let n=J(e),o=[],i=n.requires;an(o,n.minKodaxVersion,t.kodaxVersion??He()),i?.environment?.includes("git-repo")&&t.isGitRepo===!1&&b(o,"error","environment:git-repo","workflow requires a git repository"),i?.environment?.includes("worktree-capable")&&t.worktreeCapable===!1&&b(o,"error","environment:worktree-capable","workflow may request git worktree isolation");try{z(n.source,{filename:`${n.manifest.name}.workflow.js`,requireAsyncRun:!0})}catch(r){let s=r instanceof Error?r.message:String(r);b(o,"error","workflow:source",s)}return ne(o,"tools",i?.tools,t.availableTools),ne(o,"mcp",i?.mcp,t.availableMcp),ne(o,"skills",i?.skills,t.availableSkills),{ok:!o.some(r=>r.severity==="error"),issues:o}}a(ur,"preflightWorkflowCapsule");function cn(e){return{project:Ze(e,".kodax","workflows"),personal:Ze(sn(),".kodax","workflows")}}a(cn,"defaultSavedWorkflowDirs");async function fn(e,t){let o=(await $(t)).find(i=>i.name===e);if(o)return Xe(o.path)}a(fn,"resolveSavedByName");function Qe(e){let t=cn(e);return async n=>Le(n)??await fn(n,t)}a(Qe,"createNestedWorkflowResolver");import{existsSync as dn,mkdirSync as un,readFileSync as ln,writeFileSync as et}from"node:fs";import{join as N}from"node:path";var tt="results";function nt(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}a(nt,"safeKey");function rt(e,t){let n=N(e,t);if(dn(n))try{return JSON.parse(ln(n,"utf8"))}catch{return}}a(rt,"readResult");function ot(e,t={}){let n=N(e,tt);un(n,{recursive:!0});let o=t.readFrom?N(t.readFrom,tt):void 0;return{get:a(i=>{let r=`${nt(i)}.json`,s=rt(n,r);if(s!==void 0)return s;if(o===void 0)return;let c=rt(o,r);if(c!==void 0){try{et(N(n,r),JSON.stringify(c),"utf8")}catch{}return c}},"get"),set:a((i,r)=>{try{et(N(n,`${nt(i)}.json`),JSON.stringify(r),"utf8")}catch{}},"set")}}a(ot,"createFsResultCache");import{mkdirSync as mn,appendFileSync as wn,writeFileSync as U}from"node:fs";import{join as P}from"node:path";function pn(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,120);return t.length>0?t:"artifact"}a(pn,"safeWorkflowArtifactName");function at(e,t={}){let n=t.now??(()=>Date.now()),o=P(e,"artifacts");mn(o,{recursive:!0});let i=P(e,"events.jsonl");return{runDir:e,onEvent:a(r=>{wn(i,`${JSON.stringify({...r,ts:n()})}
@@ -0,0 +1,19 @@
1
+ // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
+ import{t as N,z as C}from"./chunk-JILSZHCQ.js";import{Da as M,Ea as q}from"./chunk-S4ISEA6F.js";import{$a as R,Ja as E,j as b,k as T}from"./chunk-S4GVQO3W.js";import{ac as O,bc as W,de as $,ee as g,fe as k,gc as I,ie as _,je as y,ke as x}from"./chunk-E2Q4RIOD.js";import{a as o}from"./chunk-V4WSBIXB.js";import{join as Pe}from"node:path";var te=["You generate KodaX Dynamic Workflow scripts.","Return JSON only. Do not wrap the answer in prose.","For simple tasks that do not benefit from multiple agents, return:",'{"action":"decline","reason":"..."}',"For complex tasks, return:",'{"action":"generate","manifest":{...},"source":"async function run(wf, args) { ... }","approvalSummary":"..."}',"Generated source may only coordinate agents through wf and args.","Generated source must return displayable final text for the user.","Never use import, require, process, fs, child_process, network APIs, shell commands, or direct file access."].join(`
3
+ `),j=12e4,ne="KODAX_WORKFLOW_GENERATION_TIMEOUT_SEC",re="KODAX_WORKFLOW_GENERATION_TIMEOUT_MS",se=64,oe=2,ie=2e3,ae=[{name:"default"},{name:"variant-results",finalText:o((e,n)=>`Variant smoke child report from ${e} (${n}).`,"finalText"),synthesizeText:"Variant smoke synthesis report."},{name:"unverified-success",status:o(()=>"completed_unverified","status"),finalText:o(e=>`Smoke result for ${e}: completed with verification warnings.`,"finalText"),synthesizeText:"Smoke synthesis: completed with verification warnings."},{name:"empty-args-rerun",args:o(()=>({}),"args")}],le=["- classify-and-act: first classify a mixed request, then route to the right worker behavior.","- fan-out-and-synthesize: split independent areas, files, hypotheses, reviewers, or perspectives; run them with wf.parallel, then wf.synthesize.","- adversarial-verification: produce or inspect a candidate, then have an independent verifier attack assumptions, evidence, and edge cases.","- generate-and-filter: ask several generators for distinct candidates, then filter/dedupe/rank before synthesis.","- tournament: compare competing approaches or answers and use synthesis as the judge.","- loop-until-done: run bounded follow-up rounds when findings should drive the next prompt.","- review or audit combines fan-out-and-synthesize with adversarial-verification: fan independent reviewers out across the dimensions, then pipe each finding straight into a verifier that tries to refute it before synthesis. A review with no verification stage ships findings a single reviewer's blind spot would have hidden."],ce=[{id:"import",pattern:/\bimport\s*(?:\(|['"*{]|\w+\s+from\b)/},{id:"require",pattern:/\brequire\s*\(/},{id:"process",pattern:/\bprocess\s*(?:\.|\[)/},{id:"fs",pattern:/\b(?:node:)?fs\b/},{id:"child_process",pattern:/\bchild_process\b/},{id:"shell",pattern:/\b(?:exec|spawn|execFile)\s*\(/},{id:"fetch",pattern:/\bfetch\s*\(/},{id:"Deno",pattern:/\bDeno\s*(?:\.|\[)/},{id:"Bun",pattern:/\bBun\s*(?:\.|\[)/},{id:"globalThis-index",pattern:/\bglobalThis\s*\[/}];function ue(e=process.env,n){let t=b(n?.workflow?.generationTimeoutSec,"timeouts.workflow.generationTimeoutSec");if(t!==void 0)return t;let r=T(e[ne]);if(r!==void 0)return r;let s=e[re];if(s===void 0||s.trim().length===0)return j;let i=Number(s);return!Number.isFinite(i)||i<=0?j:Math.floor(i)}o(ue,"resolveWorkflowGenerationTimeoutMs");function fe(e,n){if(typeof e!="object"||e===null)throw new Error(`${n} must be an object`);return e}o(fe,"readRecord");function P(e,n){let t=e[n];if(typeof t!="string"||t.trim().length===0)throw new Error(`workflow generation ${n} must be a non-empty string`);return t}o(P,"readNonEmptyString");function de(e){let n=e.trim(),t=/^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(n);if(t?.[1])return t[1].trim();let r=n.indexOf("{"),s=n.lastIndexOf("}");if(r>=0&&s>r)return n.slice(r,s+1);throw new Error("workflow generation output did not contain a JSON object")}o(de,"extractJsonText");function pe(e){let n=de(e);return fe(JSON.parse(n),"workflow generation output")}o(pe,"parseGenerationJson");function me(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(typeof e!="object"||e===null)return;let n=e;for(let t of["name","id","title","phase"]){let r=n[t];if(typeof r=="string"&&r.trim().length>0)return r.trim()}}o(me,"normalizePhaseEntry");function he(e){return e.split(/(?:->|\u2192|,|\n)/).map(n=>n.trim()).filter(n=>n.length>0)}o(he,"splitPhaseString");function we(e){if(typeof e!="object"||e===null)return e;let n=e,t=n.phases,r;if(Array.isArray(t)){let s=t.map(me);s.every(i=>i!==void 0)&&(r=s)}else if(typeof t=="string"){let s=he(t);s.length>0&&(r=s)}return r?{...n,phases:r}:e}o(we,"normalizeGeneratedManifestCandidate");function ge(e){return e.match(/\bwf\.(?:runAgent|spawnAgent|synthesize)\s*\(/g)?.length??0}o(ge,"estimateDirectAgentCalls");function ke(e,n){let t=e.maxConcurrency*Math.max(1,e.phases.length)+2,r=ge(n)+2,s=Math.min(se,Math.max(e.maxAgents,t,r));return s>e.maxAgents?{...e,maxAgents:s}:e}o(ke,"reserveGeneratedWorkflowAgentCapacity");function h(e){let n="",t=0,r=["code"],s=[0];for(;t<e.length;){let i=e[t],a=e[t+1];if(r[r.length-1]==="template"){if(i==="\\"){n+=" ",t+=2;continue}if(i==="`"){n+=" ",t+=1,r.pop(),s.pop();continue}if(i==="$"&&a==="{"){n+=" ",t+=2,r.push("code"),s.push(0);continue}n+=i===`
4
+ `?`
5
+ `:" ",t+=1;continue}if(i==="/"&&a==="/"){for(n+=" ",t+=2;t<e.length&&e[t]!==`
6
+ `;)n+=" ",t+=1;continue}if(i==="/"&&a==="*"){for(n+=" ",t+=2;t<e.length;){if(e[t]==="*"&&e[t+1]==="/"){n+=" ",t+=2;break}n+=e[t]===`
7
+ `?`
8
+ `:" ",t+=1}continue}if(i==='"'||i==="'"){let c=i;for(n+=" ",t+=1;t<e.length;){let u=e[t];if(n+=u===`
9
+ `?`
10
+ `:" ",t+=1,u==="\\"){t<e.length&&(n+=e[t]===`
11
+ `?`
12
+ `:" ",t+=1);continue}if(u===c)break}continue}if(i==="`"){n+=" ",t+=1,r.push("template"),s.push(0);continue}if(i==="{"){s[s.length-1]+=1,n+=i,t+=1;continue}if(i==="}"){if(s[s.length-1]>0){s[s.length-1]-=1,n+=i,t+=1;continue}if(r.length>1){n+=" ",t+=1,r.pop(),s.pop();continue}n+=i,t+=1;continue}n+=i??"",t+=1}return n}o(h,"stripGeneratedSourceLiterals");function ye(e,n){for(let t=n+1;t<e.length;t+=1){let r=e[t];if(r==="\\"){t+=1;continue}if(r==="`")return!1;if(r==="$"&&e[t+1]==="{")return!0}return!1}o(ye,"templateLiteralHasExpression");function xe(e){let n=h(e),t=/\bwf\s*\.\s*(wait|snapshot|send|stop)\s*\(/g,r;for(;(r=t.exec(n))!==null;){let s=r[1];if(!s)continue;let i=n.indexOf("(",r.index);if(i<0)continue;let a=i+1;for(;/\s/.test(e[a]??"");)a+=1;let c=e[a];if(!(c==="`"&&ye(e,a))&&(c==='"'||c==="'"||c==="`"))return{method:s}}}o(xe,"findLiteralWorkflowTaskTarget");function D(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}o(D,"isIdentifierPart");function K(e){let n=h(e),t=/\basync\s+function\s+run\s*\([^)]*\)\s*\{/.exec(n);if(!t)return;let r=n.indexOf("{",t.index);if(r<0)return;let s=0;for(let i=r;i<n.length;i+=1){let a=n[i];if(a==="{"&&(s+=1),a==="}"&&(s-=1,s===0))return{start:r+1,end:i}}}o(K,"findRunBodyRange");function z(e,n){let t=h(e),r=1;for(let s=n.start;s<n.end;s+=1){let i=t[s];if(i==="{"){r+=1;continue}if(i==="}"){r-=1;continue}if(r===1&&t.startsWith("return",s)&&!D(t[s-1])&&!D(t[s+6])){let a=s+6,c=0;for(let u=a;u<n.end;u+=1){let d=t[u];if((d==="("||d==="["||d==="{")&&(c+=1),(d===")"||d==="]"||d==="}")&&(c-=1),c===0&&(d===";"||d===`
13
+ `||d==="\r"))return e.slice(a,u).trim()}return e.slice(a,n.end).trim()}}}o(z,"findTopLevelReturnExpression");function L(e){let n=K(e);if(n)return z(e,n)}o(L,"findOuterRunReturnExpression");function be(e){let n=K(e);if(!n)return[];let t=h(e),r=[],s=n.start,i=1;for(let c=n.start;c<n.end;c+=1){let u=t[c];if(u==="{"||u==="("||u==="["){i+=1;continue}if(u==="}"||u===")"||u==="]"){i-=1;continue}if(u===";"&&i===1){let d=e.slice(s,c+1).trim();d&&r.push(d),s=c+1}}let a=e.slice(s,n.end).trim();return a&&r.push(a),r}o(be,"findOuterRunStatements");function ve(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}o(ve,"escapeRegExp");function Se(e,n){let t=/^[A-Za-z_$][A-Za-z0-9_$]*$/.exec(n.trim())?.[0];if(!t)return!1;let r=ve(t),s=new RegExp(`^\\s*(?:const|let|var)\\s+${r}\\s*=\\s*(?:await\\s+)?wf\\s*\\.\\s*artifact\\b`),i=new RegExp(`^\\s*${r}\\s*=\\s*(?:await\\s+)?wf\\s*\\.\\s*artifact\\b`);return be(e).some(a=>s.test(a)||i.test(a))}o(Se,"isReturnedArtifactHandle");function F(e,n,t,r){let s=0;for(let i=n;i<e.length;i+=1){let a=e[i];if(a===t&&(s+=1),a===r&&(s-=1,s===0))return i}}o(F,"findMatchingDelimiter");function Ae(e,n,t){let r=0;for(let s=n;s<t;s+=1){let i=e[s];if(i==="("||i==="["||i==="{"){r+=1;continue}if(i===")"||i==="]"||i==="}"){r-=1;continue}if(i===","&&r===0)return s}}o(Ae,"findTopLevelComma");function Te(e){let n=h(e),t=/^\s*(?:await\s+)?wf\s*\.\s*phase\s*\(/.exec(n);if(!t)return;let r=n.indexOf("(",t.index);if(r<0)return;let s=F(n,r,"(",")");if(s===void 0)return;let i=Ae(n,r+1,s);if(i===void 0)return;let a=e.slice(i+1,s).trim(),c=h(a),u=c.indexOf("=>");if(u<0)return;let d=u+2,l=c.slice(d).search(/\S/);if(l<0)return;let f=d+l;if(c[f]!=="{")return a.slice(f).trim();let p=F(c,f,"{","}");if(p!==void 0)return z(a,{start:f+1,end:p})}o(Te,"findPhaseCallbackReturnExpression");function G(e,n){return new RegExp(`^(?:await\\s+)?wf\\s*\\.\\s*${n}\\b`).test(e.trim())}o(G,"isDirectWorkflowCall");function U(e,n){let t=n.trim();if(/^(?:undefined|null|void\s+0|\{\s*\}|\[\s*\]|''|""|``)$/.test(t)||G(t,"artifact")||Se(e,t))return!1;if(G(t,"phase")){let r=Te(t);return r!==void 0&&U(t,r)}return!0}o(U,"isDisplayableReturnExpression");function Ee(e){let n=L(e);return n?U(e,n):!1}o(Ee,"hasDisplayableRunReturn");function Re(e){try{_(e,{filename:"generated-workflow.js",requireAsyncRun:!0,checkSourcePolicy:!1})}catch(n){let t=n instanceof Error?n.message:String(n),s=/Unexpected (identifier|string|token|end of input)|Invalid or unexpected token/i.test(t)?" \u2014 a prompt string likely has an unescaped quote or apostrophe; wrap that string in double quotes or backticks, or escape the quote, then retry":"";throw new Error(`workflow generation source has invalid JavaScript syntax: ${t}${s}`)}}o(Re,"assertGeneratedWorkflowSyntax");function Oe(e){let n=0,t=new Map,r=[],s=o(l=>{n+=1;let f=`smoke-task-${n}-${Math.random().toString(36).slice(2,8)}`;return t.set(f,l),{taskId:f,name:l}},"nextHandle"),i=o((l,f)=>{if(t.has(f))return;throw[...t.entries()].find(m=>m[1]===f)?new Error(`wf.${l}("${f}") used an agent name, but workflow task APIs require the taskId returned by spawnAgent/runAgent. Store the handle/result and pass handle.taskId or result.taskId. wf.runAgent already returns the completed result; wf.parallel returns the array of results.`):new Error(`wf.${l}("${f}") references an unknown workflow task id`)},"assertKnownTaskId"),a=o(l=>{for(let f of l.evidenceRefs??[]){if(f.startsWith("file:")||f.startsWith("diff:")||f.startsWith("finding:"))continue;if(f.startsWith("task_id:")){let m=f.slice(8).trim();if(m.length===0)throw new Error(`wf.runAgent("${l.name}") evidenceRefs contains empty task_id: reference`);i("evidenceRefs",m);continue}throw[...t.entries()].find(m=>m[1]===f)?new Error(`wf.runAgent("${l.name}") evidenceRefs contains agent name "${f}". Use "task_id:" + result.taskId from the child result.`):new Error(`wf.runAgent("${l.name}") evidenceRefs contains unsupported ref "${f}". Use file:, diff:, finding:, or task_id:<id>.`)}},"assertEvidenceRefs"),c=o((l,f)=>{i("wait",l);let p=t.get(l)??f??l,m=e.status?.(p,l)??"completed";return{taskId:l,name:p,status:m,finalText:e.finalText?.(p,l)??`Smoke result for ${p}: completed, done, verified.`}},"resultFor"),u=o((l,f)=>{i(l,f);let p=t.get(f)??f;return{taskId:f,name:p,status:"completed",lastText:`Smoke snapshot for ${p}`}},"snapshotFor");return{api:{runId:"run-smoke",args:void 0,budget:{total:null,spent:o(()=>0,"spent"),remaining:o(()=>1/0,"remaining")},phase:o(async(l,f)=>f(),"phase"),spawnAgent:o(async l=>(a(l),s(l.name)),"spawnAgent"),runAgent:o(async l=>{a(l);let f=s(l.name),p=c(f.taskId,l.name);if(p.status==="failed"||p.status==="stopped")throw new Error(`workflow task ${p.name} (${p.taskId}) ${p.status}`);return p},"runAgent"),wait:o(async l=>c(l),"wait"),snapshot:o(async l=>u("snapshot",l),"snapshot"),output:o(async l=>u("output",l),"output"),send:o(async l=>{i("send",l)},"send"),stop:o(async l=>{i("stop",l)},"stop"),parallel:o(async l=>Promise.all(l.map(f=>f())),"parallel"),synthesize:o(async()=>({text:e.synthesizeText??"Smoke synthesis: completed, done, verified."}),"synthesize"),artifact:o(async l=>(r.push(l),{name:l}),"artifact"),log:o(()=>{},"log")},artifactCount:o(()=>r.length,"artifactCount")}}o(Oe,"createSmokeWorkflowApi");function We(e,n){if(n>0)return!0;if(typeof e=="string")return e.trim().length>0;if(e==null)return!1;if(typeof e!="object")return!0;if(Array.isArray(e))return e.length>0;let t=e,r=!1,s=t.synthesis;if(typeof s=="string"&&(r=!0,s.trim().length>0))return!0;if(s&&typeof s=="object"){r=!0;let i=s.text;if(typeof i=="string"&&i.trim().length>0)return!0}for(let i of["summary","report","text","result"]){let a=t[i];if(a!==void 0&&(r=!0),typeof a=="string"&&a.trim().length>0)return!0}return r&&Object.keys(t).every(i=>i==="synthesis"||i==="summary"||i==="report"||i==="text"||i==="result")?!1:Object.keys(t).length>0}o(We,"isSmokeResultDisplayable");async function Ie(e){for(let n of ae)try{let t=Oe(n),r=await y({source:e.source,wf:t.api,args:n.args?.(e.request)??{request:e.request},filename:"generated-workflow-smoke.js",timeoutMs:ie});if(!We(r,t.artifactCount()))throw new Error("run() returned no displayable result or artifact")}catch(t){let r=t instanceof Error?t.message:String(t);throw new Error(`workflow generation source failed safe smoke validation (${n.name}): ${r}`)}}o(Ie,"assertGeneratedWorkflowSmoke");function v(e){if(e.trim().length===0)throw new Error("workflow generation source must be non-empty");if(!/\basync\s+function\s+run\s*\(/.test(e))throw new Error("workflow generation source must define async function run(wf, args)");Re(e);let n=h(e);for(let r of ce)if(r.pattern.test(n))throw new Error(`forbidden generated workflow token: ${r.id}`);if(/\.\s*output\b/.test(n))throw/\bwf\s*\.\s*output\s*\(/.test(n)?new Error("workflow generation source must use wf.snapshot(taskId) instead of legacy wf.output(taskId)"):new Error("workflow generation source must use finalText/text instead of non-existent .output");let t=xe(e);if(t)throw new Error(`workflow generation source must pass taskId variables to wf.${t.method}(...) instead of string literals; use handle.taskId from wf.spawnAgent(...) or result.taskId from wf.runAgent(...).`);for(let r of n.split(/\r?\n/)){let s=r.search(/\bwf\.artifact\s*\(/);if(s>=0&&!/\b(?:await|return)\b/.test(r.slice(0,s)))throw new Error("workflow generation source must await wf.artifact(...)")}if(!Ee(e)){let r=L(e),s=r===void 0?"no top-level `return` was found in run() \u2014 a return inside a wf.phase(...) callback does not count":`the top-level return \`${r.slice(0,80)}\` is not displayable \u2014 do not return undefined/null/{}, a bare wf.artifact(...) write, or a wf.phase(...) without a displayable callback return`;throw new Error(`workflow generation source outer run function must return displayable final text (${s})`)}return e}o(v,"validateGeneratedWorkflowSource");function $e(e){let n=e?.trim();return n?["","Referenced skill instructions (authoritative):",n,"","Skill handling requirements:","- Treat the referenced skill instructions above as binding requirements for this workflow generation.","- Preserve skill-specific file layout, naming, and process requirements in child-agent prompts that do the work.",'- Do not replace concrete skill requirements with vague paths such as "or similar"; choose paths from the skill or instruct the child to invoke the skill before acting.']:[]}o($e,"buildReferencedSkillPromptSection");function B(e,n){return["Task request:",e,...$e(n),"","Available WorkflowApi calls:","- wf.phase(name, async () => ...)","- wf.spawnAgent({ name, prompt, readOnly, modelHint, isolation, evidenceRefs, verification, outputSchema })","- wf.runAgent({ name, prompt, readOnly, modelHint, isolation, evidenceRefs, verification, outputSchema })","- wf.wait(taskId), wf.snapshot(taskId), wf.send(taskId, content), wf.stop(taskId, reason)","- wf.parallel([() => promise], { concurrency })","- wf.synthesize({ inputs, rubric }); inputs may be an array of materials, one already-formatted string, or a named object of materials","- wf.artifact(name, value), wf.log({ message, data })","- Return shapes: wf.runAgent/wf.wait return { taskId, name, status, finalText, structured?, digest?, verification?, usage }; wf.snapshot returns { taskId, name, status, lastText? }; wf.synthesize returns { text }; wf.artifact returns { name, path? }.","- When a spawn declared outputSchema (a JSON-Schema subset of type/enum/required/properties/items/additionalProperties), its parsed and validated object comes back on result.structured, not on the top-level result.","- Read your declared fields off result.structured, for example result.structured.findings. Reading them off the top-level result, or inventing top-level fields like result.findings or result.summary after declaring outputSchema, yields undefined and an empty report, because the validated object lives only on result.structured.","- Task identity rule: taskId is the opaque result.taskId/handle.taskId value, never the agent name string. Do not hardcode task IDs or pass string literals to wf.wait/wf.snapshot/wf.send/wf.stop; pass handle.taskId or result.taskId variables.","- Important naming trap: never use anyVariable.output in generated source. Agent results use finalText; synthesis results use text; task snapshots use lastText.","- Always await asynchronous workflow calls, especially wf.artifact(...), before returning.",'- Treat args as optional rerun input. Read request text with a fallback such as String(args.request || "the original request") or bake stable request context into child prompts.',"- For fan-out, prefer wf.parallel with thunks that call wf.runAgent; if using wf.spawnAgent, always wait or stop each handle so maxConcurrency capacity can release.","- Correct fan-out result pattern: const results = await wf.parallel([...].map((item) => () => wf.runAgent({...})), { concurrency }); then use results[n].finalText or results.map((r) => r.finalText). Do not call wf.wait after wf.runAgent.","- Keep intermediate findings in local variables and pass their finalText/text values forward; artifacts are durable outputs, not mutable args.","- File-writing/implementation requests are not report-only workflows. If the user asks to create, update, land, implement, or write project files, set manifest.readOnly=false, use readOnly:false child agents for the writing phases, give exact target paths in the prompt, and include verification:{ requiresMutation:true, requiredChangedPaths:[...], rejectPreparatoryFinalText:true } whenever target paths are knowable.","- Never put placeholder paths such as vNEXT.md or TODO.md in requiredChangedPaths. If the exact path is not knowable, omit requiredChangedPaths and keep requiresMutation:true.","- A write child must not ask the user to confirm routine filenames or version numbers already inferable from the request/context; it should choose the minimal project-consistent target paths, write them, and report what changed.",'- Prefer shared-cwd for write children. Do not set isolation:"worktree" for writing phases unless the workflow has an explicit merge-back strategy; isolated write evidence is not a delivered project change.',"- The outer run function must return displayable final text, preferably { synthesis: finalText }. Returning only inside a wf.phase callback is invalid. Artifact-only or empty returns are invalid.",'- Also await wf.artifact("final-report", { summary/report/text: finalText }) for durable inspection when a final report is produced.','- For multi-line prompts, rubrics, or report templates inside source, use JavaScript template literals (`...`) or arrays joined with "\\n"; never place raw newlines inside single-quoted or double-quoted strings.',"- Do not ask child agents to emit special transcript marker blocks. KodaX derives child-agent transcript digests after each child finishes; child prompts should focus on the actual work product and final report.","","Minimal source field-usage example; use it for result fields/syntax, not as the default workflow shape:","async function run(wf, args) {",' const first = await wf.runAgent({ name: "first-pass", prompt: String(args.request || ""), readOnly: true });',' const second = await wf.runAgent({ name: "second-pass", prompt: first.finalText, readOnly: true });',' const synthesis = await wf.synthesize({ inputs: [first.finalText, second.finalText], rubric: "Synthesize a final answer." });'," const finalText = synthesis.text;",' await wf.artifact("final-report", { report: finalText });'," return { synthesis: finalText };","}","","Structured-output example; when a child must return machine-readable fields (e.g. a reviewer panel), declare outputSchema and read the fields off result.structured:","async function run(wf, args) {",' const schema = { type: "object", additionalProperties: false, required: ["findings"], properties: { findings: { type: "array", items: { type: "string" } } } };',' const reviewer = await wf.runAgent({ name: "reviewer", prompt: String(args.request || ""), readOnly: true, outputSchema: schema });'," const findings = reviewer && reviewer.structured ? reviewer.structured.findings : [];",' const synthesis = await wf.synthesize({ inputs: findings, rubric: "Rank and dedupe the findings." });'," return { synthesis: synthesis.text };","}","","Canonical write-and-verify pattern for requests that must land project files:","async function run(wf, args) {",' const request = String(args.request || "Implement the requested project change.");'," const targetPaths = Array.isArray(args.targetPaths) ? args.targetPaths.map(String).filter(Boolean) : [];"," const writer = await wf.runAgent({",' name: "implementation-writer",'," prompt: [",' "Implement the requested project change in the real workspace.",',' "Use project conventions, write the files, and do not stop at a plan.",',' targetPaths.length ? "Target paths: " + targetPaths.join(", ") : "Choose the minimal project-consistent target paths.",'," request",' ].join("\\n"),'," readOnly: false,"," verification: {"," requiresMutation: true,"," ...(targetPaths.length ? { requiredChangedPaths: targetPaths } : {}),"," rejectPreparatoryFinalText: true"," }"," });"," const finalText = writer.finalText;",' await wf.artifact("final-report", { report: finalText, verification: writer.verification });'," return { synthesis: finalText, verification: writer.verification };","}","",`Supported pattern ids: ${$.join(", ")}`,"","Pattern selection guidance:",...le,"- Complex multi-part work should normally include at least two work phases plus a final wf.synthesize barrier.","- Do not collapse independent investigation, verification, ranking, generation/filtering, or iteration into one child agent.","- A generated workflow with only one child agent is appropriate only when the request has one indivisible work product; otherwise decline simple tasks or generate a richer pattern.",'- Use evidenceRefs when one child reviews another child result; reference child results as "task_id:" + result.taskId, never as bare agent names. Use modelHint:"deep" for verifiers, judges, and synthesis-critical workers.',"","Manifest requirements:","- name, description, phases, readOnly, maxAgents, maxConcurrency, optional plannedAgents, optional tokenBudget",'- phases must be a JSON array of non-empty string literals, for example ["investigate","verify","synthesize"]; never return phase objects or a single string',"- maxAgents and maxConcurrency must be positive JSON integers","- plannedAgents is the best estimate of how many child agents this script will normally launch; it is for progress display and must be no larger than maxAgents","- maxAgents is a lifetime total cap for every wf.runAgent, wf.spawnAgent, and wf.synthesize call in the whole run, not the parallel lane count; reserve enough for all phases plus synthesis","- Do not set tokenBudget unless the user explicitly asks for a token/resource budget; omit it for normal complex work","- readOnly must be a JSON boolean","- optional mayUseWorktree when child prompts need isolated worktrees","- patterns must use only supported ids","- Use the same natural language as the task request for manifest description, approvalSummary, child agent prompts, synthesis rubric, and artifact text unless the user explicitly asks otherwise","","Return JSON only."].join(`
14
+ `)}o(B,"buildWorkflowGenerationUserPrompt");async function _e(e,n){let t=M(e),r=q(e);if(t.length===0&&r.length===0)return;let s=n.context?.gitRoot??n.context?.executionCwd??process.cwd(),i=n.context?.executionCwd??s,a=O(s);a.size===0&&await W(s);let c={workingDirectory:i,projectRoot:s,environment:{},executeDynamicContext:n.skillDynamicContext?.execute,disableDynamicContext:n.skillDynamicContext?.disable},u=[...t,...r.filter(l=>!t.includes(l)&&a.has(l))];if(u.length===0)return;let d=[];for(let l of t)if(!a.has(l)){let f=a.list().map(p=>p.name).sort().join(", ");throw new Error(`workflow generation referenced unknown skill "${l}". Available skills: ${f||"(none)"}`)}for(let l of u){let f=await a.loadFull(l),p=await I(f,"",c);if(p.disableModelInvocation)throw new Error(`workflow generation referenced disabled skill "${l}"`);d.push(p.content)}return d.join(`
15
+
16
+ `)}o(_e,"buildWorkflowGenerationSkillContext");function Me(e){let n=["- Replace result.output from wf.runAgent(...) or wf.wait(...) with result.finalText.","- Replace result.output from wf.synthesize(...) with result.text.",'- Replace hardcoded wf.wait("...")/wf.snapshot("...")/wf.send("...", ...)/wf.stop("...", ...) calls with handle.taskId/result.taskId variables.','- Replace wf.wait("agent-name") after wf.runAgent(...) with captured runAgent/parallel results; wf.wait only accepts taskId values from spawnAgent handles.',"- Preserve the existing phase, fan-out, cross-review, and synthesis topology unless that topology itself is invalid; fix API usage instead of collapsing the workflow.","- Keep the outer run() return displayable, such as { synthesis: finalText }.",'- Fix generated JavaScript harness errors, including ReferenceError, wrong wf.* argument shapes, and multi-line prompts/rubrics that need template literals or "\\n".'];return(/\bwf\s*\.\s*output\s*\(/.test(e.previousOutput)||e.error.includes("wf.snapshot(taskId)"))&&n.splice(2,0,"- Replace wf.output(taskId) with wf.snapshot(taskId) for in-flight task snapshots."),[B(e.request,e.skillContext),"","Your previous output failed KodaX workflow validation.",`Repair attempt: ${e.attempt} of ${e.maxAttempts}.`,`Validation error: ${e.error}`,"","Common contract fixes:",...n,"","Previous output:",e.previousOutput,"","Return corrected JSON only. Keep the same task intent, but make the manifest and source valid."].join(`
17
+ `)}o(Me,"buildWorkflowGenerationRepairPrompt");function qe(e){return/(?:token\s*(?:budget|limit|cap)|budget\s*(?:for|of)?\s*tokens?|\b\d+(?:\.\d+)?\s*(?:k|m)?\s*tokens?\b|\d+(?:\.\d+)?\s*(?:k|m)?\s*令牌|(?:tokens?|令牌).{0,12}(?:预算|上限|限制)|(?:预算|上限|限制).{0,12}(?:tokens?|令牌))/i.test(e)}o(qe,"requestExplicitlyMentionsTokenBudget");function Ne(e,n){if(e.tokenBudget===void 0||n===void 0||qe(n))return e;let{tokenBudget:t,...r}=e;return r}o(Ne,"stripImplicitTokenBudget");function Ce(e,n={}){let t=pe(e),r=t.action;if(r==="decline")return{kind:"declined",reason:P(t,"reason"),rawText:e};if(r!=="generate")throw new Error('workflow generation action must be "generate" or "decline"');let s=v(P(t,"source")),i=Ne(ke(g(we(t.manifest)),s),n.request),a=typeof t.approvalSummary=="string"&&t.approvalSummary.trim().length>0?t.approvalSummary:i.description,c=x({manifest:i,source:s}),u=k(s,{manifest:i}).filter(d=>d.severity==="warning");return{kind:"generated",manifest:i,source:s,module:c,scriptSnapshot:{manifest:i,source:s},approvalSummary:a,...u.length>0?{qualityWarnings:u}:{},rawText:e}}o(Ce,"parseWorkflowGeneration");async function je(e){let n=e.request.trim();if(!n)return{kind:"declined",reason:"Workflow request is empty.",rawText:""};let t=oe+1,r=B(n,e.skillContext),s="";for(let i=1;i<=t;i+=1){let a=await e.generateText({system:te,prompt:r,...e.signal?{signal:e.signal}:{}});try{let c=Ce(a,{request:n});return c.kind==="generated"&&await Ie({source:c.source,request:n}),c}catch(c){if(s=c instanceof Error?c.message:String(c),i>=t)break;r=Me({request:n,...e.skillContext?{skillContext:e.skillContext}:{},previousOutput:a,error:s,attempt:i+1,maxAttempts:t})}}throw new Error(`workflow generation did not produce a valid workflow after ${t} attempts. Last validation error: ${s}`)}o(je,"generateWorkflow");async function H(e){let n=E(e.options.provider),t=e.options.modelOverride??e.options.model??n.getModel(),r=e.options.effort?.trim();if(e.timeoutMs!==void 0&&e.timeoutSec!==void 0)throw new Error("workflow generation timeoutSec and timeoutMs cannot both be set");let s=e.timeoutMs??b(e.timeoutSec,"workflow generation timeoutSec")??ue(process.env,e.options.timeouts),i=e.skillContext??await _e(e.request,e.options);return je({request:e.request,...i?{skillContext:i}:{},...e.signal?{signal:e.signal}:{},generateText:o(async a=>{let c=[{role:"user",content:a.prompt}],u=await R({provider:n,model:t,system:a.system,messages:c,querySource:"workflow-generation",timeoutMs:s,...r?{reasoning:{effort:r}}:{},...a.signal?{abortSignal:a.signal}:{}});if(!u.text.trim()){let d=u.error?`: ${u.error.message}`:"",l=u.stopReason==="timeout"?` after ${s}ms`:"";throw new Error(`workflow generation failed (${u.stopReason}${l})${d}`)}return u.text},"generateText")})}o(H,"generateWorkflowFromOptions");var De=2e3,Fe=3;function J(e){let n=k(e.source,{manifest:e.manifest,...e.hostMaxAgents!==void 0?{hostMaxAgents:e.hostMaxAgents}:{}}),t=n.filter(r=>r.severity==="error");if(t.length>0)throw new Error(["inline workflow source failed pre-flight quality validation:",...t.map(r=>r.message)].join(`
18
+ `));return n.filter(r=>r.severity==="warning")}o(J,"splitWorkflowQualityWarnings");function Q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}o(Q,"readSchemaRecord");function S(e){return/(?:items|findings|results|files|paths|tasks|entries)$/i.test(e)?[]:/^(?:ok|valid|verified|passed|success)$/i.test(e)?!0:`Smoke structured ${e}`}o(S,"smokeValueForFieldName");function A(e,n){let t=Q(e);if(!t)return n?S(n):"Smoke structured value";let r=t.enum;if(Array.isArray(r)&&r.length>0)return r[0];let s=Array.isArray(t.type)?t.type[0]:t.type;if(s==="string")return"Smoke structured text";if(s==="integer"||s==="number")return 1;if(s==="boolean")return!0;if(s==="array")return[A(t.items)];if(s==="object"||t.properties!==void 0){let i=Q(t.properties),a={};if(i)for(let[c,u]of Object.entries(i))a[c]=A(u,c);if(Array.isArray(t.required))for(let c of t.required)typeof c=="string"&&a[c]===void 0&&(a[c]=S(c));return a}return n?S(n):"Smoke structured value"}o(A,"smokeStructuredValue");function Ge(){return{nextTask:0,names:new Map,structuredByTaskId:new Map}}o(Ge,"createInlineSmokeTaskStore");function V(e,n){e.nextTask+=1;let t=`inline-smoke-task-${e.nextTask}`;return e.names.set(t,n.name),n.outputSchema!==void 0&&e.structuredByTaskId.set(t,A(n.outputSchema)),{taskId:t,name:n.name}}o(V,"nextInlineSmokeHandle");function w(e,n,t){if(e.names.has(t))return;throw[...e.names.entries()].find(s=>s[1]===t)?new Error(`wf.${n}("${t}") used an agent name, but workflow task APIs require the taskId returned by spawnAgent/runAgent. Store the handle/result and pass handle.taskId or result.taskId.`):new Error(`wf.${n}("${t}") references an unknown workflow task id`)}o(w,"assertInlineSmokeKnownTaskId");function X(e,n){for(let t of n.evidenceRefs??[])if(!(t.startsWith("file:")||t.startsWith("diff:")||t.startsWith("finding:"))){if(t.startsWith("task_id:")){let r=t.slice(8).trim();if(r.length===0)throw new Error(`wf.runAgent("${n.name}") evidenceRefs contains empty task_id: reference`);w(e,"evidenceRefs",r);continue}throw[...e.names.values()].includes(t)?new Error(`wf.runAgent("${n.name}") evidenceRefs contains agent name "${t}". Use "task_id:" + result.taskId from the child result.`):new Error(`wf.runAgent("${n.name}") evidenceRefs contains unsupported ref "${t}". Use file:, diff:, finding:, or task_id:<id>.`)}}o(X,"assertInlineSmokeEvidenceRefs");function Y(e,n){w(e,"wait",n);let t=e.names.get(n)??n,r=e.structuredByTaskId.get(n);return{taskId:n,name:t,status:"completed",finalText:`Smoke result for ${t}: completed, done, verified.`,...r!==void 0?{structured:r}:{}}}o(Y,"inlineSmokeResultFor");function Z(e,n,t){w(e,n,t);let r=e.names.get(t)??t;return{taskId:t,name:r,status:"completed",lastText:`Smoke snapshot for ${r}`}}o(Z,"inlineSmokeSnapshotFor");function ee(e,n){if(e&&n.readOnly===!1)throw new Error(`workflow manifest readOnly=true cannot spawn write-capable child "${n.name}"; set the workflow manifest readOnly=false or use child readOnly:true`)}o(ee,"assertInlineSmokeReadOnly");function Ke(e,n){let t=Ge();return{runId:"run-inline-smoke",args:e,budget:{total:null,spent:o(()=>0,"spent"),remaining:o(()=>1/0,"remaining")},phase:o(async(r,s)=>s(),"phase"),spawnAgent:o(async r=>(ee(n,r),X(t,r),V(t,r)),"spawnAgent"),runAgent:o(async r=>{ee(n,r),X(t,r);let s=V(t,r);return Y(t,s.taskId)},"runAgent"),wait:o(async r=>Y(t,r),"wait"),snapshot:o(async r=>Z(t,"snapshot",r),"snapshot"),output:o(async r=>Z(t,"output",r),"output"),send:o(async r=>{w(t,"send",r)},"send"),stop:o(async r=>{w(t,"stop",r)},"stop"),parallel:o(async r=>Promise.all(r.map(s=>s())),"parallel"),synthesize:o(async()=>({text:"Smoke synthesis: completed, done, verified."}),"synthesize"),workflow:o(async(r,s)=>({synthesis:`Smoke workflow ${r} completed.`,args:s}),"workflow"),artifact:o(async r=>({name:r}),"artifact"),log:o(()=>{},"log")}}o(Ke,"createInlineSmokeWorkflowApi");function ze(e){return["wf.parallel expects an array of thunks","wf.parallel items must be functions","wf.pipeline expects an array as its first argument","references an unknown workflow task id","used an agent name, but workflow task APIs require","evidenceRefs contains empty task_id:","evidenceRefs contains agent name","evidenceRefs contains unsupported ref","result must be awaited before reading","result must be awaited before JSON serialization","result must be awaited before enumerating properties","result must be awaited before assigning properties","result must be awaited before defining properties","result must be awaited before deleting properties","workflow manifest readOnly=true cannot spawn write-capable child"].some(n=>e.includes(n))}o(ze,"isInlineSmokeHardFailure");async function Le(e,n,t){try{await y({source:e,args:n,wf:Ke(n,t),filename:"inline-workflow-smoke.js",timeoutMs:De})}catch(r){let s=r instanceof Error?r.message:String(r);if(ze(s))throw new Error(`inline workflow source failed pre-flight smoke validation: ${s}`)}}o(Le,"assertInlineWorkflowSmoke");async function Ue(e){let n=e.source;if(n.kind==="saved")return{module:n.module};if(n.kind==="inline"){let c=g(n.manifest);v(n.source),await Le(n.source,e.args,c.readOnly===!0);let u=J({source:n.source,manifest:c,...e.options.workflowHostPolicy?.maxAgents!==void 0?{hostMaxAgents:e.options.workflowHostPolicy.maxAgents}:{}});return{module:x({manifest:c,source:n.source}),scriptSnapshot:{manifest:c,source:n.source},...u.length>0?{qualityWarnings:u}:{}}}let r=await(e.generateWorkflow??H)({request:n.request,options:e.options});if(r.kind==="declined")return{declined:r.reason};let s=J({source:r.source,manifest:r.manifest,...e.options.workflowHostPolicy?.maxAgents!==void 0?{hostMaxAgents:e.options.workflowHostPolicy.maxAgents}:{}}),i=new Set,a=[...r.qualityWarnings??[],...s].filter(c=>{let u=`${c.code}
19
+ ${c.message}`;return i.has(u)?!1:(i.add(u),!0)});return{module:r.module,scriptSnapshot:r.scriptSnapshot,...a.length>0?{qualityWarnings:a}:{}}}o(Ue,"resolveModule");function Be(e){if(!e||e.length===0)return;let n=e.slice(0,Fe);return{workflowQualityWarningCount:String(e.length),workflowQualityWarningCodes:[...new Set(e.map(t=>t.code))].join(","),workflowQualityWarnings:n.map(t=>`${t.code}: ${t.message}`).join(" | ")}}o(Be,"workflowQualityWarningMetadata");function He(e,n){let t=Be(n);return t?{...e,hostMetadata:{...e?.hostMetadata??{},...t}}:e}o(He,"withWorkflowQualityWarningMetadata");async function ot(e){let n=await Ue(e);if("declined"in n)return{kind:"declined",reason:n.declined};let{module:t,scriptSnapshot:r,qualityWarnings:s}=n,i=e.now??(()=>Date.now()),a=e.runId??`run-${i().toString(36)}`,c=Pe(e.runsBaseDir,a),u=e.manager??C(),d=N(t,e.options.workflowHostPolicy),l=u.startFromOptions({module:t,args:e.args,options:e.options,runId:a,runDir:c,...r?{scriptSnapshot:r}:{},...e.resumeFromRunDir?{resumeFromRunDir:e.resumeFromRunDir}:{},...(()=>{let f=He(e.processMetadata,s);return f?{processMetadata:f}:{}})(),...e.approval?{approval:e.approval}:{},...e.onEvent?{onEvent:e.onEvent}:{},...e.signal?{signal:e.signal}:{}});return{kind:"started",runId:a,runDir:c,module:t,managed:l,approvalSummary:d,...r?{scriptSnapshot:r}:{},...s!==void 0?{qualityWarnings:s}:{}}}o(ot,"startManagedWorkflow");export{te as a,j as b,ue as c,v as d,B as e,_e as f,Ce as g,je as h,H as i,ot as j};