@kodax-ai/kodax 0.7.51 → 0.7.52
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 +20 -6
- package/dist/chunks/{agent-EFA7BSE7.js → agent-XXTR7T37.js} +1 -1
- package/dist/chunks/{argument-completer-MAJVHSE7.js → argument-completer-VMH6VZ4X.js} +1 -1
- package/dist/chunks/{chunk-E3HENKTX.js → chunk-4RVSFOUT.js} +3 -3
- package/dist/chunks/{chunk-WQTVG2T5.js → chunk-5USNUSTL.js} +3 -3
- package/dist/chunks/{chunk-ODVA5VTE.js → chunk-7X7SOVER.js} +2 -2
- package/dist/chunks/{chunk-CCZMQE3Q.js → chunk-BFXFSEHK.js} +1 -1
- package/dist/chunks/chunk-LE6STNVN.js +31 -0
- package/dist/chunks/{chunk-FAIGYAEX.js → chunk-MFPYZT52.js} +4 -4
- package/dist/chunks/{construction-bootstrap-WY5MDXRX.js → construction-bootstrap-BXRMA3KL.js} +1 -1
- package/dist/chunks/{dist-BTWS2ENP.js → dist-IHH4BYIU.js} +1 -1
- package/dist/chunks/{dist-B73FQEAA.js → dist-Z6U7TWKJ.js} +1 -1
- package/dist/chunks/{utils-HVOJRR5C.js → utils-6WZHBMCC.js} +1 -1
- package/dist/index.d.ts +10 -10
- package/dist/index.js +1 -1
- package/dist/kodax_cli.js +628 -628
- package/dist/sdk-agent.d.ts +8 -8
- package/dist/sdk-coding.d.ts +12 -12
- package/dist/sdk-coding.js +1 -1
- package/dist/sdk-llm.d.ts +3 -3
- package/dist/sdk-llm.js +1 -1
- package/dist/sdk-repl.d.ts +10 -10
- package/dist/sdk-repl.js +1 -1
- package/dist/sdk-session.d.ts +5 -5
- package/dist/sdk-session.js +1 -1
- package/dist/types-chunks/{base.d-GZ6jvICS.d.ts → base.d-BBNUF9nz.d.ts} +1 -0
- package/dist/types-chunks/{bash-prefix-extractor.d-DTOiDMlG.d.ts → bash-prefix-extractor.d-DBFZEwop.d.ts} +2 -2
- package/dist/types-chunks/{capsule.d-CXGdLGAn.d.ts → capsule.d-CNonpwAZ.d.ts} +3 -3
- package/dist/types-chunks/{guardrail.d-D47yu9AO.d.ts → guardrail.d-B18oO1gt.d.ts} +3 -3
- package/dist/types-chunks/{process.d-B8kEBnQD.d.ts → process.d-Bj82oJhD.d.ts} +1 -1
- package/dist/types-chunks/{resolver.d-D75XFRH2.d.ts → resolver.d-CCX9NXWP.d.ts} +2 -1
- package/dist/types-chunks/{sdk-session-BKQJN9oH.d.ts → sdk-session-D4tqRl0_.d.ts} +4 -4
- package/dist/types-chunks/{storage.d-BN1xIn8R.d.ts → storage.d-CabW10Nt.d.ts} +2 -2
- package/dist/types-chunks/{types.d-DQ_hdN70.d.ts → types.d-D4jL-gAA.d.ts} +1 -1
- package/dist/types-chunks/{utils.d-ZfRDo-kX.d.ts → utils.d-23Gn14zP.d.ts} +5 -5
- package/package.json +2 -2
- package/dist/chunks/chunk-PEWH3AAL.js +0 -31
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,20 @@ All notable changes to this project will be documented in this file.
|
|
|
4
4
|
|
|
5
5
|
> Full history for versions prior to v0.7.0: [CHANGELOG_ARCHIVE.md](docs/CHANGELOG_ARCHIVE.md)
|
|
6
6
|
|
|
7
|
+
## [0.7.52] - 2026-06-18
|
|
8
|
+
|
|
9
|
+
> Scope note: a maintenance release of fixes landed right after v0.7.51 — OpenAI-compat provider robustness, the Node runtime floor raised to 20, and the cross-platform CI test cleanup. No new features; no LLM-facing prompt changes (ADR-033 eval non-trigger).
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- **Node runtime floor raised to 20 (Node 18 dropped).** The codebase relies on Node 20+ runtime features (notably the RegExp `v`/unicodeSets flag pulled in transitively), so Node 18 could no longer even load large parts of the suite. `engines.node` is now `>=20.0.0` across the root and all four workspace packages, the CI matrix runs Node 20 + 22, and the README/AGENTS/CLAUDE tech-stack tables are updated. The release build continues to run Node 22.
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
|
|
17
|
+
- **Forced `tool_choice` now falls back on upstream 5xx / unsupported-parameter errors.** OpenAI-compat providers that reject a forced `tool_choice` request with a generic 5xx (or an `unsupported parameter: tool_choice` message) now retry without the forced choice instead of surfacing a hard error. HTTP status is extracted from `status` / `statusCode` so the fallback fires consistently across SDK error shapes.
|
|
18
|
+
- **OpenAI tool history is repaired before replay.** Malformed tool history — orphan assistant `tool_calls` with no matching tool result, or orphan `tool` messages with no preceding assistant `tool_call` — is now sanitized before the conversation is replayed to OpenAI-compat endpoints, preventing avoidable 400s on resume / multi-turn tool runs.
|
|
19
|
+
- **Cross-platform CI test reliability.** Test-only fixes so the Linux CI matrix reflects real regressions: the bash large-output test no longer relies on shell-interpreted backticks/`${}` in a `node -e` script; `isScreenReader` test clears `CI` (GitHub Actions sets `CI=true`); and `resolveSessionRuntimeInfo` / `FileSessionStorage` tests use platform-portable absolute roots instead of Windows-only `C:/…` paths. Remaining Linux-only test gaps are tracked in [docs/KNOWN_ISSUES.md #141](docs/KNOWN_ISSUES.md).
|
|
20
|
+
|
|
7
21
|
## [0.7.51] - 2026-06-17
|
|
8
22
|
|
|
9
23
|
> Scope note: v0.7.51 closes the **"host reads persisted history"** loop on top of the v0.7.49/v0.7.50 workflow split. Two co-shipped, additive features: **FEATURE_230** makes the TUI tool transcript durable across resume, and **FEATURE_234** gives workflow runs a host-owned attribution slot. Neither rewrites FEATURE_217 (v0.7.49) or FEATURE_229 (v0.7.50); both treat the v0.7.50 process/snapshot model as a dependency, not future work. `FEATURE_230` was pulled forward from v0.7.59 into this release window; the original v0.7.51–v0.7.58 plan group shifted +10 (→ v0.7.61–v0.7.68).
|
|
@@ -33,7 +47,7 @@ All notable changes to this project will be documented in this file.
|
|
|
33
47
|
|
|
34
48
|
## [0.7.50] - 2026-06-16
|
|
35
49
|
|
|
36
|
-
> Scope note: v0.7.50 is a single-feature slot for **FEATURE_229**. It does **not** rewrite FEATURE_217 (v0.7.49) — the dynamic JS harness, capsule model, save/rerun, worktree isolation, and permission gates all stay. F229 lifts the v0.7.49 user-visible workflow process into a subscribable Agent-layer event/snapshot model and a Coding/SDK lifecycle surface. `FEATURE_224` was rescheduled to [v0.7.61](docs/features/v0.7.
|
|
50
|
+
> Scope note: v0.7.50 is a single-feature slot for **FEATURE_229**. It does **not** rewrite FEATURE_217 (v0.7.49) — the dynamic JS harness, capsule model, save/rerun, worktree isolation, and permission gates all stay. F229 lifts the v0.7.49 user-visible workflow process into a subscribable Agent-layer event/snapshot model and a Coding/SDK lifecycle surface. `FEATURE_224` was rescheduled to [v0.7.61](docs/features/v0.7.66.md).
|
|
37
51
|
|
|
38
52
|
### Added
|
|
39
53
|
|
|
@@ -579,7 +593,7 @@ Production trace showed Evaluator emitting `emit_verdict` accept before children
|
|
|
579
593
|
- **Slice B — Throttle-Reminder Fix**: `shouldFireTodoReminder` no longer requires `todoStore.hasItems()` — the chicken-and-egg deadlock that prevented the LLM from learning the plan-list infrastructure existed when Scout did not seed is resolved. `buildTodoReminderText` now branches: empty-store nudges the LLM toward `op:'init'` with the trivial-task exemption clause; populated-store text unchanged from v0.7.34. Mirrors Claude Code's `getTodoReminderAttachments` ([attachments.ts:3266](c:/Works/claudecode/src/utils/attachments.ts#L3266)) which fires every 10 turns regardless of store state.
|
|
580
594
|
- **FEATURE_104 prompt eval**: 4 new cases in `benchmark/datasets/feature-151-todo-self-seeding/` (2 positive: multi-file audit + 3-file rename should call op:'init'; 2 negative: typo fix + info request should not). Driver `tests/feature-151-todo-self-seeding.eval.ts` runs 5 alias × 4 case = 20 cells per pilot run; stage-1 acceptance pending post-pilot calibration.
|
|
581
595
|
- **Slice I — Fan-Out Plan Granularity** (added 2026-05-10 after user reported "派 5 个 dispatch_child_task 做 review 时整个过程完全看不到任何 plan list"). Worker role-prompt (`packages/coding/src/agents/worker-role-prompt.ts`) gains a `FAN-OUT PLAN GRANULARITY` section between dispatch rules and Evaluator handoff: when the plan involves dispatching ≥3 children, the model MUST emit `todo_update({op:"init", ...})` as its FIRST tool call and the items array MUST contain EXACTLY N items — one per child's `bundle.objective` — never collapsed into 1-2 items. v2 prompt rewrite (commit `7c508a2`) added explicit MANDATORY TRIGGER framing, COUNT-FIRST imperative ("Not 1. Not 2. Not N-1. Exactly N."), 5-package worked example, and an enumerated ANTI-PATTERNS list after Phase 1 found v1 prompt at 25% positive on the floor model. Mechanism is prompt-only (no code change) — closes the visibility gap in CC default-subagent parity (CC's main agent natively expands plan items per dispatched child via TodoWrite, KodaX Worker was retreating to 1-item plan in fan-out). **Eval ship gate cleared (LLM-judge corrected)**: 3 of 5 aliases (mmx/m27 + ark/glm51 + ds/v4pro) hit ≥80% on each positive case AND ≤20% trigger on each negative case (full pass; mmx 100%/80%, ark+ds_v4pro 100%/100%). zhipu/glm51 + kimi miss the gate due to verbose narration-only single-turn responses (model says "I'll plan first..." but doesn't emit the tool call inline) — this is a single-turn probe limitation against verbose models, not a v2 prompt regression: in the production multi-turn agent loop those models naturally emit the tool call on the second turn. Eval methodology lesson sealed in `EVAL_GUIDELINES.md` anti-pattern 7 + raw output preservation section: regex-only judges on "DOES NOT contain X" assertions falsely fail verbose models that mention X in negation context (kimi was reported as "60/40 negative-case regression" by regex; LLM-judge of the raw outputs found 100/100 — kimi was correctly NOT calling todo_update, just verbalizing the decision). Eval driver dumps `runsRaw[].text` to `os.tmpdir()/kodax-eval-dumps/feature-151-fan-out-plan-granularity/<case>.json` for offline LLM-judge audit. Test pins: 2 unit cases in `worker-role-prompt.test.ts` (presence + ordering after dispatch rules) — 15/15 pass. Design doc: `docs/features/v0.7.38.md#slice-i--fan-out-plan-granularity-review-类-fan-out-抱怨收口2026-05-10-加入`.
|
|
582
|
-
- **Downstream impact**: FEATURE_113 (v0.8.2 TodoList JSON / CLI Surface) gains a new event source (LLM-driven init) but `KodaXEvents.onTodoUpdate` payload schema unchanged — `v0.8.
|
|
596
|
+
- **Downstream impact**: FEATURE_113 (v0.8.2 TodoList JSON / CLI Surface) gains a new event source (LLM-driven init) but `KodaXEvents.onTodoUpdate` payload schema unchanged — `v0.8.7.md` updated with intersection note. No impact on FEATURE_120 / FEATURE_124 / FEATURE_125. Test guide forthcoming. Design doc: `docs/features/v0.7.38.md#feature_151-todolist-visibility--llm-self-seeding-parity--closing-the-feature_097-coverage-gap`.
|
|
583
597
|
|
|
584
598
|
### Changed
|
|
585
599
|
|
|
@@ -861,7 +875,7 @@ Two features close out v0.7.32 and the Plan B roadmap. **FEATURE_090** is the ro
|
|
|
861
875
|
### Documentation
|
|
862
876
|
|
|
863
877
|
- **EVAL_GUIDELINES rewrite** — `benchmark/EVAL_GUIDELINES.md` now documents the **single-turn probe methodology** as the official KodaX eval pattern and removes end-to-end loop comparisons from the recommended set. Loops conflate prompt quality with tool-availability artefacts (model tries to verify with `read`/`grep`/`bash`, harness can't provide tools, benchmark scores the format-fail). Single-turn probes test the prompt-only contract.
|
|
864
|
-
- **FEATURE_108 design** (`docs/features/v0.7.47.md`) — Session-Driven Reflective Prompt Patcher spec landed for v0.7.47 design preview.(注:版本重排后 FEATURE_108 先于 2026-06-05 迁至 v0.7.54,再于 2026-06-11 顺延至 [`docs/features/v0.7.
|
|
878
|
+
- **FEATURE_108 design** (`docs/features/v0.7.47.md`) — Session-Driven Reflective Prompt Patcher spec landed for v0.7.47 design preview.(注:版本重排后 FEATURE_108 先于 2026-06-05 迁至 v0.7.54,再于 2026-06-11 顺延至 [`docs/features/v0.7.72.md`](docs/features/v0.7.72.md);`v0.7.47.md` 现为 FEATURE_218 + FEATURE_132)
|
|
865
879
|
- **FEATURE_109 design** (`docs/features/v0.7.48.md`) — Harness Observability Substrate (long-term memory + prediction contract + cross-family prose guard) spec landed for v0.7.48 design preview.
|
|
866
880
|
- **`docs/features/v0.7.29.md` 1496-line expansion** — folds back the historical capability-inventory artifact (`v0.7.29-capability-inventory.md` deleted) and adds deeper FEATURE_103/104/107-related context to the v0.7.29 retrospective.
|
|
867
881
|
- **`docs/CODING_AGENT_PROMPTS.md`** — cross-project prompt-system reference (4 open-source coding agents) for KodaX prompt design comparison. Research artefact, not a project doc.
|
|
@@ -1273,7 +1287,7 @@ Structural hygiene tail — legacy cleanup + repo-intelligence protocol extracti
|
|
|
1273
1287
|
|
|
1274
1288
|
### Documentation
|
|
1275
1289
|
- `docs/features/v0.7.25.md`: 075 scope narrowed (dropped editor + markdown, added LLM prompt structural constraint), 076 Q1-Q4 decisions captured, 058 section added with FEATURE_057 dependency-free rationale.
|
|
1276
|
-
- `docs/features/v0.8.
|
|
1290
|
+
- `docs/features/v0.8.5.md`: FEATURE_058 moved out to v0.7.25 with migration note.
|
|
1277
1291
|
- `docs/FEATURE_LIST.md`: FEATURE_051 / FEATURE_058 / FEATURE_075 / FEATURE_076 marked Completed; v0.7.25 progress recorded; "Current released version" bumped to v0.7.25.
|
|
1278
1292
|
|
|
1279
1293
|
### Test Status
|
|
@@ -1310,7 +1324,7 @@ Structural hygiene tail — legacy cleanup + repo-intelligence protocol extracti
|
|
|
1310
1324
|
### Documentation
|
|
1311
1325
|
- `docs/features/v0.7.24.md`: Implementation Notes section with slice breakdown (LoC + file count per slice), design deviations (FM-2 capabilities drop, P3 cli-events deferral, Capability type extraction), FEATURE_093 opportunistic completion, test summary, final dependency graph
|
|
1312
1326
|
- `docs/features/v0.7.27.md` (FEATURE_086): added item #9 capturing the deferred cli-events relocation work
|
|
1313
|
-
- `docs/features/v0.8.
|
|
1327
|
+
- `docs/features/v0.8.5.md`: added FEATURE_093 section documenting the remaining 1-cycle scope (`repl/commands` triangle blocker)
|
|
1314
1328
|
- `docs/FEATURE_LIST.md`: FEATURE_082 and FEATURE_083 marked Completed; FEATURE_093 added to Planned; v0.7.24 progress recorded; "Current released version" bumped to v0.7.24
|
|
1315
1329
|
|
|
1316
1330
|
### Test Status
|
|
@@ -1378,7 +1392,7 @@ repl → coding, skills
|
|
|
1378
1392
|
### Documentation
|
|
1379
1393
|
- Remove `docs/features/v1.0.0.md` (all features migrated to earlier versions)
|
|
1380
1394
|
- Add feature docs for v0.7.22, v0.7.23, v0.7.24, v0.7.26–v0.7.29, v0.7.31, v0.7.32
|
|
1381
|
-
- Update `KNOWN_ISSUES.md`, `v0.8.
|
|
1395
|
+
- Update `KNOWN_ISSUES.md`, `v0.8.5.md`, and `features/README.md` references
|
|
1382
1396
|
|
|
1383
1397
|
---
|
|
1384
1398
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{Nb as c,Ob as d,Pb as e,Qb as f,_c as i,cd as j,hc as g,ic as h}from"./chunk-
|
|
2
|
+
import{Nb as c,Ob as d,Pb as e,Qb as f,_c as i,cd as j,hc as g,ic as h}from"./chunk-5USNUSTL.js";import"./chunk-LE6STNVN.js";import{jb as a,kb as b}from"./chunk-HMATTIU6.js";import"./chunk-V4WSBIXB.js";export{d as bucketProviderPayloadSize,g as buildAutoRepoIntelligenceContext,e as checkPromiseSignal,b as cleanupIncompleteToolCalls,h as describeTransientProviderRetry,f as emitResilienceDebug,c as estimateProviderPayloadBytes,j as runKodaX,i as saveSessionSnapshot,a as validateAndFixToolHistory};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{sa as a,ta as b}from"./chunk-
|
|
2
|
+
import{sa as a,ta as b}from"./chunk-7X7SOVER.js";import"./chunk-BFXFSEHK.js";import"./chunk-JJTUBNQX.js";import"./chunk-4RVSFOUT.js";import"./chunk-5USNUSTL.js";import"./chunk-LE6STNVN.js";import"./chunk-HMATTIU6.js";import"./chunk-V4WSBIXB.js";export{a as ArgumentCompleter,b as createArgumentCompleter};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{$a as Ut,$c as gs,Ab as cs,Bb as Ft,Bd as X,Ca as Bi,Cb as vr,Cd as Mr,D as zn,Da as Wi,Db as Tr,E as Yn,Ea as Hi,Eb as ds,F as Jn,Fa as Gi,Fb as ls,Ga as qi,Gb as br,Gd as Or,I as Li,Ib as Er,J as lt,Ka as Vi,Kb as Xe,L as Qn,La as Ki,Lb as Bt,M as Zn,Mb as xr,Nb as us,O as er,Ob as fs,Od as zt,P as tr,Pa as me,Q as nr,Qb as Wt,R as rr,S as or,T as ji,U as Ui,V as ir,Va as Xi,Wa as zi,Xa as Yi,Xb as Ht,Xc as hs,Y as sr,Ya as Ji,Yc as Sr,Za as Qi,Zc as _r,_a as Zi,_c as Ar,bb as lr,c as Lt,ca as jt,cb as ur,cd as pe,d as Oi,db as fr,dd as ws,ec as Rr,ed as ks,f as qn,fa as ar,fb as mr,fd as Cr,g as Ii,gb as es,gd as ys,h as Pi,hb as ts,hc as ms,hd as vs,i as Ni,ia as cr,ib as pr,ic as ps,id as Ts,ja as dr,jb as hr,ka as Fi,kb as gr,ld as Gt,mb as ns,nb as wr,nd as qt,ob as kr,od as Vt,pb as rs,ra as ut,rd as Kt,sb as os,sd as Xt,t as Vn,ud as bs,vd as Es,w as Di,wb as yr,wd as xs,x as Kn,xb as is,xd as Rs,y as $i,yb as ss,z as Xn,zb as as}from"./chunk-WQTVG2T5.js";import{Da as Pn,Ea as It,Fa as Nn,Ga as Dn,Ia as $n,Ja as qe,T as at,_ as ct,h as Ot,sa as ne}from"./chunk-PEWH3AAL.js";import{Ad as Ai,Bd as fe,C as ti,Dd as dt,Ec as gi,Ed as Ci,F as ni,Fd as $t,Ga as oi,Gc as wi,Hc as ki,Ic as yi,Jc as vi,Jd as Hn,Kd as De,La as ii,Ld as Gn,Na as ve,Sd as Mi,Ta as jn,Ub as Bn,Va as si,Zc as Ve,_a as ai,_c as Ti,ab as ci,db as di,eb as li,g as Pt,gb as ui,jb as Un,k as ye,kb as Fn,md as bi,na as Ln,nb as Nt,nd as Ei,ob as fi,od as xi,pd as Ri,rc as mi,s as ei,sc as pi,ta as ri,td as Si,va as Ne,vd as _i,xc as hi,xd as Wn,yd as Dt,zd as Ke}from"./chunk-HMATTIU6.js";import{a as o}from"./chunk-V4WSBIXB.js";var ft=class extends Error{static{o(this,"KodaXError")}code;constructor(t,n="KODAX_ERROR"){super(t),this.code=n,this.name="KodaXError"}};var Ir=class extends ft{static{o(this,"KodaXToolError")}toolName;toolId;constructor(t,n,r){super(t,"TOOL_ERROR"),this.toolName=n,this.toolId=r,this.name="KodaXToolError"}};var Pr=class extends ft{static{o(this,"KodaXSessionError")}sessionId;constructor(t,n){super(t,"SESSION_ERROR"),this.sessionId=n,this.name="KodaXSessionError"}},Nr=class extends ft{static{o(this,"KodaXTerminalError")}suggestions;constructor(t,n=[]){super(t,"TERMINAL_ERROR"),this.name="KodaXTerminalError",this.suggestions=n}};function sl(){return new Yt}o(sl,"createSessionControl");function al(e,t){let n=new AbortController,r=!1,i=o(u=>{r||(r=!0,n.abort(u))},"markAborted");e.abortSignal&&(e.abortSignal.aborted?i(e.abortSignal.reason):e.abortSignal.addEventListener("abort",()=>i(e.abortSignal.reason),{once:!0}));let s=new Yt;s.seed({provider:e.provider,model:e.modelOverride??e.model,reasoning:e.reasoningMode});let c={...e,abortSignal:n.signal,sessionControl:s},a=pe(c,t);return{id:e.session?.id??cl(),get currentProvider(){return s.getProvider()},get currentModel(){return s.getModel()},get currentReasoning(){return s.getReasoning()},get aborted(){return r},get attached(){return s.isAttached()},setProvider:o(u=>s.setProvider(u),"setProvider"),setModel:o(u=>s.setModel(u),"setModel"),setReasoning:o(u=>s.setReasoning(u),"setReasoning"),abort:o(u=>i(u),"abort"),result:a}}o(al,"startKodaX");function cl(){return`sess_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}o(cl,"generateSessionId");var Yt=class{static{o(this,"SessionControlImpl")}mutators=null;providerValue;modelValue;reasoningValue;hasPendingProvider=!1;hasPendingModel=!1;hasPendingReasoning=!1;seed(t){this.providerValue=t.provider,this.modelValue=t.model,this.reasoningValue=t.reasoning}setProvider(t){this.providerValue=t,this.mutators?this.mutators.setProvider(t):this.hasPendingProvider=!0}setModel(t){this.modelValue=t,this.mutators?this.mutators.setModel(t):this.hasPendingModel=!0}setReasoning(t){this.reasoningValue=t,this.mutators?this.mutators.setReasoning(t):this.hasPendingReasoning=!0}getProvider(){return this.providerValue??""}getModel(){return this.modelValue}getReasoning(){return this.reasoningValue}isAttached(){return this.mutators!==null}_attach(t){this.mutators,this.mutators=t,this.hasPendingProvider&&this.providerValue!==void 0&&t.setProvider(this.providerValue),this.hasPendingModel&&t.setModel(this.modelValue),this.hasPendingReasoning&&t.setReasoning(this.reasoningValue),this.hasPendingProvider=!1,this.hasPendingModel=!1,this.hasPendingReasoning=!1}};function dl(e,t){return e.kind!=="revise_count"?{ok:!0}:e.count<=3?{ok:!0}:{ok:!1,severity:"warn",reason:`boundedRevise: revise_count for harness="${e.harness}" reached ${e.count}, exceeding soft threshold 3`}}o(dl,"observe");var Dr={id:"boundedRevise",description:"Per-harness revise count must stay within the soft threshold; crossings emit a warn signal for dispatch-eval (hard cap enforced by the budget controller).",observe:dl};function ll(e,t){return typeof e.maxBudget!="number"?{ok:!0}:e.maxBudget<=t.systemCap.maxBudget?{ok:!0}:{ok:!1,severity:"clamp",reason:`budgetCeiling: manifest.maxBudget=${e.maxBudget} exceeds systemCap.maxBudget=${t.systemCap.maxBudget}`,patch:{clampMaxBudget:t.systemCap.maxBudget}}}o(ll,"admit");var $r={id:"budgetCeiling",description:"manifest.maxBudget must be \u2264 systemCap.maxBudget; over-cap declarations are clamped down to the cap.",admit:ll};function ul(e,t){return{ok:!0}}o(ul,"observe");var Ss={id:"harnessSelectionTiming",description:"FEATURE_193 V2 no-op shell \u2014 predicate always admits since V1 Scout retired. Kept registered for admission-framework / audit-array compat.",observe:ul};function fl(e,t){if(e.kind!=="mutation_recorded")return{ok:!0};let n=t.recorder;return typeof n.todoUpdateCount!="number"?{ok:!0}:n.todoUpdateCount>0?{ok:!0}:n.workerTrivialDeclaration===!0?{ok:!0}:{ok:!1,severity:"warn",reason:`planBeforeMutate: Worker mutated ${e.file} without a prior todo_update plan commit and without a trivial declaration`}}o(fl,"observe");var _s={id:"planBeforeMutate",description:"Worker mutations should be preceded by a todo_update plan commit (or an explicit trivial declaration). Missing plan is a warn-only signal in v0.7.36.",observe:fl};function Lr(e){switch(e){case"read":case"glob":case"grep":case"code_search":case"semantic_lookup":case"repo_overview":case"changed_scope":case"changed_diff":case"changed_diff_bundle":case"module_context":case"symbol_context":case"process_context":case"impact_estimate":case"cyclic_dependencies":case"ask_user_question":case"exit_plan_mode":return"read";case"write":case"edit":case"multi_edit":case"insert_after_anchor":case"undo":return"edit";case"bash":return"bash:mutating";case"web_search":case"web_fetch":case"mcp_search":case"mcp_describe":case"mcp_call":case"mcp_read_resource":case"mcp_get_prompt":return"bash:network";case"dispatch_child_task":case"emit_verdict":case"scaffold_tool":case"validate_tool":case"stage_construction":case"test_tool":case"activate_tool":case"scaffold_agent":case"validate_agent":case"stage_agent_construction":case"test_agent":case"activate_agent":case"worktree_create":case"worktree_remove":return"subagent";default:return"subagent"}}o(Lr,"resolveToolCapability");function ml(e){if(typeof e=="object"&&e!==null&&"name"in e){let t=e.name;if(typeof t=="string"&&t.length>0)return t}}o(ml,"getToolName");function pl(e,t){if(!e.tools||e.tools.length===0)return{ok:!0};let n=new Set(t.systemCap.allowedToolCapabilities),r=[];for(let c of e.tools){let a=ml(c);if(!a)continue;let l=Lr(a);n.has(l)||r.push({name:a,capability:l})}if(r.length===0)return{ok:!0};let i=r.map(c=>c.name);return{ok:!1,severity:"clamp",reason:`toolPermission: tools requiring disallowed capabilities \u2014 ${r.map(c=>`${c.name}=${c.capability}`).join(", ")}`,patch:{removeTools:i}}}o(pl,"admit");var jr={id:"toolPermission",description:"Every tool in manifest.tools must resolve to a capability tier that systemCap.allowedToolCapabilities permits; offending tools are clamped via removeTools.",admit:pl};var As=[$r,jr,Dr,Ss,_s];function hl(){ri();for(let e of As)ni(e)}o(hl,"registerCodingInvariants");var Jt=class{static{o(this,"KodaXClient")}options;sessionId;messages=[];contextTokenSnapshot;constructor(t){this.options=t,this.sessionId=t.session?.id??"",this.messages=t.session?.initialMessages?[...t.session.initialMessages]:[],this.contextTokenSnapshot=t.context?.contextTokenSnapshot}async send(t){let n=this.messages.length>0?this.messages:this.options.session?.initialMessages,r=await pe({...this.options,session:{...this.options.session,id:this.sessionId||void 0,initialMessages:n},context:{...this.options.context,contextTokenSnapshot:this.contextTokenSnapshot}},t);return this.sessionId=r.sessionId,this.messages=r.messages,this.contextTokenSnapshot=r.contextTokenSnapshot,r}getSessionId(){return this.sessionId}getMessages(){return[...this.messages]}clear(){this.messages=[],this.sessionId="",this.contextTokenSnapshot=void 0}};function gl(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}o(gl,"dedupeBundles");function Cs(e){return e==="evidence-scan"?"winner-cancel":"none"}o(Cs,"resolveFanoutCancellationPolicy");function wl(e,t,n){if(!(!e.fanout.admissible||!e.fanout.class))return{profile:e.profile,fanoutClass:e.fanout.class,maxChildren:e.fanout.maxChildren,bundles:t,reductionStrategy:n.strategy}}o(wl,"createFanoutSchedulerInput");function kl(e){let t=gl(e.bundles.filter(a=>a.fanoutClass===e.fanoutClass));if(t.length===0)return{enabled:!1,profile:e.profile,fanoutClass:e.fanoutClass,branches:[],scheduledBundleIds:[],deferredBundleIds:[],maxParallel:1,mergeStrategy:e.reductionStrategy,cancellationPolicy:Cs(e.fanoutClass),reason:"No child bundles matched the requested fan-out class."};let n=e.maxChildren&&e.maxChildren>0?e.maxChildren:t.length,r=t.slice(0,n),i=t.slice(r.length),s=[...r.map(a=>({bundleId:a.id,status:"scheduled"})),...i.map(a=>({bundleId:a.id,status:"deferred",reason:"Deferred by the current AMA fan-out budget."}))],c=Math.max(1,Math.min(r.length,n));return{enabled:r.length>0,profile:e.profile,fanoutClass:e.fanoutClass,branches:s,scheduledBundleIds:r.map(a=>a.id),deferredBundleIds:i.map(a=>a.id),maxParallel:c,mergeStrategy:e.reductionStrategy,cancellationPolicy:Cs(e.fanoutClass),reason:i.length>0?`Scheduled ${r.length} child bundles and deferred ${i.length} to stay within the current AMA fan-out budget.`:`Scheduled ${r.length} child bundles for ${e.fanoutClass}.`}}o(kl,"buildFanoutSchedulerPlan");function Ms(e,t){let n=e.branches.find(r=>r.bundleId===t);if(!n)throw new Error(`Unknown fan-out bundle id: ${t}`);return n}o(Ms,"getFanoutBranch");function yl(e){return e.branches.filter(t=>t.status==="scheduled").length}o(yl,"countActiveFanoutBranches");function Qt(e,t){let n=Ms(e,t.bundleId);return{...e,branches:e.branches.map(r=>{if(r.bundleId!==t.bundleId)return r;switch(t.type){case"assign":return{...n,workerId:t.workerId};case"complete":return{...n,status:"completed",childId:t.childId??n.childId,reason:void 0};case"cancel":return{...n,status:"cancelled",reason:t.reason};default:return t}})}}o(Qt,"applyFanoutBranchTransition");function vl(e,t,n){return Qt(e,{type:"assign",bundleId:t,workerId:n})}o(vl,"assignFanoutBranchWorker");function Tl(e,t,n){return Qt(e,{type:"complete",bundleId:t,childId:n})}o(Tl,"markFanoutBranchCompleted");function bl(e,t,n){return Qt(e,{type:"cancel",bundleId:t,reason:n})}o(bl,"markFanoutBranchCancelled");var Os="kodax-review-findings",Is="kodax-investigation-shards",Ps="kodax-lookup-shards",Ns="kodax-child-result";var Ds="kodax-budget-request";function $e(e,t=!1){return{globalWorkBudget:e?.totalBudget,budgetUsage:e?.spentBudget,budgetApprovalRequired:t}}o($e,"buildManagedStatusBudgetFields");function mt(e,t=1){e.spentBudget=Math.max(0,e.spentBudget+t)}o(mt,"incrementManagedBudgetUsage");function xl(e,t=200){e.totalBudget+=t}o(xl,"extendManagedWorkBudget");async function Ur(e,t,n){if(!e?.askUser)return"skipped";if(!n.force){let l=Math.ceil(t.totalBudget*.9);if(t.spentBudget<l)return"skipped"}if(t.lastApprovalBudgetTotal===t.totalBudget)return"skipped";let r=n.additionalUnits??200,i=Math.min(100,Math.round(t.spentBudget/Math.max(1,t.totalBudget)*100)),s=/[\u4e00-\u9fff]/.test(n.originalTask??n.summary),c=await e.askUser({question:s?`\u5F53\u524D AMA \u8FD0\u884C\u5DF2\u4F7F\u7528 ${t.spentBudget}/${t.totalBudget} \u5DE5\u4F5C\u5355\u5143\uFF08${i}%\uFF09\uFF0C\u9700\u8981\u66F4\u591A\u5DE5\u4F5C\u91CF\u3002\u662F\u5426\u8FFD\u52A0 ${r} \u5355\u5143\uFF1F`:`This AMA run has used ${t.spentBudget}/${t.totalBudget} work units (${i}%) and needs more work. Add ${r} more work units?`,options:[{label:s?`\u7EE7\u7EED (+${r})`:`Continue (+${r})`,value:"continue",description:s?`\u8FFD\u52A0 ${r} \u5DE5\u4F5C\u5355\u5143\uFF0C\u4ECE\u7B2C ${n.currentRound}/${n.maxRounds} \u8F6E\u7EE7\u7EED\u3002`:`Grant ${r} more work units and continue from round ${n.currentRound}/${n.maxRounds}.`},{label:s?"\u505C\u6B62":"Stop here",value:"stop",description:s?`\u4F7F\u7528\u5F53\u524D\u6700\u4F73\u7ED3\u679C\u3002\u6700\u65B0\u8FDB\u5C55\uFF1A${kr(n.summary,80)}`:`Finish now with the current best result. Latest note: ${kr(n.summary,80)}`}],default:"continue"}),a=t.totalBudget;return c==="continue"?(t.lastApprovalBudgetTotal=a,xl(t,r),"approved"):(t.lastApprovalBudgetTotal=a,"denied")}o(Ur,"maybeRequestAdditionalWorkBudget");import{mkdir as Rl,readdir as Sl,readFile as js,stat as _l,unlink as Al,writeFile as Cl}from"node:fs/promises";import{execFile as Ml}from"node:child_process";import{promisify as Ol}from"node:util";import ze from"node:path";import Ls from"node:path";function Te(e){return e.context?.taskSurface??"cli"}o(Te,"getManagedTaskSurface");function be(e,t){if(e.context?.managedTaskWorkspaceDir?.trim())return Ls.resolve(e.context.managedTaskWorkspaceDir);let n=e.context?.executionCwd??e.context?.gitRoot??process.cwd();return Ls.resolve(n,".agent","managed-tasks")}o(be,"getManagedTaskWorkspaceRoot");var Il=Ol(Ml),Us=3600*1e3,Zt="checkpoint.json";async function en(e){let t=ze.resolve(e?.trim()||process.cwd());try{let{stdout:n}=await Il("git",["rev-parse","--short","HEAD"],{cwd:t});return n.trim()||void 0}catch{return}}o(en,"getGitHeadCommit");async function Fr(e,t){await Rl(e,{recursive:!0}),await Cl(ze.join(e,Zt),`${JSON.stringify(t,null,2)}
|
|
2
|
+
import{$a as Ut,$c as gs,Ab as cs,Bb as Ft,Bd as X,Ca as Bi,Cb as vr,Cd as Mr,D as zn,Da as Wi,Db as Tr,E as Yn,Ea as Hi,Eb as ds,F as Jn,Fa as Gi,Fb as ls,Ga as qi,Gb as br,Gd as Or,I as Li,Ib as Er,J as lt,Ka as Vi,Kb as Xe,L as Qn,La as Ki,Lb as Bt,M as Zn,Mb as xr,Nb as us,O as er,Ob as fs,Od as zt,P as tr,Pa as me,Q as nr,Qb as Wt,R as rr,S as or,T as ji,U as Ui,V as ir,Va as Xi,Wa as zi,Xa as Yi,Xb as Ht,Xc as hs,Y as sr,Ya as Ji,Yc as Sr,Za as Qi,Zc as _r,_a as Zi,_c as Ar,bb as lr,c as Lt,ca as jt,cb as ur,cd as pe,d as Oi,db as fr,dd as ws,ec as Rr,ed as ks,f as qn,fa as ar,fb as mr,fd as Cr,g as Ii,gb as es,gd as ys,h as Pi,hb as ts,hc as ms,hd as vs,i as Ni,ia as cr,ib as pr,ic as ps,id as Ts,ja as dr,jb as hr,ka as Fi,kb as gr,ld as Gt,mb as ns,nb as wr,nd as qt,ob as kr,od as Vt,pb as rs,ra as ut,rd as Kt,sb as os,sd as Xt,t as Vn,ud as bs,vd as Es,w as Di,wb as yr,wd as xs,x as Kn,xb as is,xd as Rs,y as $i,yb as ss,z as Xn,zb as as}from"./chunk-5USNUSTL.js";import{Da as Pn,Ea as It,Fa as Nn,Ga as Dn,Ia as $n,Ja as qe,T as at,_ as ct,h as Ot,sa as ne}from"./chunk-LE6STNVN.js";import{Ad as Ai,Bd as fe,C as ti,Dd as dt,Ec as gi,Ed as Ci,F as ni,Fd as $t,Ga as oi,Gc as wi,Hc as ki,Ic as yi,Jc as vi,Jd as Hn,Kd as De,La as ii,Ld as Gn,Na as ve,Sd as Mi,Ta as jn,Ub as Bn,Va as si,Zc as Ve,_a as ai,_c as Ti,ab as ci,db as di,eb as li,g as Pt,gb as ui,jb as Un,k as ye,kb as Fn,md as bi,na as Ln,nb as Nt,nd as Ei,ob as fi,od as xi,pd as Ri,rc as mi,s as ei,sc as pi,ta as ri,td as Si,va as Ne,vd as _i,xc as hi,xd as Wn,yd as Dt,zd as Ke}from"./chunk-HMATTIU6.js";import{a as o}from"./chunk-V4WSBIXB.js";var ft=class extends Error{static{o(this,"KodaXError")}code;constructor(t,n="KODAX_ERROR"){super(t),this.code=n,this.name="KodaXError"}};var Ir=class extends ft{static{o(this,"KodaXToolError")}toolName;toolId;constructor(t,n,r){super(t,"TOOL_ERROR"),this.toolName=n,this.toolId=r,this.name="KodaXToolError"}};var Pr=class extends ft{static{o(this,"KodaXSessionError")}sessionId;constructor(t,n){super(t,"SESSION_ERROR"),this.sessionId=n,this.name="KodaXSessionError"}},Nr=class extends ft{static{o(this,"KodaXTerminalError")}suggestions;constructor(t,n=[]){super(t,"TERMINAL_ERROR"),this.name="KodaXTerminalError",this.suggestions=n}};function sl(){return new Yt}o(sl,"createSessionControl");function al(e,t){let n=new AbortController,r=!1,i=o(u=>{r||(r=!0,n.abort(u))},"markAborted");e.abortSignal&&(e.abortSignal.aborted?i(e.abortSignal.reason):e.abortSignal.addEventListener("abort",()=>i(e.abortSignal.reason),{once:!0}));let s=new Yt;s.seed({provider:e.provider,model:e.modelOverride??e.model,reasoning:e.reasoningMode});let c={...e,abortSignal:n.signal,sessionControl:s},a=pe(c,t);return{id:e.session?.id??cl(),get currentProvider(){return s.getProvider()},get currentModel(){return s.getModel()},get currentReasoning(){return s.getReasoning()},get aborted(){return r},get attached(){return s.isAttached()},setProvider:o(u=>s.setProvider(u),"setProvider"),setModel:o(u=>s.setModel(u),"setModel"),setReasoning:o(u=>s.setReasoning(u),"setReasoning"),abort:o(u=>i(u),"abort"),result:a}}o(al,"startKodaX");function cl(){return`sess_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}o(cl,"generateSessionId");var Yt=class{static{o(this,"SessionControlImpl")}mutators=null;providerValue;modelValue;reasoningValue;hasPendingProvider=!1;hasPendingModel=!1;hasPendingReasoning=!1;seed(t){this.providerValue=t.provider,this.modelValue=t.model,this.reasoningValue=t.reasoning}setProvider(t){this.providerValue=t,this.mutators?this.mutators.setProvider(t):this.hasPendingProvider=!0}setModel(t){this.modelValue=t,this.mutators?this.mutators.setModel(t):this.hasPendingModel=!0}setReasoning(t){this.reasoningValue=t,this.mutators?this.mutators.setReasoning(t):this.hasPendingReasoning=!0}getProvider(){return this.providerValue??""}getModel(){return this.modelValue}getReasoning(){return this.reasoningValue}isAttached(){return this.mutators!==null}_attach(t){this.mutators,this.mutators=t,this.hasPendingProvider&&this.providerValue!==void 0&&t.setProvider(this.providerValue),this.hasPendingModel&&t.setModel(this.modelValue),this.hasPendingReasoning&&t.setReasoning(this.reasoningValue),this.hasPendingProvider=!1,this.hasPendingModel=!1,this.hasPendingReasoning=!1}};function dl(e,t){return e.kind!=="revise_count"?{ok:!0}:e.count<=3?{ok:!0}:{ok:!1,severity:"warn",reason:`boundedRevise: revise_count for harness="${e.harness}" reached ${e.count}, exceeding soft threshold 3`}}o(dl,"observe");var Dr={id:"boundedRevise",description:"Per-harness revise count must stay within the soft threshold; crossings emit a warn signal for dispatch-eval (hard cap enforced by the budget controller).",observe:dl};function ll(e,t){return typeof e.maxBudget!="number"?{ok:!0}:e.maxBudget<=t.systemCap.maxBudget?{ok:!0}:{ok:!1,severity:"clamp",reason:`budgetCeiling: manifest.maxBudget=${e.maxBudget} exceeds systemCap.maxBudget=${t.systemCap.maxBudget}`,patch:{clampMaxBudget:t.systemCap.maxBudget}}}o(ll,"admit");var $r={id:"budgetCeiling",description:"manifest.maxBudget must be \u2264 systemCap.maxBudget; over-cap declarations are clamped down to the cap.",admit:ll};function ul(e,t){return{ok:!0}}o(ul,"observe");var Ss={id:"harnessSelectionTiming",description:"FEATURE_193 V2 no-op shell \u2014 predicate always admits since V1 Scout retired. Kept registered for admission-framework / audit-array compat.",observe:ul};function fl(e,t){if(e.kind!=="mutation_recorded")return{ok:!0};let n=t.recorder;return typeof n.todoUpdateCount!="number"?{ok:!0}:n.todoUpdateCount>0?{ok:!0}:n.workerTrivialDeclaration===!0?{ok:!0}:{ok:!1,severity:"warn",reason:`planBeforeMutate: Worker mutated ${e.file} without a prior todo_update plan commit and without a trivial declaration`}}o(fl,"observe");var _s={id:"planBeforeMutate",description:"Worker mutations should be preceded by a todo_update plan commit (or an explicit trivial declaration). Missing plan is a warn-only signal in v0.7.36.",observe:fl};function Lr(e){switch(e){case"read":case"glob":case"grep":case"code_search":case"semantic_lookup":case"repo_overview":case"changed_scope":case"changed_diff":case"changed_diff_bundle":case"module_context":case"symbol_context":case"process_context":case"impact_estimate":case"cyclic_dependencies":case"ask_user_question":case"exit_plan_mode":return"read";case"write":case"edit":case"multi_edit":case"insert_after_anchor":case"undo":return"edit";case"bash":return"bash:mutating";case"web_search":case"web_fetch":case"mcp_search":case"mcp_describe":case"mcp_call":case"mcp_read_resource":case"mcp_get_prompt":return"bash:network";case"dispatch_child_task":case"emit_verdict":case"scaffold_tool":case"validate_tool":case"stage_construction":case"test_tool":case"activate_tool":case"scaffold_agent":case"validate_agent":case"stage_agent_construction":case"test_agent":case"activate_agent":case"worktree_create":case"worktree_remove":return"subagent";default:return"subagent"}}o(Lr,"resolveToolCapability");function ml(e){if(typeof e=="object"&&e!==null&&"name"in e){let t=e.name;if(typeof t=="string"&&t.length>0)return t}}o(ml,"getToolName");function pl(e,t){if(!e.tools||e.tools.length===0)return{ok:!0};let n=new Set(t.systemCap.allowedToolCapabilities),r=[];for(let c of e.tools){let a=ml(c);if(!a)continue;let l=Lr(a);n.has(l)||r.push({name:a,capability:l})}if(r.length===0)return{ok:!0};let i=r.map(c=>c.name);return{ok:!1,severity:"clamp",reason:`toolPermission: tools requiring disallowed capabilities \u2014 ${r.map(c=>`${c.name}=${c.capability}`).join(", ")}`,patch:{removeTools:i}}}o(pl,"admit");var jr={id:"toolPermission",description:"Every tool in manifest.tools must resolve to a capability tier that systemCap.allowedToolCapabilities permits; offending tools are clamped via removeTools.",admit:pl};var As=[$r,jr,Dr,Ss,_s];function hl(){ri();for(let e of As)ni(e)}o(hl,"registerCodingInvariants");var Jt=class{static{o(this,"KodaXClient")}options;sessionId;messages=[];contextTokenSnapshot;constructor(t){this.options=t,this.sessionId=t.session?.id??"",this.messages=t.session?.initialMessages?[...t.session.initialMessages]:[],this.contextTokenSnapshot=t.context?.contextTokenSnapshot}async send(t){let n=this.messages.length>0?this.messages:this.options.session?.initialMessages,r=await pe({...this.options,session:{...this.options.session,id:this.sessionId||void 0,initialMessages:n},context:{...this.options.context,contextTokenSnapshot:this.contextTokenSnapshot}},t);return this.sessionId=r.sessionId,this.messages=r.messages,this.contextTokenSnapshot=r.contextTokenSnapshot,r}getSessionId(){return this.sessionId}getMessages(){return[...this.messages]}clear(){this.messages=[],this.sessionId="",this.contextTokenSnapshot=void 0}};function gl(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}o(gl,"dedupeBundles");function Cs(e){return e==="evidence-scan"?"winner-cancel":"none"}o(Cs,"resolveFanoutCancellationPolicy");function wl(e,t,n){if(!(!e.fanout.admissible||!e.fanout.class))return{profile:e.profile,fanoutClass:e.fanout.class,maxChildren:e.fanout.maxChildren,bundles:t,reductionStrategy:n.strategy}}o(wl,"createFanoutSchedulerInput");function kl(e){let t=gl(e.bundles.filter(a=>a.fanoutClass===e.fanoutClass));if(t.length===0)return{enabled:!1,profile:e.profile,fanoutClass:e.fanoutClass,branches:[],scheduledBundleIds:[],deferredBundleIds:[],maxParallel:1,mergeStrategy:e.reductionStrategy,cancellationPolicy:Cs(e.fanoutClass),reason:"No child bundles matched the requested fan-out class."};let n=e.maxChildren&&e.maxChildren>0?e.maxChildren:t.length,r=t.slice(0,n),i=t.slice(r.length),s=[...r.map(a=>({bundleId:a.id,status:"scheduled"})),...i.map(a=>({bundleId:a.id,status:"deferred",reason:"Deferred by the current AMA fan-out budget."}))],c=Math.max(1,Math.min(r.length,n));return{enabled:r.length>0,profile:e.profile,fanoutClass:e.fanoutClass,branches:s,scheduledBundleIds:r.map(a=>a.id),deferredBundleIds:i.map(a=>a.id),maxParallel:c,mergeStrategy:e.reductionStrategy,cancellationPolicy:Cs(e.fanoutClass),reason:i.length>0?`Scheduled ${r.length} child bundles and deferred ${i.length} to stay within the current AMA fan-out budget.`:`Scheduled ${r.length} child bundles for ${e.fanoutClass}.`}}o(kl,"buildFanoutSchedulerPlan");function Ms(e,t){let n=e.branches.find(r=>r.bundleId===t);if(!n)throw new Error(`Unknown fan-out bundle id: ${t}`);return n}o(Ms,"getFanoutBranch");function yl(e){return e.branches.filter(t=>t.status==="scheduled").length}o(yl,"countActiveFanoutBranches");function Qt(e,t){let n=Ms(e,t.bundleId);return{...e,branches:e.branches.map(r=>{if(r.bundleId!==t.bundleId)return r;switch(t.type){case"assign":return{...n,workerId:t.workerId};case"complete":return{...n,status:"completed",childId:t.childId??n.childId,reason:void 0};case"cancel":return{...n,status:"cancelled",reason:t.reason};default:return t}})}}o(Qt,"applyFanoutBranchTransition");function vl(e,t,n){return Qt(e,{type:"assign",bundleId:t,workerId:n})}o(vl,"assignFanoutBranchWorker");function Tl(e,t,n){return Qt(e,{type:"complete",bundleId:t,childId:n})}o(Tl,"markFanoutBranchCompleted");function bl(e,t,n){return Qt(e,{type:"cancel",bundleId:t,reason:n})}o(bl,"markFanoutBranchCancelled");var Os="kodax-review-findings",Is="kodax-investigation-shards",Ps="kodax-lookup-shards",Ns="kodax-child-result";var Ds="kodax-budget-request";function $e(e,t=!1){return{globalWorkBudget:e?.totalBudget,budgetUsage:e?.spentBudget,budgetApprovalRequired:t}}o($e,"buildManagedStatusBudgetFields");function mt(e,t=1){e.spentBudget=Math.max(0,e.spentBudget+t)}o(mt,"incrementManagedBudgetUsage");function xl(e,t=200){e.totalBudget+=t}o(xl,"extendManagedWorkBudget");async function Ur(e,t,n){if(!e?.askUser)return"skipped";if(!n.force){let l=Math.ceil(t.totalBudget*.9);if(t.spentBudget<l)return"skipped"}if(t.lastApprovalBudgetTotal===t.totalBudget)return"skipped";let r=n.additionalUnits??200,i=Math.min(100,Math.round(t.spentBudget/Math.max(1,t.totalBudget)*100)),s=/[\u4e00-\u9fff]/.test(n.originalTask??n.summary),c=await e.askUser({question:s?`\u5F53\u524D AMA \u8FD0\u884C\u5DF2\u4F7F\u7528 ${t.spentBudget}/${t.totalBudget} \u5DE5\u4F5C\u5355\u5143\uFF08${i}%\uFF09\uFF0C\u9700\u8981\u66F4\u591A\u5DE5\u4F5C\u91CF\u3002\u662F\u5426\u8FFD\u52A0 ${r} \u5355\u5143\uFF1F`:`This AMA run has used ${t.spentBudget}/${t.totalBudget} work units (${i}%) and needs more work. Add ${r} more work units?`,options:[{label:s?`\u7EE7\u7EED (+${r})`:`Continue (+${r})`,value:"continue",description:s?`\u8FFD\u52A0 ${r} \u5DE5\u4F5C\u5355\u5143\uFF0C\u4ECE\u7B2C ${n.currentRound}/${n.maxRounds} \u8F6E\u7EE7\u7EED\u3002`:`Grant ${r} more work units and continue from round ${n.currentRound}/${n.maxRounds}.`},{label:s?"\u505C\u6B62":"Stop here",value:"stop",description:s?`\u4F7F\u7528\u5F53\u524D\u6700\u4F73\u7ED3\u679C\u3002\u6700\u65B0\u8FDB\u5C55\uFF1A${kr(n.summary,80)}`:`Finish now with the current best result. Latest note: ${kr(n.summary,80)}`}],default:"continue"}),a=t.totalBudget;return c==="continue"?(t.lastApprovalBudgetTotal=a,xl(t,r),"approved"):(t.lastApprovalBudgetTotal=a,"denied")}o(Ur,"maybeRequestAdditionalWorkBudget");import{mkdir as Rl,readdir as Sl,readFile as js,stat as _l,unlink as Al,writeFile as Cl}from"node:fs/promises";import{execFile as Ml}from"node:child_process";import{promisify as Ol}from"node:util";import ze from"node:path";import Ls from"node:path";function Te(e){return e.context?.taskSurface??"cli"}o(Te,"getManagedTaskSurface");function be(e,t){if(e.context?.managedTaskWorkspaceDir?.trim())return Ls.resolve(e.context.managedTaskWorkspaceDir);let n=e.context?.executionCwd??e.context?.gitRoot??process.cwd();return Ls.resolve(n,".agent","managed-tasks")}o(be,"getManagedTaskWorkspaceRoot");var Il=Ol(Ml),Us=3600*1e3,Zt="checkpoint.json";async function en(e){let t=ze.resolve(e?.trim()||process.cwd());try{let{stdout:n}=await Il("git",["rev-parse","--short","HEAD"],{cwd:t});return n.trim()||void 0}catch{return}}o(en,"getGitHeadCommit");async function Fr(e,t){await Rl(e,{recursive:!0}),await Cl(ze.join(e,Zt),`${JSON.stringify(t,null,2)}
|
|
3
3
|
`,"utf8")}o(Fr,"writeCheckpoint");async function Le(e){try{await Al(ze.join(e,Zt))}catch{}}o(Le,"deleteCheckpoint");async function Br(e){let t=e.context?.gitRoot,n=Te(e),r=be(e,n),i;try{i=await Sl(r)}catch{return}let s=await en(t),c=Date.now();for(let a of i){let l=ze.join(r,a),u=ze.join(l,Zt);try{if(!(await _l(u)).isFile())continue;let d=await js(u,"utf8"),f=JSON.parse(d);if(!f||typeof f!="object")continue;let p=f;if(p.version!==1||typeof p.taskId!="string"||typeof p.createdAt!="string"||typeof p.gitCommit!="string"||typeof p.harnessProfile!="string")continue;let h={version:1,taskId:p.taskId,createdAt:p.createdAt,gitCommit:p.gitCommit,objective:typeof p.objective=="string"?p.objective:"",harnessProfile:p.harnessProfile,currentRound:typeof p.currentRound=="number"?p.currentRound:1,completedWorkerIds:Array.isArray(p.completedWorkerIds)?p.completedWorkerIds.filter(T=>typeof T=="string"):[],scoutCompleted:p.scoutCompleted===!0},g=new Date(h.createdAt).getTime();if(Number.isNaN(g))continue;let y=c-g;if(y>Us||y<0){await Le(l);continue}if(s&&h.gitCommit&&h.gitCommit!==s){await Le(l);continue}let x=ze.join(l,"managed-task.json"),j=await js(x,"utf8"),k=JSON.parse(j);if(!k||typeof k!="object")continue;let v=k;if(!v.contract?.taskId||!v.evidence?.workspaceDir)continue;return{checkpoint:h,workspaceDir:l,managedTask:v}}catch{continue}}}o(Br,"findValidCheckpoint");import{mkdir as Nl,writeFile as re}from"node:fs/promises";import M from"node:path";function Wr(e){let t=e?.runtime;return t?`${["# Runtime Execution Guide","","Use this guide to drive live verification against the runtime under test.","",t.cwd?`- Working directory: ${t.cwd}`:void 0,t.startupCommand?`- Startup command: ${t.startupCommand}`:void 0,t.readySignal?`- Ready signal: ${t.readySignal}`:void 0,t.baseUrl?`- Base URL: ${t.baseUrl}`:void 0,t.env&&Object.keys(t.env).length>0?`- Environment keys: ${Object.keys(t.env).join(", ")}`:void 0,"","Execution protocol:",t.startupCommand?"1. Start or confirm the runtime using the declared startup command before accepting the task.":"1. Confirm the target runtime is available before accepting the task.",t.readySignal||t.baseUrl?"2. Wait until the runtime is ready, using the ready signal or base URL when available.":"2. Confirm runtime readiness using the strongest observable signal you have.",t.uiFlows?.length?["3. Execute the declared UI flows:",...t.uiFlows.map((r,i)=>` ${i+1}. ${r}`)].join(`
|
|
4
4
|
`):"3. Execute the critical user-facing flow when browser verification is required.",t.apiChecks?.length?["4. Run the declared API checks:",...t.apiChecks.map((r,i)=>` ${i+1}. ${r}`)].join(`
|
|
5
5
|
`):void 0,t.dbChecks?.length?["5. Run the declared DB checks:",...t.dbChecks.map((r,i)=>` ${i+1}. ${r}`)].join(`
|
|
@@ -113,7 +113,7 @@ ${u}`:u}o(Ya,"resolveRoleInstructions");function Ja(e,t){if(!e)return;let n=e.cr
|
|
|
113
113
|
|
|
114
114
|
`),y=d.slice(p);if(s&&c){if(ya(c,f.name)&&on(c),ga(c,s)){let w=ka(s);g=g.length>0?`${g}
|
|
115
115
|
|
|
116
|
-
${w}`:w}wa(c)}let x=(f.tools??[]).map(w=>({name:w.name,description:w.description,input_schema:w.input_schema})),j=vr(e),k=r?.(),T=ds("sa",j,f.reasoning,k),N=T==="off"?{enabled:!1,mode:"off"}:{enabled:!0,mode:T,depth:Tr(T)};a+=1,e.events?.onIterationStart?.(a,l);let C;if(t)C=await t(y,x,g);else{let w=ne(e.provider??"anthropic"),R=e.provider??w.name??"anthropic",E=lr(R),_=E.requestTimeoutMs,U=E.streamIdleTimeoutMs,A=new fr,F=typeof w.supportsNonStreamingFallback=="function"?w.supportsNonStreamingFallback():!1,L=new mr(A,{...E,enableNonStreamingFallback:E.enableNonStreamingFallback&&F}),I=[...y];I=Fn(I),I=Un(I);let D=0,P,Ge=!1,le=0;for(;;){D+=1,A.beginRequest(R,m??w.getModel?.()??"unknown",I,D,!1),pr(A.snapshot());let Q=new AbortController,V=setTimeout(()=>{Q.abort(new Error("API Hard Timeout (10 minutes)"))},_),ee=U>0,S;ee&&(S=setTimeout(()=>{Q.abort(new Error(`Stream stalled or delayed response (${U}ms idle)`))},U));let ae=o(()=>{ee&&(S&&clearTimeout(S),Q.signal.aborted||(S=setTimeout(()=>{Q.abort(new Error(`Stream stalled or delayed response (${U}ms idle)`))},U)))},"resetIdleTimer"),we=e.abortSignal?AbortSignal.any([e.abortSignal,Q.signal]):Q.signal,Oe=us(I,g);Wt("[resilience:request]",{provider:R,attempt:D,fallbackActive:!1,payloadBytes:Oe,payloadBucket:fs(Oe)});let ot={modelOverride:m,onTextDelta:o(H=>{A.markTextDelta(H),ae();let ke=H.includes("```")||ht.some(Ie=>H.includes(Ie))?Yr(H):H;ke.length!==0&&e.events?.onTextDelta?.(ke)},"onTextDelta"),onThinkingDelta:o(H=>{A.markThinkingDelta(H),ae(),e.events?.onThinkingDelta?.(H)},"onThinkingDelta"),onThinkingEnd:o(H=>{e.events?.onThinkingEnd?.(H)},"onThinkingEnd"),onToolInputDelta:e.events?.onToolInputDelta,onRateLimit:o((H,J,ke)=>{ae(),e.events&&Ft(e.events,H,J,ke)},"onRateLimit"),onRetryAfter:o(H=>{ae(),u=It(u,{provider:H.provider,waitMs:H.waitMs,reason:H.reason,source:H.source}),e.events?.onRetryAfter?.(H)},"onRetryAfter")};try{if(P=await w.stream(I,[...x],g,N,ot,we),P.stopReason==="max_tokens"&&!Ge&&!process.env.KODAX_MAX_OUTPUT_TOKENS&&w.getEffectiveMaxOutputTokens(m)<64e3){Ge=!0,w.setMaxOutputTokensOverride(64e3),e.events?.onRetry?.(`Output budget reached, escalating to ${64e3} tokens and retrying the same turn`,1,1),V&&clearTimeout(V),S&&clearTimeout(S),V=void 0,S=void 0,D-=1;continue}if(nf(P)&&P.stopReason!=="max_tokens"&&le<Lt&&!e.abortSignal?.aborted){le+=1,e.events?.onRetry?.(`Provider returned an empty turn, retrying ${le}/${Lt}`,le,Lt),V&&clearTimeout(V),S&&clearTimeout(S),V=void 0,S=void 0,D-=1,await Ut(Oi*le,e.abortSignal);continue}break}catch(H){let J=H instanceof Error?H:new Error(String(H));if(J.name==="AbortError"&&Q.signal.aborted&&!e.abortSignal?.aborted){let ce=Q.signal.reason?.message??"Stream stalled",{KodaXNetworkError:Pe}=await import("./dist-
|
|
116
|
+
${w}`:w}wa(c)}let x=(f.tools??[]).map(w=>({name:w.name,description:w.description,input_schema:w.input_schema})),j=vr(e),k=r?.(),T=ds("sa",j,f.reasoning,k),N=T==="off"?{enabled:!1,mode:"off"}:{enabled:!0,mode:T,depth:Tr(T)};a+=1,e.events?.onIterationStart?.(a,l);let C;if(t)C=await t(y,x,g);else{let w=ne(e.provider??"anthropic"),R=e.provider??w.name??"anthropic",E=lr(R),_=E.requestTimeoutMs,U=E.streamIdleTimeoutMs,A=new fr,F=typeof w.supportsNonStreamingFallback=="function"?w.supportsNonStreamingFallback():!1,L=new mr(A,{...E,enableNonStreamingFallback:E.enableNonStreamingFallback&&F}),I=[...y];I=Fn(I),I=Un(I);let D=0,P,Ge=!1,le=0;for(;;){D+=1,A.beginRequest(R,m??w.getModel?.()??"unknown",I,D,!1),pr(A.snapshot());let Q=new AbortController,V=setTimeout(()=>{Q.abort(new Error("API Hard Timeout (10 minutes)"))},_),ee=U>0,S;ee&&(S=setTimeout(()=>{Q.abort(new Error(`Stream stalled or delayed response (${U}ms idle)`))},U));let ae=o(()=>{ee&&(S&&clearTimeout(S),Q.signal.aborted||(S=setTimeout(()=>{Q.abort(new Error(`Stream stalled or delayed response (${U}ms idle)`))},U)))},"resetIdleTimer"),we=e.abortSignal?AbortSignal.any([e.abortSignal,Q.signal]):Q.signal,Oe=us(I,g);Wt("[resilience:request]",{provider:R,attempt:D,fallbackActive:!1,payloadBytes:Oe,payloadBucket:fs(Oe)});let ot={modelOverride:m,onTextDelta:o(H=>{A.markTextDelta(H),ae();let ke=H.includes("```")||ht.some(Ie=>H.includes(Ie))?Yr(H):H;ke.length!==0&&e.events?.onTextDelta?.(ke)},"onTextDelta"),onThinkingDelta:o(H=>{A.markThinkingDelta(H),ae(),e.events?.onThinkingDelta?.(H)},"onThinkingDelta"),onThinkingEnd:o(H=>{e.events?.onThinkingEnd?.(H)},"onThinkingEnd"),onToolInputDelta:e.events?.onToolInputDelta,onRateLimit:o((H,J,ke)=>{ae(),e.events&&Ft(e.events,H,J,ke)},"onRateLimit"),onRetryAfter:o(H=>{ae(),u=It(u,{provider:H.provider,waitMs:H.waitMs,reason:H.reason,source:H.source}),e.events?.onRetryAfter?.(H)},"onRetryAfter")};try{if(P=await w.stream(I,[...x],g,N,ot,we),P.stopReason==="max_tokens"&&!Ge&&!process.env.KODAX_MAX_OUTPUT_TOKENS&&w.getEffectiveMaxOutputTokens(m)<64e3){Ge=!0,w.setMaxOutputTokensOverride(64e3),e.events?.onRetry?.(`Output budget reached, escalating to ${64e3} tokens and retrying the same turn`,1,1),V&&clearTimeout(V),S&&clearTimeout(S),V=void 0,S=void 0,D-=1;continue}if(nf(P)&&P.stopReason!=="max_tokens"&&le<Lt&&!e.abortSignal?.aborted){le+=1,e.events?.onRetry?.(`Provider returned an empty turn, retrying ${le}/${Lt}`,le,Lt),V&&clearTimeout(V),S&&clearTimeout(S),V=void 0,S=void 0,D-=1,await Ut(Oi*le,e.abortSignal);continue}break}catch(H){let J=H instanceof Error?H:new Error(String(H));if(J.name==="AbortError"&&Q.signal.aborted&&!e.abortSignal?.aborted){let ce=Q.signal.reason?.message??"Stream stalled",{KodaXNetworkError:Pe}=await import("./dist-Z6U7TWKJ.js");J=new Pe(ce,!0)}let ke=A.inferFailureStage(),Ie=ur(J,ke);es(J,Ie);let G=L.decideRecoveryAction(J,Ie,D);if(ts(G,D),e.events?.onProviderRecovery?.({stage:G.failureStage,errorClass:G.reasonCode,attempt:D,maxAttempts:E.maxRetries,delayMs:G.delayMs,recoveryAction:G.action,ladderStep:G.ladderStep,fallbackUsed:G.shouldUseNonStreaming,serverRetryAfterMs:G.serverRetryAfterMs}),G.reasonCode==="rate_limit"&&e.events&&Ft(e.events,D,E.maxRetries,G.delayMs),!e.events?.onProviderRecovery&&G.action!=="manual_continue"&&e.events?.onRetry?.(`${ps(J)} \xB7 retry ${D}/${E.maxRetries} in ${Math.round(G.delayMs/1e3)}s`,D,E.maxRetries),G.shouldUseNonStreaming&&typeof w.complete=="function"){let ce=new AbortController,Pe=e.abortSignal?AbortSignal.any([e.abortSignal,ce.signal]):ce.signal,_n=setTimeout(()=>{ce.abort(new Error("API Hard Timeout (10 minutes)"))},_);try{S&&clearTimeout(S),V&&clearTimeout(V),V=void 0,S=void 0,A.beginRequest(R,m??w.getModel?.()??"unknown",I,D,!0),pr(A.snapshot()),P=await w.complete(I,[...x],g,N,{modelOverride:m,onTextDelta:o(te=>{A.markTextDelta(te),e.events?.onTextDelta?.(te)},"onTextDelta"),onThinkingDelta:o(te=>{A.markThinkingDelta(te),e.events?.onThinkingDelta?.(te)},"onThinkingDelta"),onThinkingEnd:o(te=>{e.events?.onThinkingEnd?.(te)},"onThinkingEnd"),signal:Pe},Pe);break}catch(te){J=te instanceof Error?te:new Error(String(te))}finally{clearTimeout(_n)}}if(G.action==="sanitize_thinking_and_retry"){let ce=L.executeRecovery(I,G);hr(G.action,ce),I=ce.messages,V&&clearTimeout(V),S&&clearTimeout(S),V=void 0,S=void 0,D-=1,await Ut(G.delayMs,e.abortSignal);continue}if(G.action==="manual_continue"||D>=E.maxRetries)throw Object.defineProperty(J,"__kodaxRecoveredMessages",{value:I,enumerable:!1}),J;let it=L.executeRecovery(I,G);hr(G.action,it),I=it.messages,V&&clearTimeout(V),S&&clearTimeout(S),V=void 0,S=void 0,await Ut(G.delayMs,e.abortSignal);continue}finally{V&&clearTimeout(V),S&&clearTimeout(S)}}let Ce=0,ge=(P.textBlocks??[]).map(Q=>Q.text).join(""),Me=P.thinkingBlocks?[...P.thinkingBlocks]:void 0;for(;P.stopReason==="max_tokens"&&(P.toolBlocks?.length??0)===0&&ge.trim().length>0&&Ce<3;){Ce+=1,e.events?.onTextDelta?.(`
|
|
117
117
|
|
|
118
118
|
[max_tokens reached, continuing...]
|
|
119
119
|
|
|
@@ -274,7 +274,7 @@ ${e.verification.changedPaths?.map(r=>`- ${r}`).join(`
|
|
|
274
274
|
`)}o(Zp,"buildVerificationRepairPrompt");async function Fc(e,t,n,r,i=n){if(n===void 0)return e;let s;try{return await Promise.race([e,new Promise((c,a)=>{s=setTimeout(()=>{r.childAbortControllers?.get(t)?.abort(),a(new Error(`workflow task ${t} timed out after ${i??n}ms`))},n)})])}finally{s&&clearTimeout(s)}}o(Fc,"waitForChildPromise");function Bc(e,t){return{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}:{}}}o(Bc,"buildBundle");function Oo(e,t){if(e.cancelledChildren.includes(t))return{status:"stopped",snapStatus:"aborted",finalText:""};let n=e.results[0],r=Kp(n?.summary??"",n?.digest);return n?.status==="completed"?{status:"completed",snapStatus:"completed",finalText:r,...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}:{}}:{status:"failed",snapStatus:"failed",finalText:r,...n?.limitReached?{limitReached:!0}:{},...n?.provider?{provider:n.provider}:{},...n?.model?{model:n.model}:{}}}o(Oo,"deriveTerminal");function Gc(e){let{ctx:t,childOptions:n}=e,r=e.runChild??ws,i=e.queue??ve(),s=e.listChangedFiles??Xp,c=e.now??(()=>Date.now()),a=0,l=e.generateId??(()=>`wf-child-${a+=1}`),u=new Map,m=new Set,d=new Map,f=o(()=>e.onTaskSummary!==void 0||m.size>0,"hasTaskSummaryObservers"),p=o((k,v)=>{try{e.onTaskSummary?.(k,v)}catch{}for(let T of m)try{T(k,v)}catch{}},"notifyTaskSummary");return{spawn:o(async k=>{let v=l(),T=Bc(v,k),C=Vp(k).verification,$=zp(),O=k.isolation!=="worktree",q=_o(C)?Ao(t,s):Promise.resolve({paths:[]}),w=t.childProgressSnapshots,R=o(async _=>{let U=new AbortController;t.childAbortControllers?.set(v,U),w&&ks(w,{childId:v,startedAt:c(),maxIterations:n.maxIterationsPerChild,parentRole:n.parentRole,readOnly:_.readOnly,specialistName:_.specialistName});let A={...n,parentOptions:{...n.parentOptions,events:Jp(n.parentOptions.events,$)},maxParallel:1,workflowChild:!0,...e.runId!==void 0?{workflowCorrelation:{workflowRunId:e.runId,childAgentId:v,itemId:`agent:${v}`}}:{},childActivityName:k.name,workflowDigestMode:f()?"async":"blocking",...f()?{onWorkflowChildDigest:o(L=>{p(L.childId,{...L.digest?{summary:L.digest}:{},summaryKind:L.digest?"digest":"digest-failed",...L.totalTokensUsed>0?{usage:{totalTokens:L.totalTokensUsed}}:{}})},"onWorkflowChildDigest")}:{},abortSignal:U.signal,snapshotUpdater:w?L=>ys(w,v,L):void 0},F;try{return await q,F=await r([_],t,A),F}finally{if(t.childAbortControllers?.delete(v),w){let L=F?Oo(F,v):{snapStatus:"failed",finalText:""};Cr(w,v,{status:L.snapStatus,finalText:L.finalText,endedAt:c()})}}},"runBundle"),E=R(T);return u.set(v,{name:k.name,input:k,bundle:T,promise:E,runBundle:R,verification:C,changedPathBaseline:q,mutationRecorder:$,acceptToolMutationEvidence:O,repairAttempts:0}),jn(d,v,E),{taskId:v,name:k.name}},"spawn"),wait:o(async(k,v)=>{let T=u.get(k);if(!T)throw new Error(`unknown workflow task: ${k}`);let N=Gp(v),C=Date.now(),$=o(async E=>{if(N===void 0)return Fc(E,k,void 0,t);let _=Date.now()-C,U=N-_;if(U<=0)throw t.childAbortControllers?.get(k)?.abort(),new Error(`workflow task ${k} timed out after ${N}ms`);return Fc(E,k,Math.max(1,Math.floor(U)),t,N)},"waitForAttempt"),O=await $(T.promise),q=O.totalTokensUsed,w=Oo(O,k),R=T.verification?jc({verification:T.verification,term:w,before:await T.changedPathBaseline,after:_o(T.verification)?await Ao(t,s):{paths:[]},mutationRecorder:T.mutationRecorder,ctx:t,acceptToolMutationEvidence:T.acceptToolMutationEvidence}):void 0;for(w.limitReached===!0&&R===void 0&&w.status==="completed"&&(R=Uc(),w={...w,status:"completed_unverified",snapStatus:"completed",finalText:Mo(w.finalText,R)});Qp({entry:T,term:w,verification:R});){T.repairAttempts+=1;let E=Bc(k,{...T.input,prompt:Zp({originalPrompt:T.input.prompt,previousFinalText:w.finalText,verification:R,attempt:T.repairAttempts})});T.promise=T.runBundle(E),jn(d,k,T.promise),O=await $(T.promise),q+=O.totalTokensUsed,w=Oo(O,k),R=T.verification?jc({verification:T.verification,term:w,before:await T.changedPathBaseline,after:_o(T.verification)?await Ao(t,s):{paths:[]},mutationRecorder:T.mutationRecorder,ctx:t,acceptToolMutationEvidence:T.acceptToolMutationEvidence}):void 0,w.limitReached===!0&&R===void 0&&w.status==="completed"&&(R=Uc(),w={...w,status:"completed_unverified",snapStatus:"completed",finalText:Mo(w.finalText,R)})}if(R!==void 0&&!R.ok&&w.status==="completed"){let E=R.enforcement==="warn";w={...w,status:E?"completed_unverified":"failed",snapStatus:E?"completed":"failed",finalText:Mo(w.finalText,R)}}return Cr(t.childProgressSnapshots,k,{status:w.snapStatus,finalText:w.finalText,endedAt:c()}),{taskId:k,name:T.name,status:w.status,finalText:w.finalText,...w.digest?{digest:w.digest}:{},...w.digestFailed?{digestFailed:!0}:{},...w.digestPending?{digestPending:!0}:{},...R!==void 0?{verification:R}:{},...w.limitReached?{limitReached:!0}:{},...w.provider?{provider:w.provider}:{},...w.model?{model:w.model}:{},usage:{totalTokens:q}}},"wait"),output:o(async k=>{let v=u.get(k)?.name??k,T=t.childProgressSnapshots?.get(k);if(!T)return{taskId:k,name:v,status:"running"};let N=T.status==="aborted"?"stopped":T.status;return T.finalText!==void 0?{taskId:k,name:v,status:N,lastText:T.finalText}:{taskId:k,name:v,status:N}},"output"),send:o(async(k,v)=>{ci({to:k,priority:"user",mode:"prompt",content:v,registry:d,queue:i})},"send"),stop:o(async k=>{t.childAbortControllers?.get(k)?.abort()},"stop"),subscribeTaskSummaryUpdates:o(k=>(m.add(k),()=>{m.delete(k)}),"subscribeTaskSummaryUpdates")}}o(Gc,"createCodingWorkflowBackend");import{mkdirSync as eh,appendFileSync as th,writeFileSync as bn}from"node:fs";import{join as et}from"node:path";function En(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,120);return t.length>0?t:"artifact"}o(En,"safeWorkflowArtifactName");function qc(e,t={}){let n=t.now??(()=>Date.now()),r=et(e,"artifacts");eh(r,{recursive:!0});let i=et(e,"events.jsonl");return{runDir:e,onEvent:o(s=>{th(i,`${JSON.stringify({...s,ts:n()})}
|
|
275
275
|
`,"utf8")},"onEvent"),writeArtifact:o((s,c)=>{let a=et(r,`${En(s)}.json`);return bn(a,JSON.stringify(c,null,2),"utf8"),{name:s,path:a}},"writeArtifact"),writeScriptSnapshot:o(s=>{let c=et(e,"script.js");if(bn(c,s.source,"utf8"),!s.manifest)return{scriptPath:c};let a=et(e,"manifest.json");return bn(a,`${JSON.stringify(s.manifest,null,2)}
|
|
276
276
|
`,"utf8"),{scriptPath:c,manifestPath:a}},"writeScriptSnapshot"),writeRunJson:o(s=>{let c=Dt(s.processMetadata?.hostMetadata),a={runId:s.state.runId,workflow:s.meta.name,status:s.state.status,totalSpawned:s.state.totalSpawned,artifacts:s.state.artifacts.map(l=>l.name),eventCount:s.state.events.length,startedAt:s.startedAt,endedAt:s.endedAt,args:s.args,...s.resultSummary!==void 0?{resultSummary:s.resultSummary}:{},...s.processMetadata?.displayName!==void 0?{displayName:s.processMetadata.displayName}:{},...s.processMetadata?.goal!==void 0?{goal:s.processMetadata.goal}:{},...s.processMetadata?.source!==void 0?{source:s.processMetadata.source}:{},...s.processMetadata?.savedWorkflowName!==void 0?{savedWorkflowName:s.processMetadata.savedWorkflowName}:{},...s.processMetadata?.sourceRunId!==void 0?{sourceRunId:s.processMetadata.sourceRunId}:{},...s.processMetadata?.sourceWorkflowName!==void 0?{sourceWorkflowName:s.processMetadata.sourceWorkflowName}:{},...s.processMetadata?.revisionOf!==void 0?{revisionOf:s.processMetadata.revisionOf}:{},...c!==void 0?{hostMetadata:c}:{},...s.scriptSnapshot?{scriptSnapshotPath:s.scriptSnapshot.scriptPath,...s.scriptSnapshot.manifestPath?{manifestSnapshotPath:s.scriptSnapshot.manifestPath}:{}}:{}};bn(et(e,"run.json"),`${JSON.stringify(a,null,2)}
|
|
277
|
-
`,"utf8")},"writeRunJson")}}o(qc,"createRunGraphWriter");import{dirname as uh}from"node:path";import{execFile as nh}from"node:child_process";import{promisify as rh}from"node:util";import{statSync as oh}from"node:fs";import{join as ih}from"node:path";var sh=rh(nh);function Po(e){return ih(e,"worktrees")}o(Po,"workflowWorktreeBaseDir");var ah=360*60*1e3;function Kc(e,t){return sh("git",[...e],{cwd:t}).then(n=>n.stdout)}o(Kc,"defaultRunGit");function ch(e){return oh(e).mtimeMs}o(ch,"defaultMtimeMs");function dh(e){let t=[],n,r,i=o(()=>{n&&t.push(r?{path:n,branch:r}:{path:n}),n=void 0,r=void 0},"flush");for(let s of e.split(/\r?\n/))s.startsWith("worktree ")?(i(),n=s.slice(9).trim()):s.startsWith("branch ")&&(r=s.slice(7).trim().replace(/^refs\/heads\//,""));return i(),t}o(dh,"parseWorktreeList");function Vc(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}o(Vc,"normalize");function Xc(e,t){let n=Vc(e),r=Vc(t);return n===r||n.startsWith(`${r}/`)}o(Xc,"isUnder");async function lh(e,t,n){try{let i=(await t(["status","--porcelain"],e.path)).split(/\r?\n/).filter(a=>a.trim().length>0).length,s=await t(["rev-list","--count","HEAD","--not","--remotes"],e.path),c=Number.parseInt(s.trim(),10)||0;return i>0||c>0}catch(r){return n.push(`retain ${e.path}: cannot verify worktree cleanliness: ${r instanceof Error?r.message:String(r)}`),!0}}o(lh,"worktreeHasChanges");async function zc(e,t,n,r,i){if(await lh(e,n,i)){i.push(`retain ${e.path}: worktree has unmerged changes`);return}try{await n(["worktree","remove",e.path,"--force"],t),r.push(e.path)}catch(s){i.push(`remove ${e.path}: ${s instanceof Error?s.message:String(s)}`);return}if(e.branch)try{await n(["branch","-D",e.branch],t)}catch{}}o(zc,"removeWorktree");async function Yc(e,t,n){try{let r=await t(["worktree","list","--porcelain"],e);return dh(r)}catch(r){n.push(`list worktrees: ${r instanceof Error?r.message:String(r)}`);return}}o(Yc,"listWorktrees");async function Io(e,t,n){try{await t(["worktree","prune"],e)}catch(r){n.push(`prune: ${r instanceof Error?r.message:String(r)}`)}}o(Io,"prune");async function Jc(e,t={}){let n=[],r=[];if(!e.gitRoot)return{removed:r,warnings:n};let i=t.runGit??Kc,s=await Yc(e.gitRoot,i,n);if(!s)return{removed:r,warnings:n};for(let c of s)Xc(c.path,e.baseDir)&&await zc(c,e.gitRoot,i,r,n);return r.length>0&&await Io(e.gitRoot,i,n),{removed:r,warnings:n}}o(Jc,"sweepWorkflowRunWorktrees");async function Qc(e,t={}){let n=[],r=[];if(!e.gitRoot)return{removed:r,warnings:n};let i=t.runGit??Kc,s=t.mtimeMs??ch,c=t.now??(()=>Date.now()),a=e.maxAgeMs??ah;await Io(e.gitRoot,i,n);let l=await Yc(e.gitRoot,i,n);if(!l)return{removed:r,warnings:n};for(let u of l){if(!Xc(u.path,e.workflowRunsRoot))continue;let m;try{m=c()-s(u.path)}catch{continue}m>=a&&await zc(u,e.gitRoot,i,r,n)}return r.length>0&&await Io(e.gitRoot,i,n),{removed:r,warnings:n}}o(Qc,"pruneStaleWorkflowWorktrees");var fh=200,No={maxAgents:64,maxConcurrency:16,tokenBudget:2e5};function mh(e,t){let n=e.meta,r=Et(n,t);return{name:n.name,description:n.description,phases:n.phases??[],...n.plannedAgents!==void 0?{plannedAgents:n.plannedAgents}:{},maxAgents:r.maxAgents??null,maxConcurrency:r.maxConcurrency??null,tokenBudget:r.tokenBudget??null,writesFiles:n.readOnly!==!0}}o(mh,"buildApprovalSummary");function Zc(e,t){if(e!==void 0)return!Number.isInteger(e)||e<=0?1:Math.min(e,t)}o(Zc,"clampLimit");function Do(e,t,n){let r=Zc(e,n),i=Zc(t,n);return r===void 0?i:i===void 0?r:Math.min(r,i)}o(Do,"clampEffectiveLimit");function Et(e,t){let n=Do(e.maxAgents,t?.maxAgents,No.maxAgents),r=Do(e.maxConcurrency,t?.maxConcurrency,No.maxConcurrency),i=Do(e.tokenBudget,t?.tokenBudget,No.tokenBudget);return{...n!==void 0?{maxAgents:n}:{},...r!==void 0?{maxConcurrency:r}:{},...i!==void 0?{tokenBudget:i}:{}}}o(Et,"clampWorkflowLimits");function ed(e){if(typeof e=="string"&&e.trim().length>0)return e;if(typeof e!="object"||e===null)return;let t=e,n=t.synthesis;if(typeof n=="string"&&n.trim().length>0)return n;if(typeof n=="object"&&n!==null){let r=n.text;if(typeof r=="string"&&r.trim().length>0)return r}for(let r of["summary","report","text","result"]){let i=t[r];if(typeof i=="string"&&i.trim().length>0)return i}}o(ed,"workflowResultSummary");async function $o(e){let t=Et(e.module.meta,e.hostPolicy),n=mh(e.module,e.hostPolicy);if(e.approval&&!await e.approval(n))return{kind:"denied",summary:n};let r=e.now??(()=>Date.now()),i=e.ctx?.executionCwd??e.ctx?.gitRoot;await Qc({workflowRunsRoot:uh(e.runDir),gitRoot:i},{now:r,...e.worktreeSweepDeps});let s=qc(e.runDir,{now:r}),c=e.onWorkflowProcessEvent?Ke({runId:e.runId,workflowName:e.module.meta.name,displayName:e.processMetadata?.displayName??e.module.meta.name,...e.processMetadata?.goal!==void 0?{goal:e.processMetadata.goal}:{},...e.processMetadata?.source!==void 0?{source:e.processMetadata.source}:{},...e.processMetadata?.savedWorkflowName!==void 0?{savedWorkflowName:e.processMetadata.savedWorkflowName}:{},...e.processMetadata?.sourceRunId!==void 0?{sourceRunId:e.processMetadata.sourceRunId}:{},...e.processMetadata?.sourceWorkflowName!==void 0?{sourceWorkflowName:e.processMetadata.sourceWorkflowName}:{},...e.processMetadata?.revisionOf!==void 0?{revisionOf:e.processMetadata.revisionOf}:{},...e.processMetadata?.hostMetadata!==void 0?{hostMetadata:{...e.processMetadata.hostMetadata}}:{},...e.module.meta.phases!==void 0?{phases:e.module.meta.phases}:{},...t.maxAgents!==void 0?{maxAgents:t.maxAgents}:{},...e.module.meta.plannedAgents!==void 0?{plannedAgents:e.module.meta.plannedAgents}:{},...t.tokenBudget!==void 0?{tokenBudget:t.tokenBudget}:{},now:o(()=>new Date(r()).toISOString(),"now")}):void 0,a=e.scriptSnapshot?s.writeScriptSnapshot(e.scriptSnapshot):void 0,l=e.backend??ph(e),m={...e.beforeSpawn?hh(l,e.beforeSpawn):l,writeArtifact:o(async(h,g)=>s.writeArtifact(h,g),"writeArtifact")},d=r(),f;try{f=await Mi({runId:e.runId,args:e.args,backend:m,limits:t,...e.signal?{signal:e.signal}:{},summarizeResult:ed,onEvent:o(h=>{s.onEvent(h),c&&e.onWorkflowProcessEvent?.(c.applyEvent(h)),e.onEvent?.(h)},"onEvent")},h=>e.module.run(h,e.args))}finally{await Jc({baseDir:Po(e.runDir),gitRoot:i},{now:r,...e.worktreeSweepDeps})}let p=f.ok?ed(f.result):void 0;return s.writeRunJson({meta:e.module.meta,args:e.args,state:f.state,startedAt:d,endedAt:r(),...a?{scriptSnapshot:a}:{},...p!==void 0?{resultSummary:p}:{},...e.processMetadata!==void 0?{processMetadata:e.processMetadata}:{}}),f.ok?{kind:"completed",result:f.result,state:f.state}:{kind:"failed",error:f.error,state:f.state}}o($o,"runWorkflowModule");function ph(e){if(!e.ctx||!e.childOptions)throw new Error("runWorkflowModule requires either a backend or ctx + childOptions");return Gc({ctx:e.ctx,childOptions:e.childOptions,runId:e.runId})}o(ph,"buildBackend");function hh(e,t){return{...e,spawn:o(async n=>(await t(),e.spawn(n)),"spawn")}}o(hh,"withBeforeSpawn");async function td(e){let t={...Ht({options:e.options,runtime:e.options.extensionRuntime,managedProtocolPayloadRef:{current:void 0}}),workflowWorktreeBaseDir:Po(e.runDir)},n={maxIterationsPerChild:fh,parentRole:"worker",parentHarness:"tool-dispatch",parentOptions:{provider:e.options.provider,model:e.options.model,reasoningMode:e.options.reasoningMode,extensionRuntime:e.options.extensionRuntime,events:e.options.events},...e.options.guardrails?{guardrails:e.options.guardrails}:{},...t.planModeBlockCheck?{planModeBlockCheck:t.planModeBlockCheck}:{}},r=e.onWorkflowProcessEvent||e.options.events?.onWorkflowProcessEvent?i=>{e.onWorkflowProcessEvent?.(i),e.options.events?.onWorkflowProcessEvent?.(i)}:void 0;return $o({module:e.module,args:e.args,runId:e.runId,runDir:e.runDir,ctx:t,childOptions:n,...e.approval?{approval:e.approval}:{},...e.signal?{signal:e.signal}:{},...e.onEvent?{onEvent:e.onEvent}:{},...r?{onWorkflowProcessEvent:r}:{},...e.options.workflowHostPolicy?{hostPolicy:e.options.workflowHostPolicy}:{},...e.now?{now:e.now}:{},...e.scriptSnapshot?{scriptSnapshot:e.scriptSnapshot}:{},...e.processMetadata?{processMetadata:e.processMetadata}:{},...e.beforeSpawn?{beforeSpawn:e.beforeSpawn}:{}})}o(td,"runWorkflowFromOptions");import{mkdir as sd,readdir as gh,readFile as xt,rename as wh,unlink as Uo,writeFile as Fo}from"node:fs/promises";import{basename as kh,dirname as jo,join as We}from"node:path";import{pathToFileURL as yh}from"node:url";var ad=[".workflow.json",".ts",".mjs",".js"],Rt="0.7.49";function cd(){return"0.7.51"}o(cd,"currentKodaxWorkflowVersion");function vh(e){return e.endsWith(".workflow.json")?"capability-generated":"trusted-local"}o(vh,"executionForPath");function Th(e){let t=ad.find(n=>e.endsWith(n));return t?e.slice(0,-t.length):void 0}o(Th,"stripWorkflowSuffix");function Bo(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}o(Bo,"safeWorkflowName");function Wo(e){return typeof e=="object"&&e!==null}o(Wo,"isRecord");function nd(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`workflow run.json missing ${t}`);return n}o(nd,"readRequiredString");async function rd(e,t){if(!e)return[];let n;try{n=await gh(e)}catch{return[]}let r=new Map;for(let i of ad)for(let s of n){if(!s.endsWith(i))continue;let c=Th(s);if(!c||c.length===0||r.has(c))continue;let a=We(e,s);r.set(c,{name:c,path:a,source:t,execution:vh(a)})}return[...r.values()]}o(rd,"scanDir");async function St(e){let t=await rd(e.personal,"personal"),n=await rd(e.project,"project"),r=new Map;for(let i of t)r.set(i.name,i);for(let i of n)r.set(i.name,i);return[...r.values()].sort((i,s)=>i.name.localeCompare(s.name))}o(St,"discoverSavedWorkflows");function bh(e){return typeof e=="object"&&e!==null&&"meta"in e&&"run"in e&&typeof e.run=="function"}o(bh,"isWorkflowModule");function Eh(e){let t=e.default;if(bh(t))return t;let n=typeof t=="function"?t:e.run,r=e.workflow??e.meta;if(typeof n=="function"&&typeof r=="object"&&r!==null&&"name"in r)return{meta:r,run:n};throw new Error("invalid workflow module: expected a `{ meta, run }` default export, or `export const workflow = {...}` + a default run function")}o(Eh,"normalizeWorkflowModule");function xh(e){let t=JSON.parse(e);if(!Wo(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=Hn(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 r=fe(t.manifest);return{manifest:r,source:n,capsule:De({minKodaxVersion:Rt,manifest:r,source:n}),legacy:!0}}o(xh,"parseGeneratedWorkflowFile");async function Ho(e){let t=xh(await xt(e,"utf8"));return t.capsule??De({minKodaxVersion:Rt,manifest:t.manifest,source:t.source})}o(Ho,"loadSavedWorkflowCapsule");async function WR(e){if(e.endsWith(".workflow.json"))return Gn(await Ho(e));let t=await import(yh(e).href);return Eh(t)}o(WR,"loadSavedWorkflow");function Go(e){if(e.mayUseWorktree===!0)return{environment:["git-repo","worktree-capable"]}}o(Go,"deriveRequirements");function xn(e,t){dt(t,{filename:`${e.name}.workflow.js`,requireAsyncRun:!0})}o(xn,"assertGeneratedCapsuleSource");async function Rh(e){let t=Bo(e.name),n=fe(e.manifest);xn(n,e.source);let r=e.requires??Go(n),i=De({minKodaxVersion:e.minKodaxVersion??Rt,manifest:n,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...r!==void 0?{requires:r}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}});await sd(e.dir,{recursive:!0});let s=We(e.dir,`${t}.workflow.json`);return await Fo(s,`${JSON.stringify(i,null,2)}
|
|
277
|
+
`,"utf8")},"writeRunJson")}}o(qc,"createRunGraphWriter");import{dirname as uh}from"node:path";import{execFile as nh}from"node:child_process";import{promisify as rh}from"node:util";import{statSync as oh}from"node:fs";import{join as ih}from"node:path";var sh=rh(nh);function Po(e){return ih(e,"worktrees")}o(Po,"workflowWorktreeBaseDir");var ah=360*60*1e3;function Kc(e,t){return sh("git",[...e],{cwd:t}).then(n=>n.stdout)}o(Kc,"defaultRunGit");function ch(e){return oh(e).mtimeMs}o(ch,"defaultMtimeMs");function dh(e){let t=[],n,r,i=o(()=>{n&&t.push(r?{path:n,branch:r}:{path:n}),n=void 0,r=void 0},"flush");for(let s of e.split(/\r?\n/))s.startsWith("worktree ")?(i(),n=s.slice(9).trim()):s.startsWith("branch ")&&(r=s.slice(7).trim().replace(/^refs\/heads\//,""));return i(),t}o(dh,"parseWorktreeList");function Vc(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}o(Vc,"normalize");function Xc(e,t){let n=Vc(e),r=Vc(t);return n===r||n.startsWith(`${r}/`)}o(Xc,"isUnder");async function lh(e,t,n){try{let i=(await t(["status","--porcelain"],e.path)).split(/\r?\n/).filter(a=>a.trim().length>0).length,s=await t(["rev-list","--count","HEAD","--not","--remotes"],e.path),c=Number.parseInt(s.trim(),10)||0;return i>0||c>0}catch(r){return n.push(`retain ${e.path}: cannot verify worktree cleanliness: ${r instanceof Error?r.message:String(r)}`),!0}}o(lh,"worktreeHasChanges");async function zc(e,t,n,r,i){if(await lh(e,n,i)){i.push(`retain ${e.path}: worktree has unmerged changes`);return}try{await n(["worktree","remove",e.path,"--force"],t),r.push(e.path)}catch(s){i.push(`remove ${e.path}: ${s instanceof Error?s.message:String(s)}`);return}if(e.branch)try{await n(["branch","-D",e.branch],t)}catch{}}o(zc,"removeWorktree");async function Yc(e,t,n){try{let r=await t(["worktree","list","--porcelain"],e);return dh(r)}catch(r){n.push(`list worktrees: ${r instanceof Error?r.message:String(r)}`);return}}o(Yc,"listWorktrees");async function Io(e,t,n){try{await t(["worktree","prune"],e)}catch(r){n.push(`prune: ${r instanceof Error?r.message:String(r)}`)}}o(Io,"prune");async function Jc(e,t={}){let n=[],r=[];if(!e.gitRoot)return{removed:r,warnings:n};let i=t.runGit??Kc,s=await Yc(e.gitRoot,i,n);if(!s)return{removed:r,warnings:n};for(let c of s)Xc(c.path,e.baseDir)&&await zc(c,e.gitRoot,i,r,n);return r.length>0&&await Io(e.gitRoot,i,n),{removed:r,warnings:n}}o(Jc,"sweepWorkflowRunWorktrees");async function Qc(e,t={}){let n=[],r=[];if(!e.gitRoot)return{removed:r,warnings:n};let i=t.runGit??Kc,s=t.mtimeMs??ch,c=t.now??(()=>Date.now()),a=e.maxAgeMs??ah;await Io(e.gitRoot,i,n);let l=await Yc(e.gitRoot,i,n);if(!l)return{removed:r,warnings:n};for(let u of l){if(!Xc(u.path,e.workflowRunsRoot))continue;let m;try{m=c()-s(u.path)}catch{continue}m>=a&&await zc(u,e.gitRoot,i,r,n)}return r.length>0&&await Io(e.gitRoot,i,n),{removed:r,warnings:n}}o(Qc,"pruneStaleWorkflowWorktrees");var fh=200,No={maxAgents:64,maxConcurrency:16,tokenBudget:2e5};function mh(e,t){let n=e.meta,r=Et(n,t);return{name:n.name,description:n.description,phases:n.phases??[],...n.plannedAgents!==void 0?{plannedAgents:n.plannedAgents}:{},maxAgents:r.maxAgents??null,maxConcurrency:r.maxConcurrency??null,tokenBudget:r.tokenBudget??null,writesFiles:n.readOnly!==!0}}o(mh,"buildApprovalSummary");function Zc(e,t){if(e!==void 0)return!Number.isInteger(e)||e<=0?1:Math.min(e,t)}o(Zc,"clampLimit");function Do(e,t,n){let r=Zc(e,n),i=Zc(t,n);return r===void 0?i:i===void 0?r:Math.min(r,i)}o(Do,"clampEffectiveLimit");function Et(e,t){let n=Do(e.maxAgents,t?.maxAgents,No.maxAgents),r=Do(e.maxConcurrency,t?.maxConcurrency,No.maxConcurrency),i=Do(e.tokenBudget,t?.tokenBudget,No.tokenBudget);return{...n!==void 0?{maxAgents:n}:{},...r!==void 0?{maxConcurrency:r}:{},...i!==void 0?{tokenBudget:i}:{}}}o(Et,"clampWorkflowLimits");function ed(e){if(typeof e=="string"&&e.trim().length>0)return e;if(typeof e!="object"||e===null)return;let t=e,n=t.synthesis;if(typeof n=="string"&&n.trim().length>0)return n;if(typeof n=="object"&&n!==null){let r=n.text;if(typeof r=="string"&&r.trim().length>0)return r}for(let r of["summary","report","text","result"]){let i=t[r];if(typeof i=="string"&&i.trim().length>0)return i}}o(ed,"workflowResultSummary");async function $o(e){let t=Et(e.module.meta,e.hostPolicy),n=mh(e.module,e.hostPolicy);if(e.approval&&!await e.approval(n))return{kind:"denied",summary:n};let r=e.now??(()=>Date.now()),i=e.ctx?.executionCwd??e.ctx?.gitRoot;await Qc({workflowRunsRoot:uh(e.runDir),gitRoot:i},{now:r,...e.worktreeSweepDeps});let s=qc(e.runDir,{now:r}),c=e.onWorkflowProcessEvent?Ke({runId:e.runId,workflowName:e.module.meta.name,displayName:e.processMetadata?.displayName??e.module.meta.name,...e.processMetadata?.goal!==void 0?{goal:e.processMetadata.goal}:{},...e.processMetadata?.source!==void 0?{source:e.processMetadata.source}:{},...e.processMetadata?.savedWorkflowName!==void 0?{savedWorkflowName:e.processMetadata.savedWorkflowName}:{},...e.processMetadata?.sourceRunId!==void 0?{sourceRunId:e.processMetadata.sourceRunId}:{},...e.processMetadata?.sourceWorkflowName!==void 0?{sourceWorkflowName:e.processMetadata.sourceWorkflowName}:{},...e.processMetadata?.revisionOf!==void 0?{revisionOf:e.processMetadata.revisionOf}:{},...e.processMetadata?.hostMetadata!==void 0?{hostMetadata:{...e.processMetadata.hostMetadata}}:{},...e.module.meta.phases!==void 0?{phases:e.module.meta.phases}:{},...t.maxAgents!==void 0?{maxAgents:t.maxAgents}:{},...e.module.meta.plannedAgents!==void 0?{plannedAgents:e.module.meta.plannedAgents}:{},...t.tokenBudget!==void 0?{tokenBudget:t.tokenBudget}:{},now:o(()=>new Date(r()).toISOString(),"now")}):void 0,a=e.scriptSnapshot?s.writeScriptSnapshot(e.scriptSnapshot):void 0,l=e.backend??ph(e),m={...e.beforeSpawn?hh(l,e.beforeSpawn):l,writeArtifact:o(async(h,g)=>s.writeArtifact(h,g),"writeArtifact")},d=r(),f;try{f=await Mi({runId:e.runId,args:e.args,backend:m,limits:t,...e.signal?{signal:e.signal}:{},summarizeResult:ed,onEvent:o(h=>{s.onEvent(h),c&&e.onWorkflowProcessEvent?.(c.applyEvent(h)),e.onEvent?.(h)},"onEvent")},h=>e.module.run(h,e.args))}finally{await Jc({baseDir:Po(e.runDir),gitRoot:i},{now:r,...e.worktreeSweepDeps})}let p=f.ok?ed(f.result):void 0;return s.writeRunJson({meta:e.module.meta,args:e.args,state:f.state,startedAt:d,endedAt:r(),...a?{scriptSnapshot:a}:{},...p!==void 0?{resultSummary:p}:{},...e.processMetadata!==void 0?{processMetadata:e.processMetadata}:{}}),f.ok?{kind:"completed",result:f.result,state:f.state}:{kind:"failed",error:f.error,state:f.state}}o($o,"runWorkflowModule");function ph(e){if(!e.ctx||!e.childOptions)throw new Error("runWorkflowModule requires either a backend or ctx + childOptions");return Gc({ctx:e.ctx,childOptions:e.childOptions,runId:e.runId})}o(ph,"buildBackend");function hh(e,t){return{...e,spawn:o(async n=>(await t(),e.spawn(n)),"spawn")}}o(hh,"withBeforeSpawn");async function td(e){let t={...Ht({options:e.options,runtime:e.options.extensionRuntime,managedProtocolPayloadRef:{current:void 0}}),workflowWorktreeBaseDir:Po(e.runDir)},n={maxIterationsPerChild:fh,parentRole:"worker",parentHarness:"tool-dispatch",parentOptions:{provider:e.options.provider,model:e.options.model,reasoningMode:e.options.reasoningMode,extensionRuntime:e.options.extensionRuntime,events:e.options.events},...e.options.guardrails?{guardrails:e.options.guardrails}:{},...t.planModeBlockCheck?{planModeBlockCheck:t.planModeBlockCheck}:{}},r=e.onWorkflowProcessEvent||e.options.events?.onWorkflowProcessEvent?i=>{e.onWorkflowProcessEvent?.(i),e.options.events?.onWorkflowProcessEvent?.(i)}:void 0;return $o({module:e.module,args:e.args,runId:e.runId,runDir:e.runDir,ctx:t,childOptions:n,...e.approval?{approval:e.approval}:{},...e.signal?{signal:e.signal}:{},...e.onEvent?{onEvent:e.onEvent}:{},...r?{onWorkflowProcessEvent:r}:{},...e.options.workflowHostPolicy?{hostPolicy:e.options.workflowHostPolicy}:{},...e.now?{now:e.now}:{},...e.scriptSnapshot?{scriptSnapshot:e.scriptSnapshot}:{},...e.processMetadata?{processMetadata:e.processMetadata}:{},...e.beforeSpawn?{beforeSpawn:e.beforeSpawn}:{}})}o(td,"runWorkflowFromOptions");import{mkdir as sd,readdir as gh,readFile as xt,rename as wh,unlink as Uo,writeFile as Fo}from"node:fs/promises";import{basename as kh,dirname as jo,join as We}from"node:path";import{pathToFileURL as yh}from"node:url";var ad=[".workflow.json",".ts",".mjs",".js"],Rt="0.7.49";function cd(){return"0.7.52"}o(cd,"currentKodaxWorkflowVersion");function vh(e){return e.endsWith(".workflow.json")?"capability-generated":"trusted-local"}o(vh,"executionForPath");function Th(e){let t=ad.find(n=>e.endsWith(n));return t?e.slice(0,-t.length):void 0}o(Th,"stripWorkflowSuffix");function Bo(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}o(Bo,"safeWorkflowName");function Wo(e){return typeof e=="object"&&e!==null}o(Wo,"isRecord");function nd(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`workflow run.json missing ${t}`);return n}o(nd,"readRequiredString");async function rd(e,t){if(!e)return[];let n;try{n=await gh(e)}catch{return[]}let r=new Map;for(let i of ad)for(let s of n){if(!s.endsWith(i))continue;let c=Th(s);if(!c||c.length===0||r.has(c))continue;let a=We(e,s);r.set(c,{name:c,path:a,source:t,execution:vh(a)})}return[...r.values()]}o(rd,"scanDir");async function St(e){let t=await rd(e.personal,"personal"),n=await rd(e.project,"project"),r=new Map;for(let i of t)r.set(i.name,i);for(let i of n)r.set(i.name,i);return[...r.values()].sort((i,s)=>i.name.localeCompare(s.name))}o(St,"discoverSavedWorkflows");function bh(e){return typeof e=="object"&&e!==null&&"meta"in e&&"run"in e&&typeof e.run=="function"}o(bh,"isWorkflowModule");function Eh(e){let t=e.default;if(bh(t))return t;let n=typeof t=="function"?t:e.run,r=e.workflow??e.meta;if(typeof n=="function"&&typeof r=="object"&&r!==null&&"name"in r)return{meta:r,run:n};throw new Error("invalid workflow module: expected a `{ meta, run }` default export, or `export const workflow = {...}` + a default run function")}o(Eh,"normalizeWorkflowModule");function xh(e){let t=JSON.parse(e);if(!Wo(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=Hn(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 r=fe(t.manifest);return{manifest:r,source:n,capsule:De({minKodaxVersion:Rt,manifest:r,source:n}),legacy:!0}}o(xh,"parseGeneratedWorkflowFile");async function Ho(e){let t=xh(await xt(e,"utf8"));return t.capsule??De({minKodaxVersion:Rt,manifest:t.manifest,source:t.source})}o(Ho,"loadSavedWorkflowCapsule");async function WR(e){if(e.endsWith(".workflow.json"))return Gn(await Ho(e));let t=await import(yh(e).href);return Eh(t)}o(WR,"loadSavedWorkflow");function Go(e){if(e.mayUseWorktree===!0)return{environment:["git-repo","worktree-capable"]}}o(Go,"deriveRequirements");function xn(e,t){dt(t,{filename:`${e.name}.workflow.js`,requireAsyncRun:!0})}o(xn,"assertGeneratedCapsuleSource");async function Rh(e){let t=Bo(e.name),n=fe(e.manifest);xn(n,e.source);let r=e.requires??Go(n),i=De({minKodaxVersion:e.minKodaxVersion??Rt,manifest:n,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...r!==void 0?{requires:r}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}});await sd(e.dir,{recursive:!0});let s=We(e.dir,`${t}.workflow.json`);return await Fo(s,`${JSON.stringify(i,null,2)}
|
|
278
278
|
`,"utf8"),{name:t,path:s,source:"project",execution:"capability-generated"}}o(Rh,"saveGeneratedWorkflow");async function od(e,t){await Fo(e,`${JSON.stringify(t,null,2)}
|
|
279
279
|
`,"utf8")}o(od,"writeCapsuleFile");async function Sh(e){try{return await xt(e,"utf8"),!0}catch{return!1}}o(Sh,"fileExists");async function dd(e){let t=(await St(e.dirs)).filter(a=>a.name===e.name).filter(a=>e.source===void 0||a.source===e.source);if(t.length===0)throw new Error(`saved workflow not found: ${e.name}`);if(t.length>1)throw new Error(`ambiguous saved workflow name: ${e.name}`);let n=t[0];if(!n.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be renamed");let r=Bo(e.newName),i=We(jo(n.path),`${r}.workflow.json`);if(i!==n.path&&await Sh(i))throw new Error(`saved workflow already exists: ${r}`);let s=await Ho(n.path);xn(s.manifest,s.source);let c=De({minKodaxVersion:s.minKodaxVersion,manifest:{...s.manifest,name:r},source:s.source,...s.intent!==void 0?{intent:s.intent}:{},...s.inputs!==void 0?{inputs:s.inputs}:{},...s.requires!==void 0?{requires:s.requires}:{},...s.provenance!==void 0?{provenance:s.provenance}:{}});return await Fo(i,`${JSON.stringify(c,null,2)}
|
|
280
280
|
`,"utf8"),i!==n.path&&await Uo(n.path),{name:r,path:i,source:n.source,execution:"capability-generated"}}o(dd,"renameSavedWorkflow");async function ld(e){let t=(await St(e.dirs)).filter(r=>r.name===e.name).filter(r=>e.source===void 0||r.source===e.source);if(t.length===0)throw new Error(`saved workflow not found: ${e.name}`);if(t.length>1)throw new Error(`ambiguous saved workflow name: ${e.name}`);let n=t[0];if(!n.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be deleted");return await Uo(n.path),n}o(ld,"deleteSavedWorkflow");async function ud(e){let t=Bo(e.name),n=(await St(e.dirs)).filter(p=>p.name===t).filter(p=>e.savedSource===void 0||p.source===e.savedSource);if(n.length===0)throw new Error(`saved workflow not found: ${t}`);if(n.length>1)throw new Error(`ambiguous saved workflow name: ${t}`);let r=n[0];if(!r.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be replaced");let i=fe({...e.manifest,name:t});xn(i,e.source);let s=e.requires??Go(i),c=De({minKodaxVersion:e.minKodaxVersion??Rt,manifest:i,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...s!==void 0?{requires:s}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}}),a=await Ho(r.path),l=new Date().toISOString().replace(/[:.]/g,"-"),u=We(jo(r.path),".revisions",t),m=`${l}-${process.hrtime.bigint().toString(36)}`,d=We(u,`${t}-${m}.workflow.json`),f=We(jo(r.path),`.${t}.${process.pid}.${Date.now().toString(36)}.tmp`);await sd(u,{recursive:!0}),await od(d,a);try{await od(f,c),await wh(f,r.path)}catch(p){try{await Uo(f)}catch{}throw p}return{name:t,path:r.path,source:r.source,execution:"capability-generated",previousPath:d}}o(ud,"replaceSavedWorkflow");function _h(e){if(!Wo(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}o(_h,"readOptionalOriginalRequest");function fd(e){return Ah(e)}o(fd,"buildCapsuleFromRun");async function Ah(e){let t=JSON.parse(await xt(We(e.runDir,"run.json"),"utf8"));if(!Wo(t))throw new Error("workflow run.json must be an object");let n=nd(t,"scriptSnapshotPath"),r=nd(t,"manifestSnapshotPath"),i=await xt(n,"utf8"),s=fe(JSON.parse(await xt(r,"utf8")));xn(s,i);let c=typeof t.runId=="string"&&t.runId.length>0?t.runId:kh(e.runDir),a=_h(t.args),l=Go(s),u={taskClass:s.patterns[0]??s.name,...a!==void 0?{originalRequest:a}:{},reusableFor:[s.description]},m={description:"Provide new workflow args matching the generated request shape.",..."args"in t?{examples:[t.args]}:{}};return De({minKodaxVersion:Rt,manifest:s,source:i,intent:u,inputs:m,...l!==void 0?{requires:l}:{},provenance:{fromRunId:c,createdAt:new Date().toISOString(),kodaxVersion:cd()}})}o(Ah,"readCapsuleFromRun");async function HR(e){let t=await fd(e);return{capsule:t,module:Gn(t)}}o(HR,"loadGeneratedWorkflowFromRun");async function GR(e){let t=await fd(e);return Rh({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})}o(GR,"saveGeneratedWorkflowFromRun");function Ae(e,t,n,r){e.push({severity:t,requirement:n,message:r})}o(Ae,"addRequirementIssue");function id(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e.trim());if(t)return[Number(t[1]),Number(t[2]),Number(t[3])]}o(id,"parseSemver");function Ch(e,t){for(let n=0;n<3;n+=1){let r=e[n]-t[n];if(r!==0)return r}return 0}o(Ch,"compareSemver");function Mh(e,t,n){let r=id(t),i=id(n);if(!r){Ae(e,"error","kodax:min-version",`workflow minKodaxVersion is not valid semver: ${t}`);return}if(!i){Ae(e,"warning","kodax:min-version",`cannot verify workflow minKodaxVersion ${t}; current version is unknown`);return}Ch(i,r)<0&&Ae(e,"error","kodax:min-version",`workflow requires KodaX >= ${t}, current version is ${n}`)}o(Mh,"addMinVersionIssue");function Lo(e,t,n,r){if(!n)return;if(!r){for(let s of n)Ae(e,"warning",`${t}:${s}`,`workflow requires ${t}:${s}, but no ${t} inventory was provided`);return}let i=new Set(r);for(let s of n)i.has(s)||Ae(e,"error",`${t}:${s}`,`missing required workflow ${t}: ${s}`)}o(Lo,"addMissingItems");function md(e,t={}){let n=Hn(e),r=[],i=n.requires;Mh(r,n.minKodaxVersion,t.kodaxVersion??cd()),i?.environment?.includes("git-repo")&&t.isGitRepo===!1&&Ae(r,"error","environment:git-repo","workflow requires a git repository"),i?.environment?.includes("worktree-capable")&&t.worktreeCapable===!1&&Ae(r,"error","environment:worktree-capable","workflow may request git worktree isolation");try{dt(n.source,{filename:`${n.manifest.name}.workflow.js`,requireAsyncRun:!0})}catch(s){let c=s instanceof Error?s.message:String(s);Ae(r,"error","workflow:source",c)}return Lo(r,"tools",i?.tools,t.availableTools),Lo(r,"mcp",i?.mcp,t.availableMcp),Lo(r,"skills",i?.skills,t.availableSkills),{ok:!r.some(s=>s.severity==="error"),issues:r}}o(md,"preflightWorkflowCapsule");function Rn(e){return{runId:e.runId,workflow:e.workflow,status:e.status,runDir:e.runDir,totalSpawned:e.totalSpawned,eventCount:e.eventCount,startedAt:e.startedAt,...e.endedAt!==void 0?{endedAt:e.endedAt}:{},...e.error!==void 0?{error:e.error}:{},...e.resultText!==void 0?{resultText:e.resultText}:{}}}o(Rn,"snapshot");function Oh(e,t){return t?"stopped":e.kind==="completed"?"completed":e.kind==="denied"?"denied":"failed"}o(Oh,"terminalStatus");function Ih(e){if(typeof e=="string"&&e.trim().length>0)return e;if(typeof e!="object"||e===null)return;let t=e,n=t.synthesis;if(typeof n=="string"&&n.trim().length>0)return n;if(typeof n=="object"&&n!==null){let r=n.text;if(typeof r=="string"&&r.trim().length>0)return r}for(let r of["summary","report","text","result"]){let i=t[r];if(typeof i=="string"&&i.trim().length>0)return i}}o(Ih,"resultText");function Ph(e){return e instanceof Error?e:new Error(String(e))}o(Ph,"toError");function pd(e,t){let n=Ph(t),r={runId:e.runId,status:"failed",totalSpawned:e.totalSpawned,events:[],artifacts:[]};return{kind:"failed",error:n,state:r}}o(pd,"failedOutcome");function Nh(e={}){let t=e.now??(()=>Date.now()),n=new Map,r=new Set,i=o(()=>new Date(t()).toISOString(),"isoNow"),s=o(d=>{for(let f of r)try{f(d)}catch{}},"notifyProcess"),c=o(async d=>{for(;d.status==="paused"&&!d.controller.signal.aborted;)await new Promise(f=>d.pauseWaiters.push(f));if(d.controller.signal.aborted)throw new Error("workflow stopped")},"waitIfPaused"),a=o(d=>{let f=d.pauseWaiters.splice(0);for(let p of f)p()},"releasePauseWaiters"),l=o((d,f)=>p=>{d.eventCount+=1,p.type==="agent_spawned"&&(d.totalSpawned+=1),s(d.process.applyEvent(p)),f?.(p)},"onEvent"),u=o((d,f,p)=>{let h=new AbortController;p&&p.addEventListener("abort",()=>h.abort(),{once:!0});let g={runId:d.runId,workflow:d.workflow,status:"running",runDir:f,totalSpawned:0,eventCount:0,startedAt:t(),controller:h,pauseWaiters:[],process:Ke({runId:d.runId,workflowName:d.workflow,displayName:d.processMetadata?.displayName??d.workflow,...d.processMetadata?.goal!==void 0?{goal:d.processMetadata.goal}:{},...d.processMetadata?.source!==void 0?{source:d.processMetadata.source}:{},...d.processMetadata?.savedWorkflowName!==void 0?{savedWorkflowName:d.processMetadata.savedWorkflowName}:{},...d.processMetadata?.sourceRunId!==void 0?{sourceRunId:d.processMetadata.sourceRunId}:{},...d.processMetadata?.sourceWorkflowName!==void 0?{sourceWorkflowName:d.processMetadata.sourceWorkflowName}:{},...d.processMetadata?.revisionOf!==void 0?{revisionOf:d.processMetadata.revisionOf}:{},...d.processMetadata?.hostMetadata!==void 0?{hostMetadata:{...d.processMetadata.hostMetadata}}:{},...d.phases!==void 0?{phases:d.phases}:{},...d.maxAgents!==void 0?{maxAgents:d.maxAgents}:{},...d.plannedAgents!==void 0?{plannedAgents:d.plannedAgents}:{},...d.tokenBudget!==void 0?{tokenBudget:d.tokenBudget}:{},now:i})};return n.set(d.runId,g),g},"createRun"),m=o((d,f)=>(d.status=Oh(f,d.controller.signal.aborted||d.status==="stopped"),d.endedAt=t(),f.kind==="failed"&&d.status!=="stopped"&&(d.error=f.error.message),f.kind==="completed"&&(d.resultText=Ih(f.result)),f.kind==="failed"&&!Wn(d.process.getSnapshot().status)?s(d.process.setStatus("failed",f.error.message)):f.kind==="denied"?s(d.process.setStatus("cancelled","workflow denied")):d.status==="stopped"&&d.process.getSnapshot().status!=="cancelled"&&s(d.process.setStatus("cancelled","workflow stopped")),a(d),f),"settle");return{start:o(d=>{let f=Et(d.module.meta,d.hostPolicy),p=u({runId:d.runId,workflow:d.module.meta.name,...d.module.meta.phases!==void 0?{phases:d.module.meta.phases}:{},...f.maxAgents!==void 0?{maxAgents:f.maxAgents}:{},...d.module.meta.plannedAgents!==void 0?{plannedAgents:d.module.meta.plannedAgents}:{},...f.tokenBudget!==void 0?{tokenBudget:f.tokenBudget}:{},...d.processMetadata!==void 0?{processMetadata:d.processMetadata}:{}},d.runDir,d.signal),h=$o({...d,signal:p.controller.signal,beforeSpawn:o(()=>c(p),"beforeSpawn"),onEvent:l(p,d.onEvent)}).catch(g=>pd(p,g)).then(g=>m(p,g));return{runId:p.runId,done:h,getSnapshot:o(()=>Rn(p),"getSnapshot"),getProcessSnapshot:o(()=>p.process.getSnapshot(),"getProcessSnapshot")}},"start"),startFromOptions:o(d=>{let f=Et(d.module.meta,d.options.workflowHostPolicy),p=u({runId:d.runId,workflow:d.module.meta.name,...d.module.meta.phases!==void 0?{phases:d.module.meta.phases}:{},...f.maxAgents!==void 0?{maxAgents:f.maxAgents}:{},...d.module.meta.plannedAgents!==void 0?{plannedAgents:d.module.meta.plannedAgents}:{},...f.tokenBudget!==void 0?{tokenBudget:f.tokenBudget}:{},...d.processMetadata!==void 0?{processMetadata:d.processMetadata}:{}},d.runDir,d.signal),h=td({...d,signal:p.controller.signal,beforeSpawn:o(()=>c(p),"beforeSpawn"),onEvent:l(p,d.onEvent)}).catch(g=>pd(p,g)).then(g=>m(p,g));return{runId:p.runId,done:h,getSnapshot:o(()=>Rn(p),"getSnapshot"),getProcessSnapshot:o(()=>p.process.getSnapshot(),"getProcessSnapshot")}},"startFromOptions"),list:o(()=>[...n.values()].map(Rn).sort((d,f)=>f.startedAt-d.startedAt),"list"),get:o(d=>{let f=n.get(d);return f?Rn(f):void 0},"get"),subscribeWorkflowProcess:o(d=>(r.add(d),()=>{r.delete(d)}),"subscribeWorkflowProcess"),getWorkflowProcessSnapshot:o(d=>n.get(d)?.process.getSnapshot(),"getWorkflowProcessSnapshot"),listWorkflowProcessSnapshots:o(d=>{let f=[...n.values()].sort((p,h)=>h.startedAt-p.startedAt).map(p=>p.process.getSnapshot()).filter(p=>d?.activeOnly===!0?!Wn(p.status):!0);return d?.limit===void 0?f:f.slice(0,d.limit)},"listWorkflowProcessSnapshots"),pause:o(d=>{let f=n.get(d);return!f||f.status!=="running"?!1:(f.status="paused",s(f.process.setStatus("paused","workflow paused")),!0)},"pause"),resume:o(d=>{let f=n.get(d);return!f||f.status!=="paused"?!1:(f.status="running",s(f.process.setStatus("running","workflow resumed")),a(f),!0)},"resume"),stop:o((d,f)=>{let p=n.get(d);return!p||["completed","failed","denied","stopped"].includes(p.status)?!1:(p.status="stopped",s(p.process.setStatus("cancelled",f??"workflow stopped")),p.controller.abort(),a(p),!0)},"stop")}}o(Nh,"createWorkflowRunManager");var hd;function zR(){return hd??=Nh(),hd}o(zR,"getDefaultWorkflowRunManager");import{existsSync as Vo,readFileSync as Rd,readdirSync as Gh,rmSync as bd,writeFileSync as qh}from"node:fs";import{join as tt,resolve as Sn,sep as Sd}from"node:path";import{existsSync as qo,readdirSync as Dh,readFileSync as wd}from"node:fs";import{join as kd,resolve as gd,sep as $h}from"node:path";function yd(e){return e!=="."&&/^[a-zA-Z0-9._-]+$/.test(e)&&!e.includes("..")}o(yd,"isSafeWorkflowRunId");function Lh(e,t){if(!yd(t))return;let n=gd(e),r=gd(n,t);return r.startsWith(`${n}${$h}`)?r:void 0}o(Lh,"safeRunDir");function jh(e){let t=kd(e,"run.json");if(qo(t))try{let n=JSON.parse(wd(t,"utf8"));return typeof n=="object"&&n!==null?n:void 0}catch{return}}o(jh,"readRunRecord");function Uh(e){let t=kd(e,"workflow-metadata.json");if(qo(t))try{let n=JSON.parse(wd(t,"utf8"));if(typeof n!="object"||n===null)return;let r=n.displayName;return typeof r=="string"&&r.trim().length>0?r:void 0}catch{return}}o(Uh,"readMetadataDisplayName");function Fh(e){let t=e.displayName;return typeof t=="string"&&t.trim().length>0?t:void 0}o(Fh,"readRunJsonDisplayName");function Bh(e,t){return e?.trim()===t}o(Bh,"displayNameMatches");function vd(e,t){if(!t)return;let n=Lh(t,e);if(!n)return;let r=jh(n);if(!r)return;let i=r.workflow,s=Uh(n)??Fh(r);return{kind:"run",target:e,runId:e,runDir:n,...typeof i=="string"&&i.length>0?{workflowName:i}:{},...s!==void 0?{displayName:s}:{}}}o(vd,"resolveRun");function Wh(e,t){if(!t||!qo(t))return[];let n=[];for(let r of Dh(t)){if(!yd(r))continue;let i=vd(r,t);i&&Bh(i.displayName,e)&&n.push(i)}return n}o(Wh,"resolveRunsByDisplayName");async function Hh(e,t){return t?(await St(t)).find(r=>r.name===e):void 0}o(Hh,"resolveSaved");async function Td(e){let t=e.target.trim();if(!t)return{kind:"missing",target:e.target};let n=vd(t,e.runBaseDir),r=n?[]:Wh(t,e.runBaseDir),i=await Hh(t,e.savedWorkflowDirs),s=n?[n]:r;return s.length>1?{kind:"ambiguous",target:t,matches:i?["run","saved"]:["run"],...i?{savedWorkflow:i}:{}}:s.length===1&&i?{kind:"ambiguous",target:t,matches:["run","saved"],run:s[0],savedWorkflow:i}:n||(r.length===1?r[0]:i?{kind:"saved",target:t,savedWorkflow:i}:{kind:"missing",target:t})}o(Td,"resolveWorkflowIdentity");var Ko=new Set(["completed","failed","stopped","denied","cancelled"]);function _d(e){if(Vo(e))try{return JSON.parse(Rd(e,"utf8"))}catch{return}}o(_d,"readJsonFile");function Ad(e){let t=_d(e);return typeof t=="object"&&t!==null?t:void 0}o(Ad,"readRecord");function ie(e){return typeof e=="string"&&e.trim().length>0?e:void 0}o(ie,"readString");function Vh(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}o(Vh,"readNumber");function Kh(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}o(Kh,"readStringArray");function Xh(e){if(e==="command"||e==="amaw"||e==="review"||e==="sdk"||e==="capsule"||e==="extension"||e==="automation")return e}o(Xh,"readWorkflowProcessSource");function zh(e,t){let n=ie(e.goal),r=Xh(e.source),i=ie(e.savedWorkflowName),s=ie(e.sourceRunId),c=ie(e.sourceWorkflowName),a=ie(e.revisionOf),l=Dt(e.hostMetadata),u={...t!==void 0?{displayName:t}:{},...n!==void 0?{goal:n}:{},...r!==void 0?{source:r}:{},...i!==void 0?{savedWorkflowName:i}:{},...s!==void 0?{sourceRunId:s}:{},...c!==void 0?{sourceWorkflowName:c}:{},...a!==void 0?{revisionOf:a}:{},...l!==void 0?{hostMetadata:l}:{}};return Object.keys(u).length>0?u:void 0}o(zh,"readRunProcessMetadata");function Yh(e){return e!=="."&&/^[a-zA-Z0-9._-]+$/.test(e)&&!e.includes("..")}o(Yh,"isSafeWorkflowRunId");function He(e,t){if(!Yh(t))return;let n=Sn(e),r=Sn(n,t);return r.startsWith(`${n}${Sd}`)?r:void 0}o(He,"runDir");function Jh(e){return e==="running"||e==="paused"}o(Jh,"isManagedWorkflowActive");function Qh(e,t){let n=Sn(e),r=Sn(t);return r===n||r.startsWith(`${n}${Sd}`)}o(Qh,"isPathWithinBase");function _t(e,t){let n=He(e,t);if(!n)return;let r=Ad(tt(n,"run.json"));if(!r)return;let i=Zh(n)??ie(r.displayName),s=ie(r.resultSummary),c=zh(r,i);return{runId:t,workflow:ie(r.workflow)??"?",...i!==void 0?{displayName:i}:{},...s!==void 0?{resultSummary:s}:{},...c!==void 0?{processMetadata:c}:{},status:ie(r.status)??"?",endedAt:Vh(r.endedAt)??0,artifacts:Kh(r.artifacts)}}o(_t,"readPersistedRun");function Zh(e){let t=Ad(tt(e,"workflow-metadata.json"));return t?ie(t.displayName):void 0}o(Zh,"readRunDisplayName");function Ed(e){if(!Vo(e))return[];let t=[];for(let n of Gh(e)){let r=_t(e,n);r&&t.push(r)}return t.sort((n,r)=>r.endedAt-n.endedAt)}o(Ed,"listPersistedRuns");function Cd(e){let t=tt(e,"events.jsonl");if(!Vo(t))return[];let n=[];for(let r of Rd(t,"utf8").split(/\r?\n/)){if(!r.trim())continue;let i;try{i=JSON.parse(r)}catch{continue}if(typeof i!="object"||i===null)continue;let s=i;if(typeof s.seq!="number"||typeof s.type!="string")continue;let c=s.data;n.push({seq:s.seq,type:s.type,...typeof c=="object"&&c!==null?{data:c}:{}})}return n}o(Cd,"readWorkflowEvents");function xd(e,t){let n=He(e,t.runId);if(!n)return;let r=Ke({runId:t.runId,workflowName:t.workflow,displayName:t.displayName??t.processMetadata?.displayName??t.workflow,...t.processMetadata?.goal!==void 0?{goal:t.processMetadata.goal}:{},...t.processMetadata?.source!==void 0?{source:t.processMetadata.source}:{},...t.processMetadata?.savedWorkflowName!==void 0?{savedWorkflowName:t.processMetadata.savedWorkflowName}:{},...t.processMetadata?.sourceRunId!==void 0?{sourceRunId:t.processMetadata.sourceRunId}:{},...t.processMetadata?.sourceWorkflowName!==void 0?{sourceWorkflowName:t.processMetadata.sourceWorkflowName}:{},...t.processMetadata?.revisionOf!==void 0?{revisionOf:t.processMetadata.revisionOf}:{},...t.processMetadata?.hostMetadata!==void 0?{hostMetadata:{...t.processMetadata.hostMetadata}}:{},...t.resultSummary!==void 0?{resultSummary:t.resultSummary}:{},artifacts:t.artifacts.map(s=>({name:s,path:tt(n,"artifacts",`${En(s)}.json`)}))});for(let s of Cd(n))r.applyEvent(s);let i=r.getSnapshot();return i.status!=="running"||!Ko.has(t.status)?i:(t.status==="completed"?r.setStatus("completed"):t.status==="failed"?r.setStatus("failed"):r.setStatus("cancelled"),r.getSnapshot())}o(xd,"snapshotFromPersistedRun");function eg(e){for(let t of[...e].reverse()){if(t.type==="workflow_completed"){let i=ie(t.data?.resultSummary);if(i)return i}if(t.type!=="agent_completed"&&t.type!=="agent_unverified"&&t.type!=="agent_failed")continue;let n=ie(t.data?.summary);if(n)return n;let r=ie(t.data?.error);if(r)return r}}o(eg,"readEventSummary");function tg(e,t,n){let r=e.filter(a=>Ko.has(a.status)).sort((a,l)=>l.endedAt-a.endedAt),i=t.keep,s=t.olderThanDays===void 0?void 0:n-t.olderThanDays*24*60*60*1e3,c=i===void 0?new Set:new Set(r.slice(0,Math.max(0,i)).map(a=>a.runId));return i===void 0&&s===void 0?[]:r.filter(a=>c.has(a.runId)?!1:s===void 0?!0:a.endedAt>0&&a.endedAt<s)}o(tg,"pruneCandidates");function dS(e){let t=e.now??(()=>Date.now()),{runManager:n,runBaseDir:r}=e;return{subscribeWorkflowProcess:o(i=>n.subscribeWorkflowProcess(i),"subscribeWorkflowProcess"),getWorkflowProcessSnapshot:o(i=>{let s=n.getWorkflowProcessSnapshot(i);if(s)return s;let c=_t(r,i);return c?xd(r,c):void 0},"getWorkflowProcessSnapshot"),listWorkflowProcessSnapshots:o(i=>{let s=n.listWorkflowProcessSnapshots(i);if(i?.activeOnly===!0)return s;let c=new Set(s.map(u=>u.runId)),a=Ed(r).filter(u=>!c.has(u.runId)).map(u=>xd(r,u)).filter(u=>u!==void 0),l=[...s,...a];return i?.limit===void 0?l:l.slice(0,i.limit)},"listWorkflowProcessSnapshots"),resolveWorkflowIdentity:o(async i=>Td({target:i,runBaseDir:r,savedWorkflowDirs:e.savedWorkflowDirs}),"resolveWorkflowIdentity"),preflightWorkflowCapsule:o(async i=>md(i.capsule,i.env),"preflightWorkflowCapsule"),stopWorkflow:o(async(i,s)=>n.stop(i,s),"stopWorkflow"),pauseWorkflow:o(async i=>n.pause(i),"pauseWorkflow"),resumeWorkflow:o(async i=>n.resume(i),"resumeWorkflow"),renameWorkflowRun:o(async(i,s)=>{let c=s.trim();if(c.length===0)return!1;let a=He(r,i);return!a||!_t(r,i)?!1:(qh(tt(a,"workflow-metadata.json"),`${JSON.stringify({displayName:c},null,2)}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
|
|
2
|
-
import{B as nl,Da as rl,Ea as ol,Fa as il,Ga as sl,Ia as al,Q as _i,S as Ei,_ as Si,b as Qe,c as et,d as tt,e as el,ga as Ai,na as Ci,p as tl,pa as Ri,sa as rn}from"./chunk-
|
|
2
|
+
import{B as nl,Da as rl,Ea as ol,Fa as il,Ga as sl,Ia as al,Q as _i,S as Ei,_ as Si,b as Qe,c as et,d as tt,e as el,ga as Ai,na as Ci,p as tl,pa as Ri,sa as rn}from"./chunk-LE6STNVN.js";import{$a as ul,Bb as pl,Cc as Li,Dc as Ni,Ec as wl,Ga as Me,Gc as vl,H as cl,Ha as sn,Hc as kl,Ia as Jn,Ic as xl,Jc as Tl,Na as je,R as ll,Sa as $i,T as on,Ta as dl,Yb as hl,ab as so,b as Ii,bb as fl,c as Xn,cc as gl,cd as Di,f as It,g as Vn,j as Mi,jb as Zn,k as ie,kb as Oi,kd as Fi,m as oo,na as re,nd as _l,oa as Pi,od as El,pd as Sl,rc as co,rd as Al,sb as ao,sc as yl,sd as Cl,tb as ml,td as Rl,va as Yn,vd as Il,wa as io,xc as bl}from"./chunk-HMATTIU6.js";import{a as i}from"./chunk-V4WSBIXB.js";function lo(e,t){let n;try{let r=JSON.stringify(t);if(r===void 0)return`${e}: [unserializable input]`;n=r}catch{return`${e}: [unserializable input]`}return n.length>200&&(n=n.slice(0,200)+"\u2026"),`${e}: ${n}`}i(lo,"defaultToClassifierInput");function Pl(e,t,n){let r=`MCP[${e}.${t}]`;if(n==null||typeof n!="object"){let c=Cg(n,200);return`${r}: ${c}`}let o=n,s=Sg(o);if(s){let c=$l(String(s.value),200),l=Ml(o,s.field);return l?`${r}: ${c} | ${l}`:`${r}: ${c}`}let a=Ml(o,null);return`${r}: ${a||"{}"}`}i(Pl,"mcpToClassifierInput");var Eg=["method","command","url","query","action"];function Sg(e){for(let t of Eg)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(n!=null&&n!=="")return{field:t,value:n}}}i(Sg,"pickActionField");function Ml(e,t){let n=Object.entries(e).filter(([c])=>c!==t);if(n.length===0)return"";let r=32,o=[],s=0;for(let[c,l]of n){if(o.length>=3){s+=1;continue}let d=Ag(l,r);d?o.push(`${c}=${d}`):s+=1}let a=[];if(o.length>0&&a.push(o.join(", ")),s>0){let c=n.filter(([l])=>!o.some(d=>d.startsWith(`${l}=`))).map(([l])=>l);a.push(`+${s} key${s>1?"s":""}: ${c.join(", ")}`)}return a.join(", ")}i(Ml,"describeStructure");function Ag(e,t){if(e===null)return"null";if(typeof e=="string")return e.length<=t?e:void 0;if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e)&&e.length<=3){let n=e.map(r=>typeof r=="string"?r:JSON.stringify(r)).join(",");if(n.length<=t)return`[${n}]`}}i(Ag,"formatScalarOrShortStructure");function Cg(e,t){if(e===void 0)return"[undefined]";if(e===null)return"null";let n;try{n=typeof e=="string"?e:JSON.stringify(e)??String(e)}catch{n=String(e)}return $l(n,t)}i(Cg,"formatValue");function $l(e,t){return e.length>t?e.slice(0,t)+"\u2026":e}i($l,"truncate");import Wi from"fs/promises";import{createReadStream as Dg}from"fs";import Fg from"node:path";import{createInterface as jg}from"readline";import uo from"path";function z(e){return uo.resolve(e?.executionCwd??e?.gitRoot??process.cwd())}i(z,"resolveExecutionCwd");function K(e,t){let n=z(t);return uo.isAbsolute(e)?uo.resolve(e):uo.resolve(n,e)}i(K,"resolveExecutionPath");function an(e,t){return!e||!e.trim()?z(t):K(e,t)}i(an,"resolveExecutionPathOrCwd");import*as Ol from"node:fs";var Rg={statSync(e){return{mtimeMs:Ol.statSync(e).mtimeMs}}};function ji(e,t){return`${e}|${t}`}i(ji,"rangeKey");function UR(e={}){if(e.disabled??process.env.KODAX_READ_DEDUP_KILLSWITCH==="1")return{lookup:i(()=>({kind:"miss"}),"lookup"),record:i(()=>{},"record"),forget:i(()=>{},"forget"),clear:i(()=>{},"clear"),size:i(()=>0,"size")};let n=e.fs??Rg,r=e.clock??Date.now,o=new Map;return{lookup(s,a,c){let l=o.get(s);if(!l)return{kind:"miss"};let d=l.get(ji(a,c));if(!d)return{kind:"miss"};let u;try{u=n.statSync(s).mtimeMs}catch{return{kind:"miss"}}return u!==d.mtimeMs?(l.delete(ji(a,c)),{kind:"miss"}):{kind:"hit",previousReadAtMs:d.readAtMs}},record(s,a,c,l){let d=o.get(s);d||(d=new Map,o.set(s,d)),d.set(ji(a,c),{mtimeMs:l,readAtMs:r()})},forget(s){o.delete(s)},clear(){o.clear()},size(){return o.size}}}i(UR,"createReadFileStateCache");function Ll(e,t,n){return`[Read Cache] ${e} is unchanged since you read it earlier in this task (offset=${t}, limit=${n}). The content from the earlier read tool_result in this conversation is still current \u2014 refer to that instead of re-reading. If you need different lines, call read with a different offset/limit. If the file is modified externally, this cache invalidates automatically on mtime change.`}i(Ll,"buildReadFileUnchangedStub");import jl from"fs/promises";import Ul from"path";import Ui from"fs/promises";import Ig from"path";var Dl=336*60*60*1e3,Mg=3600*1e3;async function Pg(e,t=Dl,n=Date.now()){let r;try{r=await Ui.readdir(e)}catch{return{scanned:0,removed:0,failed:0,bytesRemoved:0}}let o=0,s=0,a=0,c=0;for(let l of r){let d=Ig.join(e,l),u;try{u=await Ui.stat(d)}catch{a+=1;continue}if(!(!u.isFile()||(o+=1,n-u.mtimeMs<=t)))try{await Ui.unlink(d),s+=1,c+=u.size}catch{a+=1}}return{scanned:o,removed:s,failed:a,bytesRemoved:c}}i(Pg,"cleanupExpiredToolOutputs");var Nl=0,cn=null;function Fl(e,t=Dl,n=Date.now()){return cn||(n-Nl<Mg?Promise.resolve(null):(Nl=n,cn=Pg(e,t,n).then(r=>(cn=null,r)).catch(()=>(cn=null,null)),cn))}i(Fl,"maybeRunToolOutputGc");var ql=2e3,ln=50*1024,$g=500,fo=2e3,Bi=256*1024,dn=2e3,Hl=`... [line truncated to ${dn} chars]`,qi=512*1024,Og="KODAX_TOOL_OUTPUT_DIR";function Wl(e){return{maxLines:e.maxLines??ql,maxBytes:e.maxBytes??ln}}i(Wl,"getLimits");function F(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}i(F,"formatSize");function un(e,t={}){let{maxLines:n,maxBytes:r}=Wl(t),o=Buffer.byteLength(e,"utf-8"),s=e.split(`
|
|
3
3
|
`),a=s.length;if(a<=n&&o<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:a,totalBytes:o,outputLines:a,outputBytes:o,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};let c=s[0]??"";if(Buffer.byteLength(c,"utf-8")>r)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines:a,totalBytes:o,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines:n,maxBytes:r};let l=[],d=0,u="lines";for(let m=0;m<s.length&&m<n;m++){let g=s[m]??"",p=Buffer.byteLength(g,"utf-8")+(m>0?1:0);if(d+p>r){u="bytes";break}l.push(g),d+=p}l.length>=n&&d<=r&&(u="lines");let f=l.join(`
|
|
4
4
|
`);return{content:f,truncated:!0,truncatedBy:u,totalLines:a,totalBytes:o,outputLines:l.length,outputBytes:Buffer.byteLength(f,"utf-8"),lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}i(un,"truncateHead");function fn(e,t={}){let{maxLines:n,maxBytes:r}=Wl(t),o=Buffer.byteLength(e,"utf-8"),s=e.split(`
|
|
5
5
|
`),a=s.length;if(a<=n&&o<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:a,totalBytes:o,outputLines:a,outputBytes:o,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};let c=[],l=0,d="lines",u=!1;for(let m=s.length-1;m>=0&&c.length<n;m--){let g=s[m]??"",p=Buffer.byteLength(g,"utf-8")+(c.length>0?1:0);if(l+p>r){if(d="bytes",c.length===0&&g.length>0){let h=Lg(g,r);c.unshift(h),l=Buffer.byteLength(h,"utf-8"),u=!0}break}c.unshift(g),l+=p}c.length>=n&&l<=r&&(d="lines");let f=c.join(`
|
|
@@ -170,7 +170,7 @@ ${n.content}
|
|
|
170
170
|
`).join(`
|
|
171
171
|
---
|
|
172
172
|
`)}
|
|
173
|
-
`}i(Fo,"formatAgentsForPrompt");function _k(e){if(!e.trim())return[];let t=[],n=/(^|\s)\/skill:([\w](?:[\w.\-:]*[\w])?)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1]??"",s=r[2]??"";if(!s)continue;let a=r.index+o.length,c=`/skill:${s}`;t.push({name:s,raw:c,start:a,end:a+c.length})}return t}i(_k,"parseInlineSkillReferences");function Ek(e){if(!e.trim())return[];let t=[],n=/(^|\s)\/(?!skill:)([\w](?:[\w.\-:]*[\w])?)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1]??"",s=r[2]??"";if(!s)continue;let a=r.index+o.length,c=`/${s}`;t.push({name:s,raw:c,start:a,end:a+c.length})}return t}i(Ek,"parseBareInlineSlashReferences");function mf(e){return Array.from(new Set(_k(e).map(t=>t.name)))}i(mf,"uniqueInlineSkillNames");function pf(e){return Array.from(new Set(Ek(e).map(t=>t.name)))}i(pf,"uniqueBareInlineSlashNames");var dO="kodax/role/scout",uO="kodax/role/planner",fO="kodax/role/generator",Sk="kodax/role/worker",jo=oo({name:Sk,instructions:"KodaX single primary role: plan via todo_update, execute via tool calls, terminate text-only when done \u2014 Sidecar Verifier runs verification out-of-band."}),mO=Object.freeze({worker:jo});var Ak=new Map([["worker",jo],["kodax/role/worker",jo]]),Pe=new Map,We=new Map;function jt(e){return Pe.get(e)?.agent}i(jt,"resolveConstructedAgent");function be(){return Array.from(Pe.values()).map(e=>e.agent)}i(be,"listConstructedAgents");function ra(){for(let e of Pe.values())on(e.agent);Pe.clear();for(let e of We.values())on(e.agent);We.clear()}i(ra,"_resetAgentResolverForTesting");function Ck(e){return We.has(e)}i(Ck,"hasPendingSwap");function Rk(){if(We.size===0)return[];let e=[];for(let[t,n]of We){let r=Pe.get(t);r&&on(r.agent),Pe.set(t,n),e.push(t)}return We.clear(),e}i(Rk,"drainPendingSwaps");function Ik(e){let t=e.ref.indexOf(":"),n=t===-1?e.ref:e.ref.slice(t+1).split("@")[0],r=gt(n);if(r)return{name:r.name,description:r.description,input_schema:r.input_schema}}i(Ik,"liftToolRef");function Mk(e){let t=e.target.ref.indexOf(":"),n=t===-1?"":e.target.ref.slice(0,t),r=t===-1?e.target.ref:e.target.ref.slice(t+1),o=r.indexOf("@"),s=o===-1?r:r.slice(0,o),a;return n==="builtin"?a=Ak.get(s)??{name:s,instructions:""}:a=Pe.get(s)?.agent??{name:s,instructions:""},{target:a,kind:e.kind,description:e.description}}i(Mk,"liftHandoffRef");function Pk(e,t){let n=[];if(t.tools)for(let o of t.tools){let s=Ik(o);s&&n.push(s)}let r=t.handoffs?.map(Mk);return{name:e,instructions:t.instructions,...n.length>0?{tools:n}:{},...r&&r.length>0?{handoffs:r}:{},...t.reasoning?{reasoning:t.reasoning}:{},...t.guardrails?{guardrails:t.guardrails.map(o=>{let s=o.ref.indexOf(":");return{kind:o.kind,name:s===-1?o.ref:o.ref.slice(s+1).split("@")[0]}})}:{},...t.model?{model:t.model}:{},...t.provider?{provider:t.provider}:{},...t.outputSchema?{outputSchema:t.outputSchema}:{},...t.description?{description:t.description}:{}}}i(Pk,"buildAgentFromContent");function ze(e,t={},n={}){let r=Pk(e.name,e.content);return t.bindings&&t.manifest&&ll(r,t.manifest,t.bindings),(n.deferred?We:Pe).set(e.name,{artifact:e,agent:r,source:t.source}),()=>{let s=We.get(e.name);if(s&&s.artifact.version===e.version){on(s.agent),We.delete(e.name);return}let a=Pe.get(e.name);a&&a.artifact.version===e.version&&(on(a.agent),Pe.delete(e.name))}}i(ze,"registerConstructedAgent");var oa,Uo;async function wf(){if(oa)return oa;if(!Uo){let e="./agent.js";Uo=import("./agent-
|
|
173
|
+
`}i(Fo,"formatAgentsForPrompt");function _k(e){if(!e.trim())return[];let t=[],n=/(^|\s)\/skill:([\w](?:[\w.\-:]*[\w])?)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1]??"",s=r[2]??"";if(!s)continue;let a=r.index+o.length,c=`/skill:${s}`;t.push({name:s,raw:c,start:a,end:a+c.length})}return t}i(_k,"parseInlineSkillReferences");function Ek(e){if(!e.trim())return[];let t=[],n=/(^|\s)\/(?!skill:)([\w](?:[\w.\-:]*[\w])?)/g,r;for(;(r=n.exec(e))!==null;){let o=r[1]??"",s=r[2]??"";if(!s)continue;let a=r.index+o.length,c=`/${s}`;t.push({name:s,raw:c,start:a,end:a+c.length})}return t}i(Ek,"parseBareInlineSlashReferences");function mf(e){return Array.from(new Set(_k(e).map(t=>t.name)))}i(mf,"uniqueInlineSkillNames");function pf(e){return Array.from(new Set(Ek(e).map(t=>t.name)))}i(pf,"uniqueBareInlineSlashNames");var dO="kodax/role/scout",uO="kodax/role/planner",fO="kodax/role/generator",Sk="kodax/role/worker",jo=oo({name:Sk,instructions:"KodaX single primary role: plan via todo_update, execute via tool calls, terminate text-only when done \u2014 Sidecar Verifier runs verification out-of-band."}),mO=Object.freeze({worker:jo});var Ak=new Map([["worker",jo],["kodax/role/worker",jo]]),Pe=new Map,We=new Map;function jt(e){return Pe.get(e)?.agent}i(jt,"resolveConstructedAgent");function be(){return Array.from(Pe.values()).map(e=>e.agent)}i(be,"listConstructedAgents");function ra(){for(let e of Pe.values())on(e.agent);Pe.clear();for(let e of We.values())on(e.agent);We.clear()}i(ra,"_resetAgentResolverForTesting");function Ck(e){return We.has(e)}i(Ck,"hasPendingSwap");function Rk(){if(We.size===0)return[];let e=[];for(let[t,n]of We){let r=Pe.get(t);r&&on(r.agent),Pe.set(t,n),e.push(t)}return We.clear(),e}i(Rk,"drainPendingSwaps");function Ik(e){let t=e.ref.indexOf(":"),n=t===-1?e.ref:e.ref.slice(t+1).split("@")[0],r=gt(n);if(r)return{name:r.name,description:r.description,input_schema:r.input_schema}}i(Ik,"liftToolRef");function Mk(e){let t=e.target.ref.indexOf(":"),n=t===-1?"":e.target.ref.slice(0,t),r=t===-1?e.target.ref:e.target.ref.slice(t+1),o=r.indexOf("@"),s=o===-1?r:r.slice(0,o),a;return n==="builtin"?a=Ak.get(s)??{name:s,instructions:""}:a=Pe.get(s)?.agent??{name:s,instructions:""},{target:a,kind:e.kind,description:e.description}}i(Mk,"liftHandoffRef");function Pk(e,t){let n=[];if(t.tools)for(let o of t.tools){let s=Ik(o);s&&n.push(s)}let r=t.handoffs?.map(Mk);return{name:e,instructions:t.instructions,...n.length>0?{tools:n}:{},...r&&r.length>0?{handoffs:r}:{},...t.reasoning?{reasoning:t.reasoning}:{},...t.guardrails?{guardrails:t.guardrails.map(o=>{let s=o.ref.indexOf(":");return{kind:o.kind,name:s===-1?o.ref:o.ref.slice(s+1).split("@")[0]}})}:{},...t.model?{model:t.model}:{},...t.provider?{provider:t.provider}:{},...t.outputSchema?{outputSchema:t.outputSchema}:{},...t.description?{description:t.description}:{}}}i(Pk,"buildAgentFromContent");function ze(e,t={},n={}){let r=Pk(e.name,e.content);return t.bindings&&t.manifest&&ll(r,t.manifest,t.bindings),(n.deferred?We:Pe).set(e.name,{artifact:e,agent:r,source:t.source}),()=>{let s=We.get(e.name);if(s&&s.artifact.version===e.version){on(s.agent),We.delete(e.name);return}let a=Pe.get(e.name);a&&a.artifact.version===e.version&&(on(a.agent),Pe.delete(e.name))}}i(ze,"registerConstructedAgent");var oa,Uo;async function wf(){if(oa)return oa;if(!Uo){let e="./agent.js";Uo=import("./agent-XXTR7T37.js").then(t=>{let n=t.runKodaX;if(typeof n!="function")throw new Error("[child-executor] Agent module loaded but `runKodaX` export is missing or not a function. This indicates an API break in packages/coding/src/agent.ts. Check that `export { runKodaX }` is still present.");return oa=n,n}).catch(t=>{if(Uo=void 0,t instanceof Error&&t.message.startsWith("[child-executor]"))throw t;let n=t instanceof Error?t.message:String(t);throw new Error(`[child-executor] Failed to lazy-load agent module (\`${e}\`) for dispatch_child_task. This usually means the @kodax-ai/coding build is broken or out of date. Underlying cause: ${n}`)})}return Uo}i(wf,"getRunKodaX");var Lk=["You are summarizing your own just-completed child-agent report for a parent workflow.","Do not use tools. Do not continue investigation. Produce only the digest."].join(`
|
|
174
174
|
`),Nk=["Create a short user-facing digest of your previous report for the parent workflow.","Return only 2-4 bullet lines.","Each bullet must be concrete: a finding, decision, risk, evidence pointer, unresolved question, or next action.","Use the same natural language as the user request or your report.","Do not include a title, table, generic preamble, or workflow handoff markers."].join(`
|
|
175
175
|
`),Dk=4,vf=1e4,Fk=45e3,jk=40;async function sa(e,t,n){if(e.length===0)return bf;let r=e.filter(f=>f.readOnly),o=e.filter(f=>!f.readOnly),s=ox(o,n.parentRole,n.parentHarness),a=[...r,...s];if(a.length===0)return bf;let c=[],l=[],d=n.onProgress??(()=>{});d(`Starting ${a.length} child tasks in parallel`);let u=await ul({bundles:a,runOne:i(f=>f.readOnly?Xk(f,t,n):Yk(f,t,n),"runOne"),maxParallel:n.maxParallel,abortSignal:n.abortSignal,onProgress:i((f,m)=>{f.kind==="start"?d(`[${m.completedCount}/${m.totalCount}] Running: ${f.bundle.id}`):f.kind==="item-done"&&d(`[${m.completedCount}/${m.totalCount}] Done: ${f.bundle.id} \u2192 ${f.result.status}`)},"onProgress")});for(let f of u.results)f.status==="fulfilled"?c.push(f.value):c.push(Ut(f.bundle,`[Crash] ${f.reason.message}`,"failed"));for(let f of u.cancelled)l.push(f.id);return rx(a,c,l)}i(sa,"executeChildAgents");function Uk(e){let t=JSON.parse(e);if(typeof t!="object"||t===null||!("path"in t))throw new Error("worktree_create returned an invalid payload");let n=t.path;if(typeof n!="string"||n.length===0)throw new Error("worktree_create returned an invalid path");return n}i(Uk,"readWorktreePath");async function kf(e,t){if(e.isolation!=="worktree")return{ctx:t};let n=await Tr({description:`workflow-${e.id}`,...t.workflowWorktreeBaseDir?{base_dir:t.workflowWorktreeBaseDir}:{}},t),r=Uk(n);return{ctx:{...t,gitRoot:r,executionCwd:r},worktreePath:r}}i(kf,"prepareChildIsolationScope");function xf(e,t){return t.worktreePath?[`[Workflow worktree: ${t.worktreePath}]`,e].join(`
|
|
176
176
|
`):e}i(xf,"annotateWorktreeSummary");async function gf(e,t){if(e.worktreePath)try{await _r({action:"remove",worktree_path:e.worktreePath,discard_changes:!1},t);return}catch(n){return`[Workflow worktree cleanup failed: ${n instanceof Error?n.message:String(n)}]`}}i(gf,"cleanupChildIsolationScope");function Bk(e,t){return t?{...e,summary:`${e.summary}
|
|
@@ -468,7 +468,7 @@ ${o.map(a=>` ${a}`).join(`
|
|
|
468
468
|
`)}};return{effectiveOptions:o,systemPrompt:e.context?.systemPromptOverride??await Oc(o,n),providerReasoning:{enabled:t.depth!=="off",mode:t.mode,depth:t.depth,taskType:t.decision.primaryTask,executionMode:t.decision.recommendedMode}}}i(Hn,"buildReasoningExecutionState");function pC(e,t){return t?{...e,mode:t,depth:qn(t)}:e}i(pC,"buildEffectiveReasoningPlan");async function xh(e){let t=pC(e.reasoningPlan,e.thinkingLevel),n=await Hn({...e.options,provider:e.providerName,modelOverride:e.modelOverride,reasoningMode:e.thinkingLevel??e.options.reasoningMode},t,e.messages.length===1);return{effectiveReasoningPlan:t,currentExecution:n}}i(xh,"resolvePerTurnReasoning");function Th(e){let t=new AbortController,n=setTimeout(()=>{t.abort(new Error("API Hard Timeout (10 minutes)"))},e.hardTimeoutMs),r;e.streamMaxDurationMs>0&&(r=setTimeout(()=>{t.abort(new Error(`Stream max duration exceeded (${e.streamMaxDurationMs}ms; provider has known server-side kill window)`))},e.streamMaxDurationMs));let o=e.idleTimeoutMs>0,s;o&&(s=setTimeout(()=>{t.abort(new Error(`Stream stalled or delayed response (${e.idleTimeoutMs}ms idle)`))},e.idleTimeoutMs));let a=i(()=>{o&&(clearTimeout(s),t.signal.aborted||(s=setTimeout(()=>{t.abort(new Error(`Stream stalled or delayed response (${e.idleTimeoutMs}ms idle)`))},e.idleTimeoutMs)))},"resetIdleTimer"),c=i(()=>{o&&(clearTimeout(s),s=void 0)},"clearIdleTimer"),l=e.callerAbortSignal?AbortSignal.any([e.callerAbortSignal,t.signal]):t.signal;return{retryTimeoutController:t,retrySignal:l,resetIdleTimer:a,clearIdleTimer:c,clearAll:i(()=>{clearTimeout(n),clearTimeout(r),clearTimeout(s),n=void 0,r=void 0,s=void 0},"clearAll")}}i(Th,"buildStreamTimers");function _h(e){let t=si({providerName:e.providerName,model:e.model,provider:e.provider,prompt:e.prompt,options:e.effectiveOptions,context:e.effectiveOptions.context,reasoningMode:e.reasoningMode,taskType:e.taskType,executionMode:e.executionMode});if(t.status==="block")throw new Error(`[Provider Policy] ${t.summary}`);return{effectiveSystemPrompt:t.issues.length>0?[e.baseSystemPrompt,xp(t).join(`
|
|
469
469
|
`)].join(`
|
|
470
470
|
|
|
471
|
-
`):e.baseSystemPrompt,decision:t}}i(_h,"applyProviderPolicyGate");function Eh(e){let{events:t,boundaryTracker:n,streamTimers:r,emitActiveExtensionEvent:o,providerName:s}=e;return{onTextDelta:i(a=>{r.resetIdleTimer(),n.markTextDelta(a),o("text:delta",{text:a}),t.onTextDelta?.(a)},"onTextDelta"),onThinkingDelta:i(a=>{r.resetIdleTimer(),n.markThinkingDelta(a),o("thinking:delta",{text:a}),t.onThinkingDelta?.(a)},"onThinkingDelta"),onThinkingEnd:i(a=>{r.resetIdleTimer(),o("thinking:end",{thinking:a}),t.onThinkingEnd?.(a)},"onThinkingEnd"),onToolInputDelta:i((a,c,l)=>{r.resetIdleTimer(),n.markToolInputStart(l?.toolId??`pending:${a}`),t.onToolInputDelta?.(a,c,l)},"onToolInputDelta"),onRateLimit:i((a,c,l)=>{r.resetIdleTimer(),o("provider:rate-limit",{provider:s,attempt:a,maxRetries:c,delayMs:l}),Mn(t,a,c,l)},"onRateLimit"),onRetryAfter:i(a=>{r.resetIdleTimer(),t.onRetryAfter?.(a)},"onRetryAfter"),onHeartbeat:i(a=>{a?r.clearIdleTimer():r.resetIdleTimer()},"onHeartbeat")}}i(Eh,"buildStreamHandlers");var gi=class{static{i(this,"BoundaryTrackerSession")}tracker;constructor(){this.tracker=new Ur}beginAttempt(t,n,r,o,s){this.tracker.beginRequest(t,n,r,o,s),lc(this.tracker.snapshot())}markTextDelta(t){this.tracker.markTextDelta(t)}markThinkingDelta(t){this.tracker.markThinkingDelta(t)}markToolInputStart(t){this.tracker.markToolInputStart(t)}inferFailureStage(){return this.tracker.inferFailureStage()}snapshot(){return this.tracker.snapshot()}};function Sh(e){let t=e.message.toLowerCase();return e.name==="StreamIncompleteError"||t.includes("stream incomplete")?"Stream interrupted before completion":t.includes("stream stalled")||t.includes("delayed response")||t.includes("60s idle")?"Stream stalled":t.includes("hard timeout")||t.includes("10 minutes")?"Provider response timed out":t.includes("socket hang up")||t.includes("connection error")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("fetch failed")||t.includes("network")?"Provider connection error":t.includes("timed out")||t.includes("timeout")||t.includes("etimedout")?"Provider request timed out":t.includes("aborted")?"Provider stream aborted":"Transient provider error"}i(Sh,"describeTransientProviderRetry");function Ah(e,t,n){let r=rc(e),o=new Br(n,{...r,enableNonStreamingFallback:r.enableNonStreamingFallback&&t.supportsNonStreamingFallback()});return{resilienceCfg:r,recoveryCoordinator:o}}i(Ah,"buildResilienceSession");async function Ch(e,t,n){if(e.name==="AbortError"&&t.signal.aborted&&!n?.aborted){let r=t.signal.reason?.message??"Stream stalled",{KodaXNetworkError:o}=await import("./dist-
|
|
471
|
+
`):e.baseSystemPrompt,decision:t}}i(_h,"applyProviderPolicyGate");function Eh(e){let{events:t,boundaryTracker:n,streamTimers:r,emitActiveExtensionEvent:o,providerName:s}=e;return{onTextDelta:i(a=>{r.resetIdleTimer(),n.markTextDelta(a),o("text:delta",{text:a}),t.onTextDelta?.(a)},"onTextDelta"),onThinkingDelta:i(a=>{r.resetIdleTimer(),n.markThinkingDelta(a),o("thinking:delta",{text:a}),t.onThinkingDelta?.(a)},"onThinkingDelta"),onThinkingEnd:i(a=>{r.resetIdleTimer(),o("thinking:end",{thinking:a}),t.onThinkingEnd?.(a)},"onThinkingEnd"),onToolInputDelta:i((a,c,l)=>{r.resetIdleTimer(),n.markToolInputStart(l?.toolId??`pending:${a}`),t.onToolInputDelta?.(a,c,l)},"onToolInputDelta"),onRateLimit:i((a,c,l)=>{r.resetIdleTimer(),o("provider:rate-limit",{provider:s,attempt:a,maxRetries:c,delayMs:l}),Mn(t,a,c,l)},"onRateLimit"),onRetryAfter:i(a=>{r.resetIdleTimer(),t.onRetryAfter?.(a)},"onRetryAfter"),onHeartbeat:i(a=>{a?r.clearIdleTimer():r.resetIdleTimer()},"onHeartbeat")}}i(Eh,"buildStreamHandlers");var gi=class{static{i(this,"BoundaryTrackerSession")}tracker;constructor(){this.tracker=new Ur}beginAttempt(t,n,r,o,s){this.tracker.beginRequest(t,n,r,o,s),lc(this.tracker.snapshot())}markTextDelta(t){this.tracker.markTextDelta(t)}markThinkingDelta(t){this.tracker.markThinkingDelta(t)}markToolInputStart(t){this.tracker.markToolInputStart(t)}inferFailureStage(){return this.tracker.inferFailureStage()}snapshot(){return this.tracker.snapshot()}};function Sh(e){let t=e.message.toLowerCase();return e.name==="StreamIncompleteError"||t.includes("stream incomplete")?"Stream interrupted before completion":t.includes("stream stalled")||t.includes("delayed response")||t.includes("60s idle")?"Stream stalled":t.includes("hard timeout")||t.includes("10 minutes")?"Provider response timed out":t.includes("socket hang up")||t.includes("connection error")||t.includes("econnrefused")||t.includes("enotfound")||t.includes("fetch failed")||t.includes("network")?"Provider connection error":t.includes("timed out")||t.includes("timeout")||t.includes("etimedout")?"Provider request timed out":t.includes("aborted")?"Provider stream aborted":"Transient provider error"}i(Sh,"describeTransientProviderRetry");function Ah(e,t,n){let r=rc(e),o=new Br(n,{...r,enableNonStreamingFallback:r.enableNonStreamingFallback&&t.supportsNonStreamingFallback()});return{resilienceCfg:r,recoveryCoordinator:o}}i(Ah,"buildResilienceSession");async function Ch(e,t,n){if(e.name==="AbortError"&&t.signal.aborted&&!n?.aborted){let r=t.signal.reason?.message??"Stream stalled",{KodaXNetworkError:o}=await import("./dist-Z6U7TWKJ.js");return new o(r,!0)}return e}i(Ch,"translateAbortError");function Rh(e){let t=sc(e.error,e.failureStage);ac(e.error,t);let n=e.recoveryCoordinator.decideRecoveryAction(e.error,t,e.attempt);return cc(n,e.attempt),e.events.onProviderRecovery?.({stage:n.failureStage,errorClass:n.reasonCode,attempt:e.attempt,maxAttempts:e.resilienceCfg.maxRetries,delayMs:n.delayMs,recoveryAction:n.action,ladderStep:n.ladderStep,fallbackUsed:n.shouldUseNonStreaming,serverRetryAfterMs:n.serverRetryAfterMs}),!e.events.onProviderRecovery&&n.action!=="manual_continue"&&e.events.onRetry?.(`${Sh(e.error)} \xB7 retry ${e.attempt}/${e.resilienceCfg.maxRetries} in ${Math.round(n.delayMs/1e3)}s`,e.attempt,e.resilienceCfg.maxRetries),{classified:t,decision:n}}i(Rh,"runRecoveryPipeline");async function Ih(e){let t=new AbortController,n=e.callerAbortSignal?AbortSignal.any([e.callerAbortSignal,t.signal]):t.signal,r=setTimeout(()=>{t.abort(new Error("API Hard Timeout (10 minutes)"))},e.hardTimeoutMs);try{return e.clearStreamTimers(),e.boundarySession.beginAttempt(e.providerName,e.modelOverride??e.streamProvider.getModel(),e.providerMessages,e.attempt,!0),{ok:!0,result:await e.streamProvider.complete(e.providerMessages,e.activeToolDefinitions,e.effectiveSystemPrompt,e.effectiveProviderReasoning,{onTextDelta:i(s=>{e.boundarySession.markTextDelta(s),e.emitActiveExtensionEvent("text:delta",{text:s}),e.events.onTextDelta?.(s)},"onTextDelta"),onThinkingDelta:i(s=>{e.boundarySession.markThinkingDelta(s),e.emitActiveExtensionEvent("thinking:delta",{text:s}),e.events.onThinkingDelta?.(s)},"onThinkingDelta"),onThinkingEnd:i(s=>{e.emitActiveExtensionEvent("thinking:end",{thinking:s}),e.events.onThinkingEnd?.(s)},"onThinkingEnd"),modelOverride:e.modelOverride,signal:n},n)}}catch(o){return{ok:!1,error:o instanceof Error?o:new Error(String(o))}}finally{clearTimeout(r)}}i(Ih,"executeNonStreamingFallback");var hC={type:"text",text:"..."};function Mh(e){return e.length===0?[hC]:e}i(Mh,"guardEmptyAssistantContent");async function Ph(e,t,n,r,o,s){if(e.beforeToolExecute){let c=await e.beforeToolExecute(t,n,{toolId:r});if(c===!1)return pe;if(typeof c=="string")return c}let a=await Ce("tool:before",{name:t,input:n,toolId:r,executionCwd:o,gitRoot:s});return a===!1?pe:typeof a=="string"?a:void 0}i(Ph,"getToolExecutionOverride");import gC from"fs";function yi(e,t){let n=e.input?.path;if(!(typeof n!="string"||n.trim().length===0))return K(n,t)}i(yi,"resolveToolTargetPath");function Nc(e,t){t&&(e.editRecoveryAttempts.delete(t),e.blockedEditWrites.delete(t))}i(Nc,"clearEditRecoveryStateForPath");function $h(e,t,n){if(e.name!=="write")return;let r=yi(e,t);if(!(!r||!n.blockedEditWrites.has(r))){if(!gC.existsSync(r)){n.blockedEditWrites.delete(r);return}return`[Tool Error] write: BLOCKED_AFTER_EDIT_FAILURE: Refusing to rewrite existing file ${r} while edit anchor recovery is in progress. Retry with edit using a smaller unique anchor or use insert_after_anchor.`}}i($h,"maybeBlockExistingFileWrite");async function Oh(e,t,n,r){let o=nr(t);if(!o)return;let s=typeof e.input?.path=="string"?e.input.path:void 0,a=yi(e,r);if(!s||!a)return;n.blockedEditWrites.add(a);let c=(n.editRecoveryAttempts.get(a)??0)+1;if(n.editRecoveryAttempts.set(a,c),n.lastToolErrorCode=o,o==="EDIT_TOO_LARGE")return _t("[edit:recovery]",{code:o,path:a,attempt:c,action:"split-edit"}),[`The previous edit for ${a} failed with ${o}.`,"Do not use write to replace the existing file.","Split the change into smaller edit calls, or use insert_after_anchor when you are appending a new section after a unique heading."].join(`
|
|
472
472
|
`);if(c>2)return _t("[edit:recovery]",{code:o,path:a,attempt:c,action:"stop-auto-recovery"}),[`The previous edit for ${a} failed with ${o}, and automatic anchor recovery is exhausted.`,"Do not escalate to a whole-file write.","Choose a smaller unique anchor manually, or switch to insert_after_anchor if this is a section append."].join(`
|
|
473
473
|
`);let l=c===1?120:400,d=await Zi(s,String(e.input?.old_string??""),r,l),u=d.candidates[0],f=d.candidates.slice(1,3);_t("[edit:recovery]",{code:o,path:a,attempt:c,windowLines:l,candidateCount:d.candidates.length});let m=[`The previous edit for ${a} failed with ${o}.`,"Do not use write to rewrite the existing file.","Retry with edit using a smaller unique old_string.","When appending a new section after a unique heading, use insert_after_anchor instead."];if(u&&(m.push(""),m.push(`Best nearby anchor window (${u.startLine}-${u.endLine}):`),m.push("```text"),m.push(u.excerpt),m.push("```")),f.length>0){m.push(""),m.push("Other nearby candidate anchors:");for(let g of f)m.push(`- lines ${g.startLine}-${g.endLine}: ${g.preview}`)}return m.join(`
|
|
474
474
|
`)}i(Oh,"buildEditRecoveryUserMessage");function Wn(e){return/^\[(?:Tool Error|Cancelled|Blocked|Error)\]/.test(e)}i(Wn,"isToolResultErrorContent");function Lh(e){return e.startsWith(rr)}i(Lh,"isCancelledToolResultContent");function Nh(e){return/^\[Tool Error\]\s+[^:]+:\s+([A-Z_]+):/.exec(e.trim())?.[1]}i(Nh,"extractStructuredToolErrorCode");var yC=new Set(["edit","write","multi_edit","apply_patch","delete","remove","rename"]),bC=3,wC=100;function Dh(e){return yC.has(e.toLowerCase())}i(Dh,"isMutationTool");function Fh(e){return e.files.size>=bC?!0:[...e.files.values()].reduce((n,r)=>n+r,0)>=wC}i(Fh,"isMutationScopeSignificant");function vC(e){let t=[...e.files.values()].reduce((r,o)=>r+o,0),n=[...e.files.entries()].map(([r,o])=>` - ${r} (~${o} lines)`).join(`
|