@kodax-ai/kodax 0.7.56 → 0.7.58

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 (79) hide show
  1. package/CHANGELOG.md +2004 -1887
  2. package/README.md +52 -48
  3. package/README_CN.md +37 -32
  4. package/dist/builtin/code-review/SKILL.md +22 -3
  5. package/dist/chunks/agent-YJNC2755.js +2 -0
  6. package/dist/chunks/argument-completer-QGBNXTYJ.js +2 -0
  7. package/dist/chunks/chunk-526OILYL.js +2 -0
  8. package/dist/chunks/{chunk-ZBK3DZ3S.js → chunk-6AU6EPO6.js} +1 -1
  9. package/dist/chunks/chunk-73Z7BK5H.js +15 -0
  10. package/dist/chunks/chunk-7QB55SYG.js +326 -0
  11. package/dist/chunks/chunk-CQ6EQG7E.js +322 -0
  12. package/dist/chunks/chunk-CV6JHPEO.js +2 -0
  13. package/dist/chunks/chunk-D6QVXQNI.js +1 -0
  14. package/dist/chunks/chunk-HS2K74I4.js +31 -0
  15. package/dist/chunks/chunk-NKHXRN7G.js +403 -0
  16. package/dist/chunks/chunk-OBPB5BQ6.js +310 -0
  17. package/dist/chunks/chunk-P4VF3JEP.js +7 -0
  18. package/dist/chunks/chunk-PIQWODWN.js +18 -0
  19. package/dist/chunks/chunk-QHWXPJEG.js +601 -0
  20. package/dist/chunks/chunk-XXEIFNBE.js +52 -0
  21. package/dist/chunks/chunk-ZZDC75H4.js +681 -0
  22. package/dist/chunks/compaction-config-OPMRZSAK.js +2 -0
  23. package/dist/chunks/{construction-bootstrap-EDDVNP2B.js → construction-bootstrap-CIXFH5SE.js} +4 -4
  24. package/dist/chunks/dist-JSE7NICF.js +2 -0
  25. package/dist/chunks/dist-SDNQOW52.js +2 -0
  26. package/dist/chunks/host-H7FQMMRC.js +2 -0
  27. package/dist/chunks/{paste-5IDBBQQ3.js → paste-Y4DVUWSM.js} +1 -1
  28. package/dist/chunks/run-manager-4H5HWMVW.js +2 -0
  29. package/dist/chunks/utils-FLVVQHM7.js +2 -0
  30. package/dist/index.d.ts +22 -18
  31. package/dist/index.js +6 -6
  32. package/dist/kodax_cli.js +1303 -1108
  33. package/dist/provider-capabilities.json +986 -197
  34. package/dist/sdk-agent.d.ts +162 -14
  35. package/dist/sdk-agent.js +1 -1
  36. package/dist/sdk-coding.d.ts +285 -255
  37. package/dist/sdk-coding.js +1 -1
  38. package/dist/sdk-llm.d.ts +66 -43
  39. package/dist/sdk-llm.js +1 -1
  40. package/dist/sdk-mcp.d.ts +1 -1
  41. package/dist/sdk-mcp.js +1 -1
  42. package/dist/sdk-media.d.ts +64 -5
  43. package/dist/sdk-media.js +1 -1
  44. package/dist/sdk-repl.d.ts +114 -107
  45. package/dist/sdk-repl.js +2 -2
  46. package/dist/sdk-session.d.ts +7 -7
  47. package/dist/sdk-session.js +1 -1
  48. package/dist/sdk-skills.js +1 -1
  49. package/dist/semantic-worker.js +11 -0
  50. package/dist/types-chunks/{base.d-CwPfI8WQ.d.ts → base.d-BA9Doaj_.d.ts} +38 -8
  51. package/dist/types-chunks/{bash-prefix-extractor.d-DZF1gDDz.d.ts → bash-prefix-extractor.d-D3cddmyV.d.ts} +639 -163
  52. package/dist/types-chunks/capability-learning.d-DRV80ISB.d.ts +29 -0
  53. package/dist/types-chunks/{cost-tracker.d-wRtyEW9d.d.ts → cost-tracker.d-CBLk1fiD.d.ts} +24 -2
  54. package/dist/types-chunks/{guardrail.d-DQQknOfb.d.ts → guardrail.d-iK7FwMdW.d.ts} +32 -10
  55. package/dist/types-chunks/{manager.d-DLmDhX3i.d.ts → manager.d-DBD7SOTT.d.ts} +7 -2
  56. package/dist/types-chunks/{process.d-BdiIUr8T.d.ts → process.d-DHow2y2G.d.ts} +170 -14
  57. package/dist/types-chunks/{resolver.d-Djq8KlCE.d.ts → resolver.d-DDOfVYDr.d.ts} +111 -18
  58. package/dist/types-chunks/{capsule.d-D0kjnqYy.d.ts → run-manager.d-ByDcJc5g.d.ts} +124 -13
  59. package/dist/types-chunks/{sdk-session-BP6ZNpOp.d.ts → sdk-session-21Tt3N_x.d.ts} +74 -9
  60. package/dist/types-chunks/{storage.d-CkydxFsV.d.ts → storage.d-BsZrBPYu.d.ts} +2 -2
  61. package/dist/types-chunks/{types.d-BJmoMf5H.d.ts → types.d-Ci5YPFEh.d.ts} +135 -22
  62. package/dist/types-chunks/{types.d-BKuHSiR0.d.ts → types.d-D4ZA8LJV.d.ts} +7 -3
  63. package/dist/types-chunks/{utils.d-bC97IuQZ.d.ts → utils.d-BURxOxFd.d.ts} +94 -19
  64. package/package.json +12 -7
  65. package/dist/chunks/agent-MAAKRAF2.js +0 -2
  66. package/dist/chunks/argument-completer-OWEXGWNL.js +0 -2
  67. package/dist/chunks/chunk-4OHXHC2S.js +0 -314
  68. package/dist/chunks/chunk-5YJIAP6C.js +0 -551
  69. package/dist/chunks/chunk-7EAGBLRV.js +0 -2
  70. package/dist/chunks/chunk-CDGOEK3T.js +0 -31
  71. package/dist/chunks/chunk-DHETLULC.js +0 -425
  72. package/dist/chunks/chunk-JCDO2FR4.js +0 -584
  73. package/dist/chunks/chunk-NZVJ3DFC.js +0 -656
  74. package/dist/chunks/chunk-QI3MRJGU.js +0 -5
  75. package/dist/chunks/chunk-XXQ3RLA2.js +0 -2
  76. package/dist/chunks/compaction-config-NAJEEPG5.js +0 -2
  77. package/dist/chunks/dist-2267YGB5.js +0 -2
  78. package/dist/chunks/dist-GW32CHO5.js +0 -2
  79. package/dist/chunks/utils-J7XBBZGB.js +0 -2
