@kodax-ai/kodax 0.7.60 → 0.7.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -1
- package/README.md +2 -0
- package/README_CN.md +2 -0
- package/dist/chunks/{agent-L5FC3YOY.js → agent-E74WVAFR.js} +1 -1
- package/dist/chunks/argument-completer-BBFYCVTM.js +2 -0
- package/dist/chunks/{chunk-5TRQBMPR.js → chunk-2OEKUAV4.js} +1 -1
- package/dist/chunks/{chunk-ZPD7IUKW.js → chunk-4NSOBQCU.js} +1 -1
- package/dist/chunks/{chunk-QFCF3GNT.js → chunk-7COB3EKF.js} +171 -156
- package/dist/chunks/chunk-CGGX3FXE.js +19 -0
- package/dist/chunks/{chunk-6DWXUZMO.js → chunk-D7CC6YZC.js} +198 -198
- package/dist/chunks/{chunk-SGNM3UP6.js → chunk-KIVYMSRH.js} +1 -1
- package/dist/chunks/chunk-NJW2LQOP.js +722 -0
- package/dist/chunks/{chunk-IJN6ZJVI.js → chunk-PJXKBM3Y.js} +4 -4
- package/dist/chunks/{chunk-2RLIKZOZ.js → chunk-QCBKLNN5.js} +2 -2
- package/dist/chunks/{chunk-XULI4U7I.js → chunk-XHOPSZVL.js} +1 -1
- package/dist/chunks/{compaction-config-E4LN3M53.js → compaction-config-GESEZQVA.js} +1 -1
- package/dist/chunks/{construction-bootstrap-GIFDM4L5.js → construction-bootstrap-OSXHEIBB.js} +1 -1
- package/dist/chunks/{dist-7PXDYX2R.js → dist-W3OOJP66.js} +1 -1
- package/dist/chunks/host-FRQXOEHH.js +2 -0
- package/dist/chunks/{run-manager-IU5COC6X.js → run-manager-FGCG7DFF.js} +1 -1
- package/dist/chunks/{utils-NP42DKL3.js → utils-47QI5MSP.js} +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/kodax_cli.js +927 -909
- package/dist/sdk-agent.d.ts +2 -2
- package/dist/sdk-agent.js +1 -1
- package/dist/sdk-coding.d.ts +6 -4
- package/dist/sdk-coding.js +1 -1
- package/dist/sdk-mcp.js +1 -1
- package/dist/sdk-repl.d.ts +6 -6
- package/dist/sdk-repl.js +1 -1
- package/dist/sdk-session.d.ts +3 -3
- package/dist/sdk-session.js +1 -1
- package/dist/sdk-skills.js +1 -1
- package/dist/types-chunks/{bash-prefix-extractor.d-Ds1THKeH.d.ts → bash-prefix-extractor.d-e1LD2IRl.d.ts} +7 -0
- package/dist/types-chunks/{run-manager.d-DLK3ed-T.d.ts → run-manager.d-DHPlNYkK.d.ts} +16 -2
- package/dist/types-chunks/{sdk-session-CtwN7iBO.d.ts → sdk-session-DINrM1pF.d.ts} +2 -2
- package/dist/types-chunks/{storage.d-DlZS0g8w.d.ts → storage.d-xiw7Vgx0.d.ts} +1 -1
- package/dist/types-chunks/{utils.d-Boz9k2HB.d.ts → utils.d-Dy19-1XR.d.ts} +2 -2
- package/package.json +1 -1
- package/dist/chunks/argument-completer-BQDAYT7W.js +0 -2
- package/dist/chunks/chunk-4K5BDO7S.js +0 -721
- package/dist/chunks/chunk-U6BNMGSK.js +0 -17
- package/dist/chunks/host-FLG7FJZT.js +0 -2
|
@@ -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-QCBKLNN5.js";import{Da as M,Ea as q}from"./chunk-7COB3EKF.js";import{$a as R,Ja as E,j as b,k as T}from"./chunk-S4GVQO3W.js";import{$d as $,Qc as O,Rc as W,Wc as I,ae as g,be as k,ee as _,fe as y,ge as x}from"./chunk-NJW2LQOP.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};
|