@@ -0,0 +1,15 @@
1
+ // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
+ import{t as W,z as $}from"./chunk-PIQWODWN.js";import{Da as _,Ea as I}from"./chunk-7QB55SYG.js";import{Ja as b,_a as v,j as k,k as x}from"./chunk-HS2K74I4.js";import{$d as A,Qc as S,Rc as E,Wc as T,ae as w,ce as R,de as O,ee as g}from"./chunk-ZZDC75H4.js";import{a as i}from"./chunk-V4WSBIXB.js";import{join as Re}from"node:path";var L=["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
+ `),M=12e4,B="KODAX_WORKFLOW_GENERATION_TIMEOUT_SEC",U="KODAX_WORKFLOW_GENERATION_TIMEOUT_MS",J=64,H=2,V=2e3,X=[{name:"default"},{name:"variant-results",finalText:i((e,t)=>`Variant smoke child report from ${e} (${t}).`,"finalText"),synthesizeText:"Variant smoke synthesis report."},{name:"unverified-success",status:i(()=>"completed_unverified","status"),finalText:i(e=>`Smoke result for ${e}: completed with verification warnings.`,"finalText"),synthesizeText:"Smoke synthesis: completed with verification warnings."},{name:"empty-args-rerun",args:i(()=>({}),"args")}],Q=["- 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."],Y=[{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*(?:\.|\[)/}];function Z(e=process.env,t){let n=k(t?.workflow?.generationTimeoutSec,"timeouts.workflow.generationTimeoutSec");if(n!==void 0)return n;let r=x(e[B]);if(r!==void 0)return r;let s=e[U];if(s===void 0||s.trim().length===0)return M;let o=Number(s);return!Number.isFinite(o)||o<=0?M:Math.floor(o)}i(Z,"resolveWorkflowGenerationTimeoutMs");function ee(e,t){if(typeof e!="object"||e===null)throw new Error(`${t} must be an object`);return e}i(ee,"readRecord");function q(e,t){let n=e[t];if(typeof n!="string"||n.trim().length===0)throw new Error(`workflow generation ${t} must be a non-empty string`);return n}i(q,"readNonEmptyString");function te(e){let t=e.trim(),n=/^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(t);if(n?.[1])return n[1].trim();let r=t.indexOf("{"),s=t.lastIndexOf("}");if(r>=0&&s>r)return t.slice(r,s+1);throw new Error("workflow generation output did not contain a JSON object")}i(te,"extractJsonText");function ne(e){let t=te(e);return ee(JSON.parse(t),"workflow generation output")}i(ne,"parseGenerationJson");function re(e){if(typeof e=="string"){let n=e.trim();return n.length>0?n:void 0}if(typeof e!="object"||e===null)return;let t=e;for(let n of["name","id","title","phase"]){let r=t[n];if(typeof r=="string"&&r.trim().length>0)return r.trim()}}i(re,"normalizePhaseEntry");function se(e){return e.split(/(?:->|\u2192|,|\n)/).map(t=>t.trim()).filter(t=>t.length>0)}i(se,"splitPhaseString");function oe(e){if(typeof e!="object"||e===null)return e;let t=e,n=t.phases,r;if(Array.isArray(n)){let s=n.map(re);s.every(o=>o!==void 0)&&(r=s)}else if(typeof n=="string"){let s=se(n);s.length>0&&(r=s)}return r?{...t,phases:r}:e}i(oe,"normalizeGeneratedManifestCandidate");function ie(e){return e.match(/\bwf\.(?:runAgent|spawnAgent|synthesize)\s*\(/g)?.length??0}i(ie,"estimateDirectAgentCalls");function ae(e,t){let n=e.maxConcurrency*Math.max(1,e.phases.length)+2,r=ie(t)+2,s=Math.min(J,Math.max(e.maxAgents,n,r));return s>e.maxAgents?{...e,maxAgents:s}:e}i(ae,"reserveGeneratedWorkflowAgentCapacity");function m(e){let t="",n=0;for(;n<e.length;){let r=e[n],s=e[n+1];if(r==="/"&&s==="/"){for(t+=" ",n+=2;n<e.length&&e[n]!==`
4
+ `;)t+=" ",n+=1;continue}if(r==="/"&&s==="*"){for(t+=" ",n+=2;n<e.length;){if(e[n]==="*"&&e[n+1]==="/"){t+=" ",n+=2;break}t+=e[n]===`
5
+ `?`
6
+ `:" ",n+=1}continue}if(r==='"'||r==="'"||r==="`"){let o=r;for(t+=" ",n+=1;n<e.length;){let l=e[n];if(t+=l===`
7
+ `?`
8
+ `:" ",n+=1,l==="\\"){n<e.length&&(t+=e[n]===`
9
+ `?`
10
+ `:" ",n+=1);continue}if(l===o)break}continue}t+=r??"",n+=1}return t}i(m,"stripGeneratedSourceLiterals");function le(e,t){for(let n=t+1;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="`")return!1;if(r==="$"&&e[n+1]==="{")return!0}return!1}i(le,"templateLiteralHasExpression");function ce(e){let t=m(e),n=/\bwf\s*\.\s*(wait|snapshot|send|stop)\s*\(/g,r;for(;(r=n.exec(t))!==null;){let s=r[1];if(!s)continue;let o=t.indexOf("(",r.index);if(o<0)continue;let l=o+1;for(;/\s/.test(e[l]??"");)l+=1;let f=e[l];if(!(f==="`"&&le(e,l))&&(f==='"'||f==="'"||f==="`"))return{method:s}}}i(ce,"findLiteralWorkflowTaskTarget");function N(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(N,"isIdentifierPart");function j(e){let t=m(e),n=/\basync\s+function\s+run\s*\([^)]*\)\s*\{/.exec(t);if(!n)return;let r=t.indexOf("{",n.index);if(r<0)return;let s=0;for(let o=r;o<t.length;o+=1){let l=t[o];if(l==="{"&&(s+=1),l==="}"&&(s-=1,s===0))return{start:r+1,end:o}}}i(j,"findRunBodyRange");function D(e,t){let n=m(e),r=1;for(let s=t.start;s<t.end;s+=1){let o=n[s];if(o==="{"){r+=1;continue}if(o==="}"){r-=1;continue}if(r===1&&n.startsWith("return",s)&&!N(n[s-1])&&!N(n[s+6])){let l=s+6,f=0;for(let u=l;u<t.end;u+=1){let p=n[u];if((p==="("||p==="["||p==="{")&&(f+=1),(p===")"||p==="]"||p==="}")&&(f-=1),f===0&&(p===";"||p===`
11
+ `||p==="\r"))return e.slice(l,u).trim()}return e.slice(l,t.end).trim()}}}i(D,"findTopLevelReturnExpression");function F(e){let t=j(e);if(t)return D(e,t)}i(F,"findOuterRunReturnExpression");function fe(e){let t=j(e);if(!t)return[];let n=m(e),r=[],s=t.start,o=1;for(let f=t.start;f<t.end;f+=1){let u=n[f];if(u==="{"||u==="("||u==="["){o+=1;continue}if(u==="}"||u===")"||u==="]"){o-=1;continue}if(u===";"&&o===1){let p=e.slice(s,f+1).trim();p&&r.push(p),s=f+1}}let l=e.slice(s,t.end).trim();return l&&r.push(l),r}i(fe,"findOuterRunStatements");function ue(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(ue,"escapeRegExp");function de(e,t){let n=/^[A-Za-z_$][A-Za-z0-9_$]*$/.exec(t.trim())?.[0];if(!n)return!1;let r=ue(n),s=new RegExp(`^\\s*(?:const|let|var)\\s+${r}\\s*=\\s*(?:await\\s+)?wf\\s*\\.\\s*artifact\\b`),o=new RegExp(`^\\s*${r}\\s*=\\s*(?:await\\s+)?wf\\s*\\.\\s*artifact\\b`);return fe(e).some(l=>s.test(l)||o.test(l))}i(de,"isReturnedArtifactHandle");function C(e,t,n,r){let s=0;for(let o=t;o<e.length;o+=1){let l=e[o];if(l===n&&(s+=1),l===r&&(s-=1,s===0))return o}}i(C,"findMatchingDelimiter");function pe(e,t,n){let r=0;for(let s=t;s<n;s+=1){let o=e[s];if(o==="("||o==="["||o==="{"){r+=1;continue}if(o===")"||o==="]"||o==="}"){r-=1;continue}if(o===","&&r===0)return s}}i(pe,"findTopLevelComma");function he(e){let t=m(e),n=/^\s*(?:await\s+)?wf\s*\.\s*phase\s*\(/.exec(t);if(!n)return;let r=t.indexOf("(",n.index);if(r<0)return;let s=C(t,r,"(",")");if(s===void 0)return;let o=pe(t,r+1,s);if(o===void 0)return;let l=e.slice(o+1,s).trim(),f=m(l),u=f.indexOf("=>");if(u<0)return;let p=u+2,a=f.slice(p).search(/\S/);if(a<0)return;let c=p+a;if(f[c]!=="{")return l.slice(c).trim();let d=C(f,c,"{","}");if(d!==void 0)return D(l,{start:c+1,end:d})}i(he,"findPhaseCallbackReturnExpression");function P(e,t){return new RegExp(`^(?:await\\s+)?wf\\s*\\.\\s*${t}\\b`).test(e.trim())}i(P,"isDirectWorkflowCall");function G(e,t){let n=t.trim();if(/^(?:undefined|null|void\s+0|\{\s*\}|\[\s*\]|''|""|``)$/.test(n)||P(n,"artifact")||de(e,n))return!1;if(P(n,"phase")){let r=he(n);return r!==void 0&&G(n,r)}return!0}i(G,"isDisplayableReturnExpression");function me(e){let t=F(e);return t?G(e,t):!1}i(me,"hasDisplayableRunReturn");function we(e){try{R(e,{filename:"generated-workflow.js",requireAsyncRun:!0,checkSourcePolicy:!1})}catch(t){let n=t instanceof Error?t.message:String(t),s=/Unexpected (identifier|string|token|end of input)|Invalid or unexpected token/i.test(n)?" \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: ${n}${s}`)}}i(we,"assertGeneratedWorkflowSyntax");function ge(e){let t=0,n=new Map,r=[],s=i(a=>{t+=1;let c=`smoke-task-${t}-${Math.random().toString(36).slice(2,8)}`;return n.set(c,a),{taskId:c,name:a}},"nextHandle"),o=i((a,c)=>{if(n.has(c))return;throw[...n.entries()].find(h=>h[1]===c)?new Error(`wf.${a}("${c}") 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.${a}("${c}") references an unknown workflow task id`)},"assertKnownTaskId"),l=i(a=>{for(let c of a.evidenceRefs??[]){if(c.startsWith("file:")||c.startsWith("diff:")||c.startsWith("finding:"))continue;if(c.startsWith("task_id:")){let h=c.slice(8).trim();if(h.length===0)throw new Error(`wf.runAgent("${a.name}") evidenceRefs contains empty task_id: reference`);o("evidenceRefs",h);continue}throw[...n.entries()].find(h=>h[1]===c)?new Error(`wf.runAgent("${a.name}") evidenceRefs contains agent name "${c}". Use "task_id:" + result.taskId from the child result.`):new Error(`wf.runAgent("${a.name}") evidenceRefs contains unsupported ref "${c}". Use file:, diff:, finding:, or task_id:<id>.`)}},"assertEvidenceRefs"),f=i((a,c)=>{o("wait",a);let d=n.get(a)??c??a,h=e.status?.(d,a)??"completed";return{taskId:a,name:d,status:h,finalText:e.finalText?.(d,a)??`Smoke result for ${d}: completed, done, verified.`}},"resultFor"),u=i((a,c)=>{o(a,c);let d=n.get(c)??c;return{taskId:c,name:d,status:"completed",lastText:`Smoke snapshot for ${d}`}},"snapshotFor");return{api:{runId:"run-smoke",args:void 0,budget:{total:null,spent:i(()=>0,"spent"),remaining:i(()=>1/0,"remaining")},phase:i(async(a,c)=>c(),"phase"),spawnAgent:i(async a=>(l(a),s(a.name)),"spawnAgent"),runAgent:i(async a=>{l(a);let c=s(a.name),d=f(c.taskId,a.name);if(d.status==="failed"||d.status==="stopped")throw new Error(`workflow task ${d.name} (${d.taskId}) ${d.status}`);return d},"runAgent"),wait:i(async a=>f(a),"wait"),snapshot:i(async a=>u("snapshot",a),"snapshot"),output:i(async a=>u("output",a),"output"),send:i(async a=>{o("send",a)},"send"),stop:i(async a=>{o("stop",a)},"stop"),parallel:i(async a=>Promise.all(a.map(c=>c())),"parallel"),synthesize:i(async()=>({text:e.synthesizeText??"Smoke synthesis: completed, done, verified."}),"synthesize"),artifact:i(async a=>(r.push(a),{name:a}),"artifact"),log:i(()=>{},"log")},artifactCount:i(()=>r.length,"artifactCount")}}i(ge,"createSmokeWorkflowApi");function ke(e,t){if(t>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 n=e,r=!1,s=n.synthesis;if(typeof s=="string"&&(r=!0,s.trim().length>0))return!0;if(s&&typeof s=="object"){r=!0;let o=s.text;if(typeof o=="string"&&o.trim().length>0)return!0}for(let o of["summary","report","text","result"]){let l=n[o];if(l!==void 0&&(r=!0),typeof l=="string"&&l.trim().length>0)return!0}return r&&Object.keys(n).every(o=>o==="synthesis"||o==="summary"||o==="report"||o==="text"||o==="result")?!1:Object.keys(n).length>0}i(ke,"isSmokeResultDisplayable");async function ye(e){for(let t of X)try{let n=ge(t),r=await O({source:e.source,wf:n.api,args:t.args?.(e.request)??{request:e.request},filename:"generated-workflow-smoke.js",timeoutMs:V});if(!ke(r,n.artifactCount()))throw new Error("run() returned no displayable result or artifact")}catch(n){let r=n instanceof Error?n.message:String(n);throw new Error(`workflow generation source failed safe smoke validation (${t.name}): ${r}`)}}i(ye,"assertGeneratedWorkflowSmoke");function y(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)");we(e);let t=m(e);for(let r of Y)if(r.pattern.test(t))throw new Error(`forbidden generated workflow token: ${r.id}`);if(/\.\s*output\b/.test(t))throw/\bwf\s*\.\s*output\s*\(/.test(t)?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 n=ce(e);if(n)throw new Error(`workflow generation source must pass taskId variables to wf.${n.method}(...) instead of string literals; use handle.taskId from wf.spawnAgent(...) or result.taskId from wf.runAgent(...).`);for(let r of t.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(!me(e)){let r=F(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}i(y,"validateGeneratedWorkflowSource");function xe(e){let t=e?.trim();return t?["","Referenced skill instructions (authoritative):",t,"","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.']:[]}i(xe,"buildReferencedSkillPromptSection");function z(e,t){return["Task request:",e,...xe(t),"","Available WorkflowApi calls:","- wf.phase(name, async () => ...)","- wf.spawnAgent({ name, prompt, readOnly, modelHint, isolation, evidenceRefs, verification })","- wf.runAgent({ name, prompt, readOnly, modelHint, isolation, evidenceRefs, verification })","- 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, digest?, verification?, usage }; wf.snapshot returns { taskId, name, status, lastText? }; wf.synthesize returns { text }; wf.artifact returns { name, path? }.","- 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 };","}","","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: ${A.join(", ")}`,"","Pattern selection guidance:",...Q,"- 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(`
12
+ `)}i(z,"buildWorkflowGenerationUserPrompt");async function be(e,t){let n=_(e),r=I(e);if(n.length===0&&r.length===0)return;let s=t.context?.gitRoot??t.context?.executionCwd??process.cwd(),o=t.context?.executionCwd??s,l=S(s);l.size===0&&await E(s);let f={workingDirectory:o,projectRoot:s,environment:{}},u=[...n,...r.filter(a=>!n.includes(a)&&l.has(a))];if(u.length===0)return;let p=[];for(let a of n)if(!l.has(a)){let c=l.list().map(d=>d.name).sort().join(", ");throw new Error(`workflow generation referenced unknown skill "${a}". Available skills: ${c||"(none)"}`)}for(let a of u){let c=await l.loadFull(a),d=await T(c,"",f);if(d.disableModelInvocation)throw new Error(`workflow generation referenced disabled skill "${a}"`);p.push(d.content)}return p.join(`
13
+
14
+ `)}i(be,"buildWorkflowGenerationSkillContext");function ve(e){let t=["- 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)"))&&t.splice(2,0,"- Replace wf.output(taskId) with wf.snapshot(taskId) for in-flight task snapshots."),[z(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:",...t,"","Previous output:",e.previousOutput,"","Return corrected JSON only. Keep the same task intent, but make the manifest and source valid."].join(`
15
+ `)}i(ve,"buildWorkflowGenerationRepairPrompt");function Se(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)}i(Se,"requestExplicitlyMentionsTokenBudget");function Ee(e,t){if(e.tokenBudget===void 0||t===void 0||Se(t))return e;let{tokenBudget:n,...r}=e;return r}i(Ee,"stripImplicitTokenBudget");function Te(e,t={}){let n=ne(e),r=n.action;if(r==="decline")return{kind:"declined",reason:q(n,"reason"),rawText:e};if(r!=="generate")throw new Error('workflow generation action must be "generate" or "decline"');let s=y(q(n,"source")),o=Ee(ae(w(oe(n.manifest)),s),t.request),l=typeof n.approvalSummary=="string"&&n.approvalSummary.trim().length>0?n.approvalSummary:o.description;return{kind:"generated",manifest:o,source:s,module:g({manifest:o,source:s}),scriptSnapshot:{manifest:o,source:s},approvalSummary:l,rawText:e}}i(Te,"parseWorkflowGeneration");async function Ae(e){let t=e.request.trim();if(!t)return{kind:"declined",reason:"Workflow request is empty.",rawText:""};let n=H+1,r=z(t,e.skillContext),s="";for(let o=1;o<=n;o+=1){let l=await e.generateText({system:L,prompt:r,...e.signal?{signal:e.signal}:{}});try{let f=Te(l,{request:t});return f.kind==="generated"&&await ye({source:f.source,request:t}),f}catch(f){if(s=f instanceof Error?f.message:String(f),o>=n)break;r=ve({request:t,...e.skillContext?{skillContext:e.skillContext}:{},previousOutput:l,error:s,attempt:o+1,maxAttempts:n})}}throw new Error(`workflow generation did not produce a valid workflow after ${n} attempts. Last validation error: ${s}`)}i(Ae,"generateWorkflow");async function K(e){let t=b(e.options.provider),n=e.options.modelOverride??e.options.model??t.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??k(e.timeoutSec,"workflow generation timeoutSec")??Z(process.env,e.options.timeouts),o=e.skillContext??await be(e.request,e.options);return Ae({request:e.request,...o?{skillContext:o}:{},...e.signal?{signal:e.signal}:{},generateText:i(async l=>{let f=[{role:"user",content:l.prompt}],u=await v({provider:t,model:n,system:l.system,messages:f,querySource:"workflow-generation",timeoutMs:s,...r?{reasoning:{effort:r}}:{},...l.signal?{abortSignal:l.signal}:{}});if(!u.text.trim()){let p=u.error?`: ${u.error.message}`:"",a=u.stopReason==="timeout"?` after ${s}ms`:"";throw new Error(`workflow generation failed (${u.stopReason}${a})${p}`)}return u.text},"generateText")})}i(K,"generateWorkflowFromOptions");async function Oe(e){let t=e.source;if(t.kind==="saved")return{module:t.module};if(t.kind==="inline"){let s=w(t.manifest);return y(t.source),{module:g({manifest:s,source:t.source}),scriptSnapshot:{manifest:s,source:t.source}}}let r=await(e.generateWorkflow??K)({request:t.request,options:e.options});return r.kind==="declined"?{declined:r.reason}:{module:r.module,scriptSnapshot:r.scriptSnapshot}}i(Oe,"resolveModule");async function Fe(e){let t=await Oe(e);if("declined"in t)return{kind:"declined",reason:t.declined};let{module:n,scriptSnapshot:r}=t,s=e.now??(()=>Date.now()),o=e.runId??`run-${s().toString(36)}`,l=Re(e.runsBaseDir,o),f=e.manager??$(),u=W(n,e.options.workflowHostPolicy),p=f.startFromOptions({module:n,args:e.args,options:e.options,runId:o,runDir:l,...r?{scriptSnapshot:r}:{},...e.resumeFromRunDir?{resumeFromRunDir:e.resumeFromRunDir}:{},...e.processMetadata?{processMetadata:e.processMetadata}:{},...e.approval?{approval:e.approval}:{},...e.onEvent?{onEvent:e.onEvent}:{},...e.signal?{signal:e.signal}:{}});return{kind:"started",runId:o,runDir:l,module:n,managed:p,approvalSummary:u,...r?{scriptSnapshot:r}:{}}}i(Fe,"startManagedWorkflow");export{L as a,M as b,Z as c,y as d,z as e,be as f,Te as g,Ae as h,K as i,Fe as j};