@kodax-ai/kodax 0.7.58 → 0.7.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +1228 -1225
  3. package/README_CN.md +647 -645
  4. package/dist/chunks/{agent-YJNC2755.js → agent-QQCRBU4C.js} +1 -1
  5. package/dist/chunks/argument-completer-7Q2T4YWA.js +2 -0
  6. package/dist/chunks/{chunk-6AU6EPO6.js → chunk-2UUOFT3Z.js} +1 -1
  7. package/dist/chunks/{chunk-NKHXRN7G.js → chunk-5GPJ6MB5.js} +110 -108
  8. package/dist/chunks/{chunk-P4VF3JEP.js → chunk-BEXLPFFB.js} +3 -3
  9. package/dist/chunks/{chunk-CQ6EQG7E.js → chunk-D7RENPQQ.js} +31 -31
  10. package/dist/chunks/{chunk-ZZDC75H4.js → chunk-PRIBJN5E.js} +70 -68
  11. package/dist/chunks/{chunk-HS2K74I4.js → chunk-S4GVQO3W.js} +13 -13
  12. package/dist/chunks/chunk-SDSLWDAZ.js +17 -0
  13. package/dist/chunks/{chunk-7QB55SYG.js → chunk-SVEJFERZ.js} +8 -8
  14. package/dist/chunks/{chunk-XXEIFNBE.js → chunk-TBXP7FEG.js} +1 -1
  15. package/dist/chunks/{chunk-526OILYL.js → chunk-UA744TZM.js} +1 -1
  16. package/dist/chunks/{chunk-QHWXPJEG.js → chunk-UXQILGRX.js} +145 -146
  17. package/dist/chunks/{chunk-CV6JHPEO.js → chunk-YADBB5GN.js} +1 -1
  18. package/dist/chunks/{chunk-OBPB5BQ6.js → chunk-Z23LK3IV.js} +6 -6
  19. package/dist/chunks/chunk-Z3ZXV3DZ.js +18 -0
  20. package/dist/chunks/compaction-config-GQIPCVFD.js +2 -0
  21. package/dist/chunks/{construction-bootstrap-CIXFH5SE.js → construction-bootstrap-YON4ZEMO.js} +1 -1
  22. package/dist/chunks/dist-73L4OYPD.js +2 -0
  23. package/dist/chunks/dist-EZXBR6NW.js +2 -0
  24. package/dist/chunks/host-LO6ZNTMV.js +2 -0
  25. package/dist/chunks/{paste-Y4DVUWSM.js → paste-4THGP5XW.js} +1 -1
  26. package/dist/chunks/run-manager-HTLXKU66.js +2 -0
  27. package/dist/chunks/{utils-FLVVQHM7.js → utils-5XVW33SY.js} +1 -1
  28. package/dist/index.d.ts +10 -9
  29. package/dist/index.js +2 -2
  30. package/dist/kodax_cli.js +995 -990
  31. package/dist/provider-capabilities.json +971 -986
  32. package/dist/sdk-agent.d.ts +9 -8
  33. package/dist/sdk-agent.js +1 -1
  34. package/dist/sdk-coding.d.ts +79 -14
  35. package/dist/sdk-coding.js +1 -1
  36. package/dist/sdk-llm.d.ts +1 -1
  37. package/dist/sdk-llm.js +1 -1
  38. package/dist/sdk-mcp.js +1 -1
  39. package/dist/sdk-media.js +1 -1
  40. package/dist/sdk-repl.d.ts +10 -9
  41. package/dist/sdk-repl.js +1 -1
  42. package/dist/sdk-session.d.ts +5 -4
  43. package/dist/sdk-session.js +1 -1
  44. package/dist/sdk-skills.d.ts +4 -231
  45. package/dist/sdk-skills.js +1 -1
  46. package/dist/types-chunks/{bash-prefix-extractor.d-D3cddmyV.d.ts → bash-prefix-extractor.d-BNdpV4Cf.d.ts} +29 -4
  47. package/dist/types-chunks/{guardrail.d-iK7FwMdW.d.ts → guardrail.d-CNdKuSD_.d.ts} +2 -2
  48. package/dist/types-chunks/{process.d-DHow2y2G.d.ts → process.d-BOrAxjvM.d.ts} +21 -3
  49. package/dist/types-chunks/{resolver.d-DDOfVYDr.d.ts → resolver.d-DFAKKUvt.d.ts} +56 -2
  50. package/dist/types-chunks/{run-manager.d-ByDcJc5g.d.ts → run-manager.d-CsJC9zYf.d.ts} +3 -3
  51. package/dist/types-chunks/{sdk-session-21Tt3N_x.d.ts → sdk-session-ByZlwgdM.d.ts} +14 -3
  52. package/dist/types-chunks/{storage.d-BsZrBPYu.d.ts → storage.d-DHL3XpAL.d.ts} +2 -2
  53. package/dist/types-chunks/{types.d-D4ZA8LJV.d.ts → types.d-CE_Ter29.d.ts} +1 -1
  54. package/dist/types-chunks/types.d-vJExiRje.d.ts +232 -0
  55. package/dist/types-chunks/{utils.d-BURxOxFd.d.ts → utils.d-D9FHU4wB.d.ts} +5 -4
  56. package/package.json +1 -1
  57. package/dist/chunks/argument-completer-QGBNXTYJ.js +0 -2
  58. package/dist/chunks/chunk-73Z7BK5H.js +0 -15
  59. package/dist/chunks/chunk-PIQWODWN.js +0 -18
  60. package/dist/chunks/compaction-config-OPMRZSAK.js +0 -2
  61. package/dist/chunks/dist-JSE7NICF.js +0 -2
  62. package/dist/chunks/dist-SDNQOW52.js +0 -2
  63. package/dist/chunks/host-H7FQMMRC.js +0 -2
  64. package/dist/chunks/run-manager-4H5HWMVW.js +0 -2
@@ -1,7 +1,7 @@
1
- import { b as PermissionMode, F as FileSessionStorage, S as SessionData } from './storage.d-BsZrBPYu.js';
1
+ import { b as PermissionMode, F as FileSessionStorage, S as SessionData } from './storage.d-DHL3XpAL.js';
2
2
  import { E as KodaXReasoningMode, j as KodaXMessage, c as KodaXContentBlock } from './types.d-Ci5YPFEh.js';
3
- import { m as KodaXAgentMode } from './bash-prefix-extractor.d-D3cddmyV.js';
4
- import { ai as KodaXSessionUiHistoryItem, am as KodaXSessionUiToolCall } from './process.d-DHow2y2G.js';
3
+ import { m as KodaXAgentMode } from './bash-prefix-extractor.d-BNdpV4Cf.js';
4
+ import { ai as KodaXSessionUiHistoryItem, am as KodaXSessionUiToolCall } from './process.d-BOrAxjvM.js';
5
5
 
6
6
  /**
7
7
  * TextBuffer - Text buffer management class - 文本缓冲区管理类
@@ -738,6 +738,10 @@ type RestoredHistorySeed = {
738
738
  } | {
739
739
  type: "thinking";
740
740
  text: string;
741
+ } | {
742
+ type: "sidecar";
743
+ text: string;
744
+ verdict?: "revise" | "blocked";
741
745
  } | {
742
746
  type: "tool_summary";
743
747
  text: string;
@@ -755,6 +759,13 @@ interface HistorySeedSourceMessage {
755
759
  role: KodaXMessage["role"];
756
760
  content: string | KodaXContentBlock[];
757
761
  _synthetic?: boolean;
762
+ /**
763
+ * Provenance marker persisted on host-injected messages. `'sidecar-verifier'`
764
+ * tags the synthetic user message the Sidecar Verifier injects on a `revise`
765
+ * verdict, so restore can render it under the Sidecar identity instead of
766
+ * swallowing it with the generic `_synthetic` skip.
767
+ */
768
+ _source?: string;
758
769
  }
759
770
  declare function extractHistorySeedsFromMessage(message: HistorySeedSourceMessage): RestoredHistorySeed[];
760
771
  declare function extractHistorySeedsFromMessages(messages: readonly HistorySeedSourceMessage[]): RestoredHistorySeed[];
@@ -1,5 +1,5 @@
1
- import { a as BashPrefixExtractor } from './bash-prefix-extractor.d-D3cddmyV.js';
2
- import { a5 as KodaXSessionData, aa as KodaXSessionLineage, ad as KodaXSessionNavigationOptions, ae as KodaXSessionRuntimeInfo, ag as KodaXSessionStorage } from './process.d-DHow2y2G.js';
1
+ import { a as BashPrefixExtractor } from './bash-prefix-extractor.d-BNdpV4Cf.js';
2
+ import { a5 as KodaXSessionData, aa as KodaXSessionLineage, ad as KodaXSessionNavigationOptions, ae as KodaXSessionRuntimeInfo, ag as KodaXSessionStorage } from './process.d-BOrAxjvM.js';
3
3
 
4
4
  /**
5
5
  * Permission Types
@@ -1,4 +1,4 @@
1
- import { z as Guardrail, aO as RunnerToolCall, e as Agent, g as AgentMessage, aR as RunnerToolResult, a_ as Span, _ as KodaXInputArtifact } from './process.d-DHow2y2G.js';
1
+ import { z as Guardrail, aO as RunnerToolCall, e as Agent, g as AgentMessage, aR as RunnerToolResult, a_ as Span, _ as KodaXInputArtifact } from './process.d-BOrAxjvM.js';
2
2
 
3
3
  /**
4
4
  * Guardrail Runtime — FEATURE_085 (v0.7.26).
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Agent Skills Standard Type Definitions
3
+ * Compliant with https://agentskills.io/ specification
4
+ *
5
+ * Also supports Claude Code extension fields for compatibility
6
+ */
7
+ /**
8
+ * Skill frontmatter as defined in SKILL.md YAML header
9
+ */
10
+ interface SkillFrontmatter {
11
+ /** Skill name in kebab-case, max 64 characters */
12
+ name: string;
13
+ /** Skill description, max 1024 characters, should include trigger conditions */
14
+ description: string;
15
+ /** Whether to disable automatic model invocation (default: false) */
16
+ disableModelInvocation?: boolean;
17
+ /** Whether skill appears in / menu (default: true) */
18
+ userInvocable?: boolean;
19
+ /** Tool restrictions, e.g., "Read, Grep, Bash(python:*)" */
20
+ allowedTools?: string;
21
+ /** Execution context - 'fork' for sub-agent execution */
22
+ context?: 'fork';
23
+ /** Sub-agent type: Explore, Plan, general-purpose, etc. */
24
+ agent?: string;
25
+ /** Argument hint for UI, e.g., "[file] [format]" */
26
+ argumentHint?: string;
27
+ /** Model preference: haiku, sonnet, opus, or a provider-specific model id */
28
+ model?: string;
29
+ /** Hooks scoped to this skill's lifecycle */
30
+ hooks?: SkillHooks;
31
+ license?: string;
32
+ compatibility?: string;
33
+ metadata?: Record<string, unknown>;
34
+ }
35
+ interface SkillHook {
36
+ matcher?: string;
37
+ command: string;
38
+ }
39
+ interface SkillHooks {
40
+ SessionStart?: SkillHook[];
41
+ UserPromptSubmit?: SkillHook[];
42
+ PreToolUse?: SkillHook[];
43
+ PostToolUse?: SkillHook[];
44
+ Stop?: SkillHook[];
45
+ SubagentStop?: SkillHook[];
46
+ Notification?: SkillHook[];
47
+ }
48
+ /**
49
+ * Lightweight skill metadata for system prompt injection
50
+ * Loaded at startup for progressive disclosure
51
+ */
52
+ interface SkillMetadata {
53
+ name: string;
54
+ description: string;
55
+ userInvocable: boolean;
56
+ argumentHint?: string;
57
+ path: string;
58
+ source: SkillSource;
59
+ /** If true, exclude from system prompt; still invokable by explicit slash forms. */
60
+ disableModelInvocation: boolean;
61
+ }
62
+ /**
63
+ * Complete skill definition with all content loaded
64
+ */
65
+ interface Skill extends SkillFrontmatter {
66
+ /** Skill directory absolute path */
67
+ path: string;
68
+ /** SKILL.md absolute path */
69
+ skillFilePath: string;
70
+ /** Markdown content (with variables resolved) */
71
+ content: string;
72
+ /** Raw markdown content (before variable resolution) */
73
+ rawContent: string;
74
+ /** Support files */
75
+ scripts?: SkillFile[];
76
+ references?: SkillFile[];
77
+ assets?: SkillFile[];
78
+ templates?: SkillFile[];
79
+ resources?: SkillFile[];
80
+ /** Runtime state */
81
+ loaded: boolean;
82
+ source: SkillSource;
83
+ }
84
+ /**
85
+ * File within a skill directory
86
+ */
87
+ interface SkillFile {
88
+ name: string;
89
+ path: string;
90
+ relativePath: string;
91
+ content?: string;
92
+ }
93
+ type SkillSource = 'project' | 'user' | 'plugin' | 'builtin';
94
+ /**
95
+ * Skill registry interface for managing discovered skills
96
+ */
97
+ interface ISkillRegistry {
98
+ /** Read-only view of discovered skill metadata */
99
+ readonly skills: ReadonlyMap<string, SkillMetadata>;
100
+ /** Discover skills from all configured paths */
101
+ discover(): Promise<void>;
102
+ /** Get skill metadata by name */
103
+ get(name: string): SkillMetadata | undefined;
104
+ /** Load full skill content */
105
+ loadFull(name: string): Promise<Skill>;
106
+ /** Invoke a skill with arguments */
107
+ invoke(name: string, args: string, context: SkillContext): Promise<SkillResult>;
108
+ /** Reload skills from disk */
109
+ reload(): Promise<void>;
110
+ /** List all discovered skills */
111
+ list(): ReadonlyArray<SkillMetadata>;
112
+ /** List skills that can be invoked directly by users */
113
+ listUserInvocable(): ReadonlyArray<SkillMetadata>;
114
+ /** Check whether a skill exists */
115
+ has(name: string): boolean;
116
+ /** Number of discovered skills */
117
+ readonly size: number;
118
+ }
119
+ /**
120
+ * v0.7.42 — SDK-embedder hook for `!`cmd`` dynamic context resolution.
121
+ *
122
+ * Receives the literal command string and the working directory the resolver
123
+ * would have used. Must return the command's text output (which the resolver
124
+ * splices into the skill markdown in place of the `!`cmd`` token), or throw
125
+ * to deny.
126
+ *
127
+ * **Trust boundary**: when the KodaX SDK is embedded inside a host app
128
+ * (e.g. KodaX Space, IDE extensions), the host typically mediates shell
129
+ * execution through a permission broker so the end user can approve / deny
130
+ * each command. Without this hook, `VariableResolver` directly `execSync`s
131
+ * commands using its own built-in whitelist — bypassing the host's broker
132
+ * and producing OS side-effects the user never saw.
133
+ *
134
+ * Embedders should route here to:
135
+ * - prompt the user via their own UI,
136
+ * - log execution to their audit trail,
137
+ * - apply policy (e.g. block network commands),
138
+ * - or refuse outright (throw).
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * const context: SkillContext = {
143
+ * workingDirectory: '/repo',
144
+ * executeDynamicContext: async (cmd, cwd) => {
145
+ * const approved = await brokerAskUser({ kind: 'skill-cmd', command: cmd, cwd });
146
+ * if (!approved) throw new Error('user denied');
147
+ * return await brokerExecute(cmd, cwd);
148
+ * },
149
+ * };
150
+ * ```
151
+ */
152
+ type SkillDynamicContextExecutor = (command: string, cwd: string) => Promise<string>;
153
+ interface SkillContext {
154
+ workingDirectory: string;
155
+ projectRoot?: string;
156
+ /**
157
+ * Optional. Used to substitute `${CLAUDE_SESSION_ID}` / `${KODAX_SESSION_ID}`
158
+ * template variables in skill markdown. Tool-invocation callers (e.g. the
159
+ * `skill` tool) may not have a session bound — in that case the resolver
160
+ * falls back to an empty replacement so the substitution doesn't leak the
161
+ * literal `${...}` to the LLM.
162
+ */
163
+ sessionId?: string;
164
+ environment?: Record<string, string>;
165
+ messages?: unknown[];
166
+ /**
167
+ * v0.7.42 — SDK-embedder hook for `!`cmd`` dynamic-context resolution.
168
+ * See {@link SkillDynamicContextExecutor} for the trust-boundary rationale.
169
+ * When present, completely replaces the built-in `execSync`-based path
170
+ * (whitelist + 5s timeout). When absent, the legacy whitelist path runs.
171
+ */
172
+ executeDynamicContext?: SkillDynamicContextExecutor;
173
+ /**
174
+ * v0.7.42 — hard-disable `!`cmd`` resolution.
175
+ * When `true`, encountering a `!`cmd`` token throws
176
+ * `[Dynamic context disabled by host]` regardless of any hook. Useful for
177
+ * embedders that want a single-flag kill switch without writing a hook.
178
+ * `executeDynamicContext` is ignored when this is `true`.
179
+ */
180
+ disableDynamicContext?: boolean;
181
+ }
182
+ interface SkillResult {
183
+ success: boolean;
184
+ /** Processed prompt content */
185
+ content: string;
186
+ /** Generated artifacts */
187
+ artifacts?: SkillArtifact[];
188
+ error?: string;
189
+ }
190
+ interface SkillArtifact {
191
+ type: 'file' | 'code' | 'text';
192
+ name: string;
193
+ content: string;
194
+ path?: string;
195
+ }
196
+ interface IVariableResolver {
197
+ /** Resolve all variables in content */
198
+ resolve(content: string, args: string, context: SkillContext): Promise<string>;
199
+ }
200
+ interface SkillPathsConfig {
201
+ projectPaths: string[];
202
+ userPaths: string[];
203
+ pluginPaths: string[];
204
+ builtinPath: string;
205
+ }
206
+ /**
207
+ * Get default skill discovery paths
208
+ *
209
+ * Priority order (highest first):
210
+ * 1. Project - <projectRoot>/.kodax/skills/
211
+ * 2. User - ~/.kodax/skills/
212
+ * 3. User - ~/.agents/skills/ (AgentSkills standard)
213
+ * 4. Plugin - (dynamic)
214
+ * 5. Builtin - packages/skills/src/builtin/
215
+ */
216
+ declare function getDefaultSkillPaths(projectRoot?: string): SkillPathsConfig;
217
+ /**
218
+ * All skill paths in priority order (highest to lowest)
219
+ *
220
+ * Priority: Project > User > Plugin > Builtin
221
+ * - Project: Project-specific skills override everything else
222
+ * - User: User preferences (~/.kodax/ and ~/.agents/)
223
+ * - Plugin: Third-party plugins
224
+ * - Builtin: Default skills shipped with KodaX
225
+ */
226
+ declare function getSkillPathsFlat(config: SkillPathsConfig): Array<{
227
+ path: string;
228
+ source: SkillSource;
229
+ }>;
230
+
231
+ export { getDefaultSkillPaths as m, getSkillPathsFlat as n };
232
+ export type { ISkillRegistry as I, Skill as S, IVariableResolver as a, SkillArtifact as b, SkillContext as c, SkillDynamicContextExecutor as d, SkillFile as e, SkillFrontmatter as f, SkillHook as g, SkillHooks as h, SkillMetadata as i, SkillPathsConfig as j, SkillResult as k, SkillSource as l };
@@ -1,8 +1,8 @@
1
- import { P as KodaXOptions, v as KodaXContextTokenSnapshot, m as KodaXAgentMode, U as KodaXRepoIntelligenceMode, a5 as KodaXSkillInvocationContext } from './bash-prefix-extractor.d-D3cddmyV.js';
2
- import { c as SessionStorage$1, b as PermissionMode } from './storage.d-BsZrBPYu.js';
3
- import { ai as KodaXSessionUiHistoryItem, aa as KodaXSessionLineage, a2 as KodaXSessionArtifactLedgerEntry, R as KodaXExtensionSessionState, Q as KodaXExtensionSessionRecord, ae as KodaXSessionRuntimeInfo, ag as KodaXSessionStorage, a5 as KodaXSessionData, bL as WorkflowProcessSource } from './process.d-DHow2y2G.js';
1
+ import { P as KodaXOptions, v as KodaXContextTokenSnapshot, a5 as KodaXSkillDynamicContextPolicy, m as KodaXAgentMode, U as KodaXRepoIntelligenceMode, a6 as KodaXSkillInvocationContext } from './bash-prefix-extractor.d-BNdpV4Cf.js';
2
+ import { c as SessionStorage$1, b as PermissionMode } from './storage.d-DHL3XpAL.js';
3
+ import { ai as KodaXSessionUiHistoryItem, aa as KodaXSessionLineage, a2 as KodaXSessionArtifactLedgerEntry, R as KodaXExtensionSessionState, Q as KodaXExtensionSessionRecord, ae as KodaXSessionRuntimeInfo, ag as KodaXSessionStorage, a5 as KodaXSessionData, bM as WorkflowProcessSource } from './process.d-BOrAxjvM.js';
4
4
  import { j as KodaXMessage, E as KodaXReasoningMode, o as KodaXProviderCapabilityProfile, d as KodaXCustomProviderConfig } from './types.d-Ci5YPFEh.js';
5
- import { A as AgentsFile, f as AutoModeStats, l as KodaXMcpServersConfig } from './guardrail.d-iK7FwMdW.js';
5
+ import { A as AgentsFile, f as AutoModeStats, l as KodaXMcpServersConfig } from './guardrail.d-CNdKuSD_.js';
6
6
  import * as readline from 'readline';
7
7
  import { SpawnSyncReturns } from 'child_process';
8
8
 
@@ -48,6 +48,7 @@ interface InteractiveContext {
48
48
  runtimeInfo?: KodaXSessionRuntimeInfo;
49
49
  createdAt: string;
50
50
  lastAccessed: string;
51
+ skillDynamicContext?: KodaXSkillDynamicContextPolicy;
51
52
  }
52
53
  declare function createInteractiveContext(options: {
53
54
  sessionId?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kodax-ai/kodax",
3
- "version": "0.7.58",
3
+ "version": "0.7.59",
4
4
  "description": "KodaX lightweight coding agent - TypeScript implementation with 15 built-in LLM provider aliases, published as a Node-free single-file CLI and SDK",
5
5
  "type": "module",
6
6
  "private": false,
@@ -1,2 +0,0 @@
1
- // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Aa as b,za as a}from"./chunk-QHWXPJEG.js";import"./chunk-6AU6EPO6.js";import"./chunk-XXEIFNBE.js";import"./chunk-NKHXRN7G.js";import"./chunk-73Z7BK5H.js";import"./chunk-PIQWODWN.js";import"./chunk-CQ6EQG7E.js";import"./chunk-D6QVXQNI.js";import"./chunk-526OILYL.js";import"./chunk-7QB55SYG.js";import"./chunk-HS2K74I4.js";import"./chunk-ZZDC75H4.js";import"./chunk-P4VF3JEP.js";import"./chunk-V4WSBIXB.js";export{a as ArgumentCompleter,b as createArgumentCompleter};
@@ -1,15 +0,0 @@
1
- // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{t as W,z as $}from"./chunk-PIQWODWN.js";import{Da as _,Ea as I}from"./chunk-7QB55SYG.js";import{Ja as b,_a as v,j as k,k as x}from"./chunk-HS2K74I4.js";import{$d as A,Qc as S,Rc as E,Wc as T,ae as w,ce as R,de as O,ee as g}from"./chunk-ZZDC75H4.js";import{a as i}from"./chunk-V4WSBIXB.js";import{join as Re}from"node:path";var L=["You generate KodaX Dynamic Workflow scripts.","Return JSON only. Do not wrap the answer in prose.","For simple tasks that do not benefit from multiple agents, return:",'{"action":"decline","reason":"..."}',"For complex tasks, return:",'{"action":"generate","manifest":{...},"source":"async function run(wf, args) { ... }","approvalSummary":"..."}',"Generated source may only coordinate agents through wf and args.","Generated source must return displayable final text for the user.","Never use import, require, process, fs, child_process, network APIs, shell commands, or direct file access."].join(`
3
- `),M=12e4,B="KODAX_WORKFLOW_GENERATION_TIMEOUT_SEC",U="KODAX_WORKFLOW_GENERATION_TIMEOUT_MS",J=64,H=2,V=2e3,X=[{name:"default"},{name:"variant-results",finalText:i((e,t)=>`Variant smoke child report from ${e} (${t}).`,"finalText"),synthesizeText:"Variant smoke synthesis report."},{name:"unverified-success",status:i(()=>"completed_unverified","status"),finalText:i(e=>`Smoke result for ${e}: completed with verification warnings.`,"finalText"),synthesizeText:"Smoke synthesis: completed with verification warnings."},{name:"empty-args-rerun",args:i(()=>({}),"args")}],Q=["- classify-and-act: first classify a mixed request, then route to the right worker behavior.","- fan-out-and-synthesize: split independent areas, files, hypotheses, reviewers, or perspectives; run them with wf.parallel, then wf.synthesize.","- adversarial-verification: produce or inspect a candidate, then have an independent verifier attack assumptions, evidence, and edge cases.","- generate-and-filter: ask several generators for distinct candidates, then filter/dedupe/rank before synthesis.","- tournament: compare competing approaches or answers and use synthesis as the judge.","- loop-until-done: run bounded follow-up rounds when findings should drive the next prompt.","- review or audit combines fan-out-and-synthesize with adversarial-verification: fan independent reviewers out across the dimensions, then pipe each finding straight into a verifier that tries to refute it before synthesis. A review with no verification stage ships findings a single reviewer's blind spot would have hidden."],Y=[{id:"import",pattern:/\bimport\s*(?:\(|['"*{]|\w+\s+from\b)/},{id:"require",pattern:/\brequire\s*\(/},{id:"process",pattern:/\bprocess\s*(?:\.|\[)/},{id:"fs",pattern:/\b(?:node:)?fs\b/},{id:"child_process",pattern:/\bchild_process\b/},{id:"shell",pattern:/\b(?:exec|spawn|execFile)\s*\(/},{id:"fetch",pattern:/\bfetch\s*\(/},{id:"Deno",pattern:/\bDeno\s*(?:\.|\[)/},{id:"Bun",pattern:/\bBun\s*(?:\.|\[)/}];function Z(e=process.env,t){let n=k(t?.workflow?.generationTimeoutSec,"timeouts.workflow.generationTimeoutSec");if(n!==void 0)return n;let r=x(e[B]);if(r!==void 0)return r;let s=e[U];if(s===void 0||s.trim().length===0)return M;let o=Number(s);return!Number.isFinite(o)||o<=0?M:Math.floor(o)}i(Z,"resolveWorkflowGenerationTimeoutMs");function ee(e,t){if(typeof e!="object"||e===null)throw new Error(`${t} must be an object`);return e}i(ee,"readRecord");function q(e,t){let n=e[t];if(typeof n!="string"||n.trim().length===0)throw new Error(`workflow generation ${t} must be a non-empty string`);return n}i(q,"readNonEmptyString");function te(e){let t=e.trim(),n=/^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(t);if(n?.[1])return n[1].trim();let r=t.indexOf("{"),s=t.lastIndexOf("}");if(r>=0&&s>r)return t.slice(r,s+1);throw new Error("workflow generation output did not contain a JSON object")}i(te,"extractJsonText");function ne(e){let t=te(e);return ee(JSON.parse(t),"workflow generation output")}i(ne,"parseGenerationJson");function re(e){if(typeof e=="string"){let n=e.trim();return n.length>0?n:void 0}if(typeof e!="object"||e===null)return;let t=e;for(let n of["name","id","title","phase"]){let r=t[n];if(typeof r=="string"&&r.trim().length>0)return r.trim()}}i(re,"normalizePhaseEntry");function se(e){return e.split(/(?:->|\u2192|,|\n)/).map(t=>t.trim()).filter(t=>t.length>0)}i(se,"splitPhaseString");function oe(e){if(typeof e!="object"||e===null)return e;let t=e,n=t.phases,r;if(Array.isArray(n)){let s=n.map(re);s.every(o=>o!==void 0)&&(r=s)}else if(typeof n=="string"){let s=se(n);s.length>0&&(r=s)}return r?{...t,phases:r}:e}i(oe,"normalizeGeneratedManifestCandidate");function ie(e){return e.match(/\bwf\.(?:runAgent|spawnAgent|synthesize)\s*\(/g)?.length??0}i(ie,"estimateDirectAgentCalls");function ae(e,t){let n=e.maxConcurrency*Math.max(1,e.phases.length)+2,r=ie(t)+2,s=Math.min(J,Math.max(e.maxAgents,n,r));return s>e.maxAgents?{...e,maxAgents:s}:e}i(ae,"reserveGeneratedWorkflowAgentCapacity");function m(e){let t="",n=0;for(;n<e.length;){let r=e[n],s=e[n+1];if(r==="/"&&s==="/"){for(t+=" ",n+=2;n<e.length&&e[n]!==`
4
- `;)t+=" ",n+=1;continue}if(r==="/"&&s==="*"){for(t+=" ",n+=2;n<e.length;){if(e[n]==="*"&&e[n+1]==="/"){t+=" ",n+=2;break}t+=e[n]===`
5
- `?`
6
- `:" ",n+=1}continue}if(r==='"'||r==="'"||r==="`"){let o=r;for(t+=" ",n+=1;n<e.length;){let l=e[n];if(t+=l===`
7
- `?`
8
- `:" ",n+=1,l==="\\"){n<e.length&&(t+=e[n]===`
9
- `?`
10
- `:" ",n+=1);continue}if(l===o)break}continue}t+=r??"",n+=1}return t}i(m,"stripGeneratedSourceLiterals");function le(e,t){for(let n=t+1;n<e.length;n+=1){let r=e[n];if(r==="\\"){n+=1;continue}if(r==="`")return!1;if(r==="$"&&e[n+1]==="{")return!0}return!1}i(le,"templateLiteralHasExpression");function ce(e){let t=m(e),n=/\bwf\s*\.\s*(wait|snapshot|send|stop)\s*\(/g,r;for(;(r=n.exec(t))!==null;){let s=r[1];if(!s)continue;let o=t.indexOf("(",r.index);if(o<0)continue;let l=o+1;for(;/\s/.test(e[l]??"");)l+=1;let f=e[l];if(!(f==="`"&&le(e,l))&&(f==='"'||f==="'"||f==="`"))return{method:s}}}i(ce,"findLiteralWorkflowTaskTarget");function N(e){return e!==void 0&&/[A-Za-z0-9_$]/.test(e)}i(N,"isIdentifierPart");function j(e){let t=m(e),n=/\basync\s+function\s+run\s*\([^)]*\)\s*\{/.exec(t);if(!n)return;let r=t.indexOf("{",n.index);if(r<0)return;let s=0;for(let o=r;o<t.length;o+=1){let l=t[o];if(l==="{"&&(s+=1),l==="}"&&(s-=1,s===0))return{start:r+1,end:o}}}i(j,"findRunBodyRange");function D(e,t){let n=m(e),r=1;for(let s=t.start;s<t.end;s+=1){let o=n[s];if(o==="{"){r+=1;continue}if(o==="}"){r-=1;continue}if(r===1&&n.startsWith("return",s)&&!N(n[s-1])&&!N(n[s+6])){let l=s+6,f=0;for(let u=l;u<t.end;u+=1){let p=n[u];if((p==="("||p==="["||p==="{")&&(f+=1),(p===")"||p==="]"||p==="}")&&(f-=1),f===0&&(p===";"||p===`
11
- `||p==="\r"))return e.slice(l,u).trim()}return e.slice(l,t.end).trim()}}}i(D,"findTopLevelReturnExpression");function F(e){let t=j(e);if(t)return D(e,t)}i(F,"findOuterRunReturnExpression");function fe(e){let t=j(e);if(!t)return[];let n=m(e),r=[],s=t.start,o=1;for(let f=t.start;f<t.end;f+=1){let u=n[f];if(u==="{"||u==="("||u==="["){o+=1;continue}if(u==="}"||u===")"||u==="]"){o-=1;continue}if(u===";"&&o===1){let p=e.slice(s,f+1).trim();p&&r.push(p),s=f+1}}let l=e.slice(s,t.end).trim();return l&&r.push(l),r}i(fe,"findOuterRunStatements");function ue(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}i(ue,"escapeRegExp");function de(e,t){let n=/^[A-Za-z_$][A-Za-z0-9_$]*$/.exec(t.trim())?.[0];if(!n)return!1;let r=ue(n),s=new RegExp(`^\\s*(?:const|let|var)\\s+${r}\\s*=\\s*(?:await\\s+)?wf\\s*\\.\\s*artifact\\b`),o=new RegExp(`^\\s*${r}\\s*=\\s*(?:await\\s+)?wf\\s*\\.\\s*artifact\\b`);return fe(e).some(l=>s.test(l)||o.test(l))}i(de,"isReturnedArtifactHandle");function C(e,t,n,r){let s=0;for(let o=t;o<e.length;o+=1){let l=e[o];if(l===n&&(s+=1),l===r&&(s-=1,s===0))return o}}i(C,"findMatchingDelimiter");function pe(e,t,n){let r=0;for(let s=t;s<n;s+=1){let o=e[s];if(o==="("||o==="["||o==="{"){r+=1;continue}if(o===")"||o==="]"||o==="}"){r-=1;continue}if(o===","&&r===0)return s}}i(pe,"findTopLevelComma");function he(e){let t=m(e),n=/^\s*(?:await\s+)?wf\s*\.\s*phase\s*\(/.exec(t);if(!n)return;let r=t.indexOf("(",n.index);if(r<0)return;let s=C(t,r,"(",")");if(s===void 0)return;let o=pe(t,r+1,s);if(o===void 0)return;let l=e.slice(o+1,s).trim(),f=m(l),u=f.indexOf("=>");if(u<0)return;let p=u+2,a=f.slice(p).search(/\S/);if(a<0)return;let c=p+a;if(f[c]!=="{")return l.slice(c).trim();let d=C(f,c,"{","}");if(d!==void 0)return D(l,{start:c+1,end:d})}i(he,"findPhaseCallbackReturnExpression");function P(e,t){return new RegExp(`^(?:await\\s+)?wf\\s*\\.\\s*${t}\\b`).test(e.trim())}i(P,"isDirectWorkflowCall");function G(e,t){let n=t.trim();if(/^(?:undefined|null|void\s+0|\{\s*\}|\[\s*\]|''|""|``)$/.test(n)||P(n,"artifact")||de(e,n))return!1;if(P(n,"phase")){let r=he(n);return r!==void 0&&G(n,r)}return!0}i(G,"isDisplayableReturnExpression");function me(e){let t=F(e);return t?G(e,t):!1}i(me,"hasDisplayableRunReturn");function we(e){try{R(e,{filename:"generated-workflow.js",requireAsyncRun:!0,checkSourcePolicy:!1})}catch(t){let n=t instanceof Error?t.message:String(t),s=/Unexpected (identifier|string|token|end of input)|Invalid or unexpected token/i.test(n)?" \u2014 a prompt string likely has an unescaped quote or apostrophe; wrap that string in double quotes or backticks, or escape the quote, then retry":"";throw new Error(`workflow generation source has invalid JavaScript syntax: ${n}${s}`)}}i(we,"assertGeneratedWorkflowSyntax");function ge(e){let t=0,n=new Map,r=[],s=i(a=>{t+=1;let c=`smoke-task-${t}-${Math.random().toString(36).slice(2,8)}`;return n.set(c,a),{taskId:c,name:a}},"nextHandle"),o=i((a,c)=>{if(n.has(c))return;throw[...n.entries()].find(h=>h[1]===c)?new Error(`wf.${a}("${c}") used an agent name, but workflow task APIs require the taskId returned by spawnAgent/runAgent. Store the handle/result and pass handle.taskId or result.taskId. wf.runAgent already returns the completed result; wf.parallel returns the array of results.`):new Error(`wf.${a}("${c}") references an unknown workflow task id`)},"assertKnownTaskId"),l=i(a=>{for(let c of a.evidenceRefs??[]){if(c.startsWith("file:")||c.startsWith("diff:")||c.startsWith("finding:"))continue;if(c.startsWith("task_id:")){let h=c.slice(8).trim();if(h.length===0)throw new Error(`wf.runAgent("${a.name}") evidenceRefs contains empty task_id: reference`);o("evidenceRefs",h);continue}throw[...n.entries()].find(h=>h[1]===c)?new Error(`wf.runAgent("${a.name}") evidenceRefs contains agent name "${c}". Use "task_id:" + result.taskId from the child result.`):new Error(`wf.runAgent("${a.name}") evidenceRefs contains unsupported ref "${c}". Use file:, diff:, finding:, or task_id:<id>.`)}},"assertEvidenceRefs"),f=i((a,c)=>{o("wait",a);let d=n.get(a)??c??a,h=e.status?.(d,a)??"completed";return{taskId:a,name:d,status:h,finalText:e.finalText?.(d,a)??`Smoke result for ${d}: completed, done, verified.`}},"resultFor"),u=i((a,c)=>{o(a,c);let d=n.get(c)??c;return{taskId:c,name:d,status:"completed",lastText:`Smoke snapshot for ${d}`}},"snapshotFor");return{api:{runId:"run-smoke",args:void 0,budget:{total:null,spent:i(()=>0,"spent"),remaining:i(()=>1/0,"remaining")},phase:i(async(a,c)=>c(),"phase"),spawnAgent:i(async a=>(l(a),s(a.name)),"spawnAgent"),runAgent:i(async a=>{l(a);let c=s(a.name),d=f(c.taskId,a.name);if(d.status==="failed"||d.status==="stopped")throw new Error(`workflow task ${d.name} (${d.taskId}) ${d.status}`);return d},"runAgent"),wait:i(async a=>f(a),"wait"),snapshot:i(async a=>u("snapshot",a),"snapshot"),output:i(async a=>u("output",a),"output"),send:i(async a=>{o("send",a)},"send"),stop:i(async a=>{o("stop",a)},"stop"),parallel:i(async a=>Promise.all(a.map(c=>c())),"parallel"),synthesize:i(async()=>({text:e.synthesizeText??"Smoke synthesis: completed, done, verified."}),"synthesize"),artifact:i(async a=>(r.push(a),{name:a}),"artifact"),log:i(()=>{},"log")},artifactCount:i(()=>r.length,"artifactCount")}}i(ge,"createSmokeWorkflowApi");function ke(e,t){if(t>0)return!0;if(typeof e=="string")return e.trim().length>0;if(e==null)return!1;if(typeof e!="object")return!0;if(Array.isArray(e))return e.length>0;let n=e,r=!1,s=n.synthesis;if(typeof s=="string"&&(r=!0,s.trim().length>0))return!0;if(s&&typeof s=="object"){r=!0;let o=s.text;if(typeof o=="string"&&o.trim().length>0)return!0}for(let o of["summary","report","text","result"]){let l=n[o];if(l!==void 0&&(r=!0),typeof l=="string"&&l.trim().length>0)return!0}return r&&Object.keys(n).every(o=>o==="synthesis"||o==="summary"||o==="report"||o==="text"||o==="result")?!1:Object.keys(n).length>0}i(ke,"isSmokeResultDisplayable");async function ye(e){for(let t of X)try{let n=ge(t),r=await O({source:e.source,wf:n.api,args:t.args?.(e.request)??{request:e.request},filename:"generated-workflow-smoke.js",timeoutMs:V});if(!ke(r,n.artifactCount()))throw new Error("run() returned no displayable result or artifact")}catch(n){let r=n instanceof Error?n.message:String(n);throw new Error(`workflow generation source failed safe smoke validation (${t.name}): ${r}`)}}i(ye,"assertGeneratedWorkflowSmoke");function y(e){if(e.trim().length===0)throw new Error("workflow generation source must be non-empty");if(!/\basync\s+function\s+run\s*\(/.test(e))throw new Error("workflow generation source must define async function run(wf, args)");we(e);let t=m(e);for(let r of Y)if(r.pattern.test(t))throw new Error(`forbidden generated workflow token: ${r.id}`);if(/\.\s*output\b/.test(t))throw/\bwf\s*\.\s*output\s*\(/.test(t)?new Error("workflow generation source must use wf.snapshot(taskId) instead of legacy wf.output(taskId)"):new Error("workflow generation source must use finalText/text instead of non-existent .output");let n=ce(e);if(n)throw new Error(`workflow generation source must pass taskId variables to wf.${n.method}(...) instead of string literals; use handle.taskId from wf.spawnAgent(...) or result.taskId from wf.runAgent(...).`);for(let r of t.split(/\r?\n/)){let s=r.search(/\bwf\.artifact\s*\(/);if(s>=0&&!/\b(?:await|return)\b/.test(r.slice(0,s)))throw new Error("workflow generation source must await wf.artifact(...)")}if(!me(e)){let r=F(e),s=r===void 0?"no top-level `return` was found in run() \u2014 a return inside a wf.phase(...) callback does not count":`the top-level return \`${r.slice(0,80)}\` is not displayable \u2014 do not return undefined/null/{}, a bare wf.artifact(...) write, or a wf.phase(...) without a displayable callback return`;throw new Error(`workflow generation source outer run function must return displayable final text (${s})`)}return e}i(y,"validateGeneratedWorkflowSource");function xe(e){let t=e?.trim();return t?["","Referenced skill instructions (authoritative):",t,"","Skill handling requirements:","- Treat the referenced skill instructions above as binding requirements for this workflow generation.","- Preserve skill-specific file layout, naming, and process requirements in child-agent prompts that do the work.",'- Do not replace concrete skill requirements with vague paths such as "or similar"; choose paths from the skill or instruct the child to invoke the skill before acting.']:[]}i(xe,"buildReferencedSkillPromptSection");function z(e,t){return["Task request:",e,...xe(t),"","Available WorkflowApi calls:","- wf.phase(name, async () => ...)","- wf.spawnAgent({ name, prompt, readOnly, modelHint, isolation, evidenceRefs, verification })","- wf.runAgent({ name, prompt, readOnly, modelHint, isolation, evidenceRefs, verification })","- wf.wait(taskId), wf.snapshot(taskId), wf.send(taskId, content), wf.stop(taskId, reason)","- wf.parallel([() => promise], { concurrency })","- wf.synthesize({ inputs, rubric }); inputs may be an array of materials, one already-formatted string, or a named object of materials","- wf.artifact(name, value), wf.log({ message, data })","- Return shapes: wf.runAgent/wf.wait return { taskId, name, status, finalText, digest?, verification?, usage }; wf.snapshot returns { taskId, name, status, lastText? }; wf.synthesize returns { text }; wf.artifact returns { name, path? }.","- Task identity rule: taskId is the opaque result.taskId/handle.taskId value, never the agent name string. Do not hardcode task IDs or pass string literals to wf.wait/wf.snapshot/wf.send/wf.stop; pass handle.taskId or result.taskId variables.","- Important naming trap: never use anyVariable.output in generated source. Agent results use finalText; synthesis results use text; task snapshots use lastText.","- Always await asynchronous workflow calls, especially wf.artifact(...), before returning.",'- Treat args as optional rerun input. Read request text with a fallback such as String(args.request || "the original request") or bake stable request context into child prompts.',"- For fan-out, prefer wf.parallel with thunks that call wf.runAgent; if using wf.spawnAgent, always wait or stop each handle so maxConcurrency capacity can release.","- Correct fan-out result pattern: const results = await wf.parallel([...].map((item) => () => wf.runAgent({...})), { concurrency }); then use results[n].finalText or results.map((r) => r.finalText). Do not call wf.wait after wf.runAgent.","- Keep intermediate findings in local variables and pass their finalText/text values forward; artifacts are durable outputs, not mutable args.","- File-writing/implementation requests are not report-only workflows. If the user asks to create, update, land, implement, or write project files, set manifest.readOnly=false, use readOnly:false child agents for the writing phases, give exact target paths in the prompt, and include verification:{ requiresMutation:true, requiredChangedPaths:[...], rejectPreparatoryFinalText:true } whenever target paths are knowable.","- Never put placeholder paths such as vNEXT.md or TODO.md in requiredChangedPaths. If the exact path is not knowable, omit requiredChangedPaths and keep requiresMutation:true.","- A write child must not ask the user to confirm routine filenames or version numbers already inferable from the request/context; it should choose the minimal project-consistent target paths, write them, and report what changed.",'- Prefer shared-cwd for write children. Do not set isolation:"worktree" for writing phases unless the workflow has an explicit merge-back strategy; isolated write evidence is not a delivered project change.',"- The outer run function must return displayable final text, preferably { synthesis: finalText }. Returning only inside a wf.phase callback is invalid. Artifact-only or empty returns are invalid.",'- Also await wf.artifact("final-report", { summary/report/text: finalText }) for durable inspection when a final report is produced.','- For multi-line prompts, rubrics, or report templates inside source, use JavaScript template literals (`...`) or arrays joined with "\\n"; never place raw newlines inside single-quoted or double-quoted strings.',"- Do not ask child agents to emit special transcript marker blocks. KodaX derives child-agent transcript digests after each child finishes; child prompts should focus on the actual work product and final report.","","Minimal source field-usage example; use it for result fields/syntax, not as the default workflow shape:","async function run(wf, args) {",' const first = await wf.runAgent({ name: "first-pass", prompt: String(args.request || ""), readOnly: true });',' const second = await wf.runAgent({ name: "second-pass", prompt: first.finalText, readOnly: true });',' const synthesis = await wf.synthesize({ inputs: [first.finalText, second.finalText], rubric: "Synthesize a final answer." });'," const finalText = synthesis.text;",' await wf.artifact("final-report", { report: finalText });'," return { synthesis: finalText };","}","","Canonical write-and-verify pattern for requests that must land project files:","async function run(wf, args) {",' const request = String(args.request || "Implement the requested project change.");'," const targetPaths = Array.isArray(args.targetPaths) ? args.targetPaths.map(String).filter(Boolean) : [];"," const writer = await wf.runAgent({",' name: "implementation-writer",'," prompt: [",' "Implement the requested project change in the real workspace.",',' "Use project conventions, write the files, and do not stop at a plan.",',' targetPaths.length ? "Target paths: " + targetPaths.join(", ") : "Choose the minimal project-consistent target paths.",'," request",' ].join("\\n"),'," readOnly: false,"," verification: {"," requiresMutation: true,"," ...(targetPaths.length ? { requiredChangedPaths: targetPaths } : {}),"," rejectPreparatoryFinalText: true"," }"," });"," const finalText = writer.finalText;",' await wf.artifact("final-report", { report: finalText, verification: writer.verification });'," return { synthesis: finalText, verification: writer.verification };","}","",`Supported pattern ids: ${A.join(", ")}`,"","Pattern selection guidance:",...Q,"- Complex multi-part work should normally include at least two work phases plus a final wf.synthesize barrier.","- Do not collapse independent investigation, verification, ranking, generation/filtering, or iteration into one child agent.","- A generated workflow with only one child agent is appropriate only when the request has one indivisible work product; otherwise decline simple tasks or generate a richer pattern.",'- Use evidenceRefs when one child reviews another child result; reference child results as "task_id:" + result.taskId, never as bare agent names. Use modelHint:"deep" for verifiers, judges, and synthesis-critical workers.',"","Manifest requirements:","- name, description, phases, readOnly, maxAgents, maxConcurrency, optional plannedAgents, optional tokenBudget",'- phases must be a JSON array of non-empty string literals, for example ["investigate","verify","synthesize"]; never return phase objects or a single string',"- maxAgents and maxConcurrency must be positive JSON integers","- plannedAgents is the best estimate of how many child agents this script will normally launch; it is for progress display and must be no larger than maxAgents","- maxAgents is a lifetime total cap for every wf.runAgent, wf.spawnAgent, and wf.synthesize call in the whole run, not the parallel lane count; reserve enough for all phases plus synthesis","- Do not set tokenBudget unless the user explicitly asks for a token/resource budget; omit it for normal complex work","- readOnly must be a JSON boolean","- optional mayUseWorktree when child prompts need isolated worktrees","- patterns must use only supported ids","- Use the same natural language as the task request for manifest description, approvalSummary, child agent prompts, synthesis rubric, and artifact text unless the user explicitly asks otherwise","","Return JSON only."].join(`
12
- `)}i(z,"buildWorkflowGenerationUserPrompt");async function be(e,t){let n=_(e),r=I(e);if(n.length===0&&r.length===0)return;let s=t.context?.gitRoot??t.context?.executionCwd??process.cwd(),o=t.context?.executionCwd??s,l=S(s);l.size===0&&await E(s);let f={workingDirectory:o,projectRoot:s,environment:{}},u=[...n,...r.filter(a=>!n.includes(a)&&l.has(a))];if(u.length===0)return;let p=[];for(let a of n)if(!l.has(a)){let c=l.list().map(d=>d.name).sort().join(", ");throw new Error(`workflow generation referenced unknown skill "${a}". Available skills: ${c||"(none)"}`)}for(let a of u){let c=await l.loadFull(a),d=await T(c,"",f);if(d.disableModelInvocation)throw new Error(`workflow generation referenced disabled skill "${a}"`);p.push(d.content)}return p.join(`
13
-
14
- `)}i(be,"buildWorkflowGenerationSkillContext");function ve(e){let t=["- Replace result.output from wf.runAgent(...) or wf.wait(...) with result.finalText.","- Replace result.output from wf.synthesize(...) with result.text.",'- Replace hardcoded wf.wait("...")/wf.snapshot("...")/wf.send("...", ...)/wf.stop("...", ...) calls with handle.taskId/result.taskId variables.','- Replace wf.wait("agent-name") after wf.runAgent(...) with captured runAgent/parallel results; wf.wait only accepts taskId values from spawnAgent handles.',"- Preserve the existing phase, fan-out, cross-review, and synthesis topology unless that topology itself is invalid; fix API usage instead of collapsing the workflow.","- Keep the outer run() return displayable, such as { synthesis: finalText }.",'- Fix generated JavaScript harness errors, including ReferenceError, wrong wf.* argument shapes, and multi-line prompts/rubrics that need template literals or "\\n".'];return(/\bwf\s*\.\s*output\s*\(/.test(e.previousOutput)||e.error.includes("wf.snapshot(taskId)"))&&t.splice(2,0,"- Replace wf.output(taskId) with wf.snapshot(taskId) for in-flight task snapshots."),[z(e.request,e.skillContext),"","Your previous output failed KodaX workflow validation.",`Repair attempt: ${e.attempt} of ${e.maxAttempts}.`,`Validation error: ${e.error}`,"","Common contract fixes:",...t,"","Previous output:",e.previousOutput,"","Return corrected JSON only. Keep the same task intent, but make the manifest and source valid."].join(`
15
- `)}i(ve,"buildWorkflowGenerationRepairPrompt");function Se(e){return/(?:token\s*(?:budget|limit|cap)|budget\s*(?:for|of)?\s*tokens?|\b\d+(?:\.\d+)?\s*(?:k|m)?\s*tokens?\b|\d+(?:\.\d+)?\s*(?:k|m)?\s*令牌|(?:tokens?|令牌).{0,12}(?:预算|上限|限制)|(?:预算|上限|限制).{0,12}(?:tokens?|令牌))/i.test(e)}i(Se,"requestExplicitlyMentionsTokenBudget");function Ee(e,t){if(e.tokenBudget===void 0||t===void 0||Se(t))return e;let{tokenBudget:n,...r}=e;return r}i(Ee,"stripImplicitTokenBudget");function Te(e,t={}){let n=ne(e),r=n.action;if(r==="decline")return{kind:"declined",reason:q(n,"reason"),rawText:e};if(r!=="generate")throw new Error('workflow generation action must be "generate" or "decline"');let s=y(q(n,"source")),o=Ee(ae(w(oe(n.manifest)),s),t.request),l=typeof n.approvalSummary=="string"&&n.approvalSummary.trim().length>0?n.approvalSummary:o.description;return{kind:"generated",manifest:o,source:s,module:g({manifest:o,source:s}),scriptSnapshot:{manifest:o,source:s},approvalSummary:l,rawText:e}}i(Te,"parseWorkflowGeneration");async function Ae(e){let t=e.request.trim();if(!t)return{kind:"declined",reason:"Workflow request is empty.",rawText:""};let n=H+1,r=z(t,e.skillContext),s="";for(let o=1;o<=n;o+=1){let l=await e.generateText({system:L,prompt:r,...e.signal?{signal:e.signal}:{}});try{let f=Te(l,{request:t});return f.kind==="generated"&&await ye({source:f.source,request:t}),f}catch(f){if(s=f instanceof Error?f.message:String(f),o>=n)break;r=ve({request:t,...e.skillContext?{skillContext:e.skillContext}:{},previousOutput:l,error:s,attempt:o+1,maxAttempts:n})}}throw new Error(`workflow generation did not produce a valid workflow after ${n} attempts. Last validation error: ${s}`)}i(Ae,"generateWorkflow");async function K(e){let t=b(e.options.provider),n=e.options.modelOverride??e.options.model??t.getModel(),r=e.options.effort?.trim();if(e.timeoutMs!==void 0&&e.timeoutSec!==void 0)throw new Error("workflow generation timeoutSec and timeoutMs cannot both be set");let s=e.timeoutMs??k(e.timeoutSec,"workflow generation timeoutSec")??Z(process.env,e.options.timeouts),o=e.skillContext??await be(e.request,e.options);return Ae({request:e.request,...o?{skillContext:o}:{},...e.signal?{signal:e.signal}:{},generateText:i(async l=>{let f=[{role:"user",content:l.prompt}],u=await v({provider:t,model:n,system:l.system,messages:f,querySource:"workflow-generation",timeoutMs:s,...r?{reasoning:{effort:r}}:{},...l.signal?{abortSignal:l.signal}:{}});if(!u.text.trim()){let p=u.error?`: ${u.error.message}`:"",a=u.stopReason==="timeout"?` after ${s}ms`:"";throw new Error(`workflow generation failed (${u.stopReason}${a})${p}`)}return u.text},"generateText")})}i(K,"generateWorkflowFromOptions");async function Oe(e){let t=e.source;if(t.kind==="saved")return{module:t.module};if(t.kind==="inline"){let s=w(t.manifest);return y(t.source),{module:g({manifest:s,source:t.source}),scriptSnapshot:{manifest:s,source:t.source}}}let r=await(e.generateWorkflow??K)({request:t.request,options:e.options});return r.kind==="declined"?{declined:r.reason}:{module:r.module,scriptSnapshot:r.scriptSnapshot}}i(Oe,"resolveModule");async function Fe(e){let t=await Oe(e);if("declined"in t)return{kind:"declined",reason:t.declined};let{module:n,scriptSnapshot:r}=t,s=e.now??(()=>Date.now()),o=e.runId??`run-${s().toString(36)}`,l=Re(e.runsBaseDir,o),f=e.manager??$(),u=W(n,e.options.workflowHostPolicy),p=f.startFromOptions({module:n,args:e.args,options:e.options,runId:o,runDir:l,...r?{scriptSnapshot:r}:{},...e.resumeFromRunDir?{resumeFromRunDir:e.resumeFromRunDir}:{},...e.processMetadata?{processMetadata:e.processMetadata}:{},...e.approval?{approval:e.approval}:{},...e.onEvent?{onEvent:e.onEvent}:{},...e.signal?{signal:e.signal}:{}});return{kind:"started",runId:o,runDir:l,module:n,managed:p,approvalSummary:u,...r?{scriptSnapshot:r}:{}}}i(Fe,"startManagedWorkflow");export{L as a,M as b,Z as c,y as d,z as e,be as f,Te as g,Ae as h,K as i,Fe as j};
@@ -1,18 +0,0 @@
1
- // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{Ec as Ee,Fa as Re,Fc as Ae,vb as We,wb as X,xb as be,yb as Te}from"./chunk-7QB55SYG.js";import{N as pe}from"./chunk-HS2K74I4.js";import{Va as G,Zd as ke,_d as ye,ae as F,ce as z,db as ge,ie as J,je as b,ke as H,le as ve,se as Se,te as xe,ue as Me}from"./chunk-ZZDC75H4.js";import{B as he}from"./chunk-P4VF3JEP.js";import{a}from"./chunk-V4WSBIXB.js";import{dirname as yn}from"node:path";import{execFile as gt}from"node:child_process";import B from"node:path";import{promisify as kt}from"node:util";var yt=kt(gt),vt=1e4,Ie=2,Pe=new Set(["write","edit","multi_edit","insert_after_anchor"]),St=/^\s*(?:let me|i will|i'll|i am going to)\b[\s\S]{0,120}\b(?:start|create|implement|write|build|plan)\b|^\s*(?:我将|让我|接下来)[\s\S]{0,80}(?:开始|创建|编写|实现|制定)/i;function xt(e){if(e?.timeoutMs!==void 0){if(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0)throw new Error("workflow wait timeoutMs must be a positive number");return Math.floor(e.timeoutMs)}}a(xt,"normalizeWaitTimeoutMs");function Y(e){return e?.requiresMutation===!0||(e?.requiredChangedPaths?.length??0)>0}a(Y,"hasVerificationWork");function T(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").trim()}a(T,"normalizeWorkspacePath");function Mt(e,t){let n=t.gitRoot?B.resolve(t.gitRoot):void 0,o=B.isAbsolute(e)&&n?B.relative(n,B.resolve(e)):e;return T(o)}a(Mt,"normalizeRequiredPath");function Rt(e){let t=(e.readOnly??!1)===!1?{enforcement:"warn",requiresMutation:!0,rejectPreparatoryFinalText:!0}:void 0;if(e.verification!==void 0){let n={...t??{},...e.verification,enforcement:e.verification.enforcement??"hard"},o=e.verification.requiredChangedPaths;return{verification:{...n,...o!==void 0&&o.length>0&&n.requiresMutation===void 0?{requiresMutation:!0}:{}}}}return{verification:t}}a(Rt,"resolveVerificationForInput");function Ne(e){let t=e.trim();return t.length>0&&St.test(t)}a(Ne,"isPreparatoryOnlyText");function Wt(e,t){let n=e.trim(),o=t?.trim();return o&&(n.length===0||Ne(n))?o:e}a(Wt,"selectWorkflowFinalText");async function L(e,t){return(await yt("git",[...e],{cwd:t,timeout:vt,windowsHide:!0,maxBuffer:4194304})).stdout.toString()}a(L,"runGit");async function bt(e){let t=e.gitRoot??e.executionCwd??process.cwd(),n=(await L(["rev-parse","--show-toplevel"],t)).trim(),o=await Promise.all([L(["diff","--name-only","--"],n),L(["diff","--cached","--name-only","--"],n),L(["ls-files","--others","--exclude-standard"],n)]);return[...new Set(o.flatMap(s=>s.split(/\r?\n/)).map(T).filter(s=>s.length>0))]}a(bt,"listGitChangedFiles");async function Z(e,t){try{return{paths:(await t(e)).map(T).filter(o=>o.length>0)}}catch(n){return{paths:[],error:n instanceof Error?n.message:String(n)}}}a(Z,"captureChangedPaths");function Tt(){return{toolNameById:new Map,toolPathById:new Map,succeededToolCalls:[],succeededPaths:[]}}a(Tt,"createMutationRecorder");function Et(e){if(e)for(let t of["path","file_path","target_path"]){let n=e[t];if(typeof n=="string"&&n.trim().length>0)return T(n)}}a(Et,"readMutationPath");function At(e,t){return{...e??{},onToolUseStart:a((n,o)=>{if(Pe.has(n.name)){t.toolNameById.set(n.id,n.name);let s=Et(n.input);s!==void 0&&t.toolPathById.set(n.id,s)}e?.onToolUseStart?.(n,o)},"onToolUseStart"),onToolResult:a((n,o)=>{let s=t.toolNameById.get(n.id)??n.name;if(Pe.has(s)&&!n.content.trimStart().startsWith("[Tool Error]")){t.succeededToolCalls.push(s);let r=t.toolPathById.get(n.id);r!==void 0&&t.succeededPaths.push(r)}e?.onToolResult?.(n,o)},"onToolResult")}}a(At,"wrapEventsForMutationRecording");function Q(e){return[...new Set(e.filter(t=>t.trim().length>0))]}a(Q,"uniqueItems");function Ce(e){let t=e.verification;if(!t)return;let n=[],o=new Set(e.before.paths.map(T)),s=Q(e.after.paths.map(T)),r=s.filter(g=>!o.has(g)),i=Q(e.mutationRecorder.succeededToolCalls),c=e.acceptToolMutationEvidence?i:[],w=e.acceptToolMutationEvidence?Q(e.mutationRecorder.succeededPaths.map(T)):[],u=r.length>0||c.length>0,p=t.enforcement??"hard",v=(t.requiredChangedPaths??[]).map(g=>Mt(g,e.ctx));t.requiresMutation===!0&&(e.before.error!==void 0||e.after.error!==void 0?n.push(`workspace mutation verification could not read changed files: ${e.after.error??e.before.error}`):u||n.push(e.acceptToolMutationEvidence||i.length===0?"expected file mutations, but no new workspace changes or successful write tools were observed":"write tools ran in an isolated worktree, but no main workspace changes were present after cleanup")),e.term.limitReached===!0&&!u&&n.push("workflow child reached its iteration limit before satisfying the task");for(let g of v)!s.includes(g)&&!w.includes(g)&&n.push(`required changed path was not present in workspace changes: ${g}`);let h=t.minFinalTextChars;return h!==void 0&&!u&&e.term.finalText.trim().length<h&&n.push(`finalText was shorter than the required ${h} characters`),t.rejectPreparatoryFinalText===!0&&!u&&Ne(e.term.finalText)&&n.push("finalText looks preparatory instead of terminal"),{ok:n.length===0,enforcement:p,reasons:n,changedPaths:s,mutationToolCalls:i,mutationEvidence:u}}a(Ce,"evaluateVerification");function ee(e,t){if(t.ok)return e;let o=[t.enforcement==="warn"?"[Workflow task completed without verification]":"[Workflow task verification failed]",...t.reasons.map(s=>`- ${s}`)].join(`
3
- `);return e.trim().length>0?`${e}
4
-
5
- ${o}`:o}a(ee,"appendVerificationFailure");function $e(){return{ok:!1,enforcement:"warn",reasons:["workflow child reached its iteration limit before satisfying the task"],mutationEvidence:!1}}a($e,"limitReachedWarningVerification");function Pt(e){return e.entry.bundle.readOnly!==!0&&e.entry.repairAttempts<Ie&&e.term.status==="completed"&&e.verification!==void 0&&e.verification.ok!==!0&&e.verification.enforcement!=="warn"}a(Pt,"shouldRepairVerificationFailure");function Ct(e){let t=e.verification.reasons.map(o=>`- ${o}`).join(`
6
- `),n=(e.verification.changedPaths??[]).length>0?`
7
- Workspace changes already present before this repair attempt:
8
- ${e.verification.changedPaths?.map(o=>`- ${o}`).join(`
9
- `)??""}`:"";return[e.originalPrompt,"","[Workflow verification repair]",`Repair attempt ${e.attempt}/${Ie}.`,"The previous attempt did not satisfy the workflow postconditions.","Do not stop at analysis, planning, or a promise to begin. Complete the required file writes in the real workspace now.","Use the available file editing tools when a file change is required, then report the exact files changed.","","Verification failures:",t,n,"","Previous terminal response:",e.previousFinalText.trim()||"(empty)"].join(`
10
- `)}a(Ct,"buildVerificationRepairPrompt");async function Oe(e,t,n,o,s=n){if(n===void 0)return e;let r;try{return await Promise.race([e,new Promise((i,c)=>{r=setTimeout(()=>{o.childAbortControllers?.get(t)?.abort(),c(new Error(`workflow task ${t} timed out after ${s??n}ms`))},n)})])}finally{r&&clearTimeout(r)}}a(Oe,"waitForChildPromise");function Fe(e,t,n){return t.outputSchema!==void 0&&Re(t.outputSchema),Ae(t.name,t.evidenceRefs,n),{id:e,fanoutClass:"evidence-scan",objective:t.prompt,readOnly:t.readOnly??!1,evidenceRefs:t.evidenceRefs?[...t.evidenceRefs]:[],constraints:[],...t.modelHint?{modelHint:t.modelHint}:{},...t.isolation?{isolation:t.isolation}:{},...t.subagentType?{specialistName:t.subagentType}:{},...t.outputSchema!==void 0?{outputSchema:t.outputSchema}:{},...t.effort?{effort:t.effort}:{}}}a(Fe,"buildBundle");function te(e,t){if(e.cancelledChildren.includes(t))return{status:"stopped",snapStatus:"aborted",finalText:""};let n=e.results[0],o=Wt(n?.summary??"",n?.digest);return n?.status==="completed"?{status:"completed",snapStatus:"completed",finalText:o,...n.digest?{digest:n.digest}:{},...n.digestFailed?{digestFailed:!0}:{},...n.digestPending?{digestPending:!0}:{},...n.limitReached?{limitReached:!0}:{},...n.provider?{provider:n.provider}:{},...n.model?{model:n.model}:{},...n.structured!==void 0?{structured:n.structured}:{}}:{status:"failed",snapStatus:"failed",finalText:o,...n?.limitReached?{limitReached:!0}:{},...n?.provider?{provider:n.provider}:{},...n?.model?{model:n.model}:{}}}a(te,"deriveTerminal");function De(e){let{ctx:t,childOptions:n}=e,o=e.runChild??Ee,s=e.queue??he(),r=e.listChangedFiles??bt,i=e.now??(()=>Date.now()),c=0,w=e.generateId??(()=>`wf-child-${c+=1}`),u=new Map,p=new Set,v=new Map,h=a(()=>e.onTaskSummary!==void 0||p.size>0,"hasTaskSummaryObservers"),g=a((f,m)=>{try{e.onTaskSummary?.(f,m)}catch{}for(let l of p)try{l(f,m)}catch{}},"notifyTaskSummary");return{spawn:a(async f=>{let m=w(),l=Fe(m,f,new Set(u.keys())),q=Rt(f).verification,P=Tt(),W=f.isolation!=="worktree",C=Y(q)?Z(t,r):Promise.resolve({paths:[]}),d=t.childProgressSnapshots,k=a(async $=>{let O=new AbortController;t.childAbortControllers?.set(m,O),d&&We(d,{childId:m,startedAt:i(),maxIterations:n.maxIterationsPerChild,parentRole:n.parentRole,readOnly:$.readOnly,specialistName:$.specialistName});let ht={...n,parentOptions:{...n.parentOptions,events:At(n.parentOptions.events,P)},maxParallel:1,workflowChild:!0,...e.runId!==void 0?{workflowCorrelation:{workflowRunId:e.runId,childAgentId:m,itemId:`agent:${m}`}}:{},childActivityName:f.name,workflowDigestMode:h()?"async":"blocking",...h()?{onWorkflowChildDigest:a(y=>{g(y.childId,{...y.digest?{summary:y.digest}:{},summaryKind:y.digest?"digest":"digest-failed",...y.totalTokensUsed>0?{usage:{totalTokens:y.totalTokensUsed}}:{}})},"onWorkflowChildDigest")}:{},abortSignal:O.signal,snapshotUpdater:d?y=>be(d,m,y):void 0},j;try{return await C,j=await o([$],t,ht),j}finally{if(t.childAbortControllers?.delete(m),d){let y=j?te(j,m):{snapStatus:"failed",finalText:""};X(d,m,{status:y.snapStatus,finalText:y.finalText,endedAt:i()})}}},"runBundle"),S=k(l);return u.set(m,{name:f.name,input:f,bundle:l,promise:S,runBundle:k,verification:q,changedPathBaseline:C,mutationRecorder:P,acceptToolMutationEvidence:W,repairAttempts:0}),G(v,m,S),{taskId:m,name:f.name}},"spawn"),wait:a(async(f,m)=>{let l=u.get(f);if(!l)throw new Error(`unknown workflow task: ${f}`);let M=xt(m),q=Date.now(),P=a(async S=>{if(M===void 0)return Oe(S,f,void 0,t);let $=Date.now()-q,O=M-$;if(O<=0)throw t.childAbortControllers?.get(f)?.abort(),new Error(`workflow task ${f} timed out after ${M}ms`);return Oe(S,f,Math.max(1,Math.floor(O)),t,M)},"waitForAttempt"),W=await P(l.promise),C=W.totalTokensUsed,d=te(W,f),k=l.verification?Ce({verification:l.verification,term:d,before:await l.changedPathBaseline,after:Y(l.verification)?await Z(t,r):{paths:[]},mutationRecorder:l.mutationRecorder,ctx:t,acceptToolMutationEvidence:l.acceptToolMutationEvidence}):void 0;for(d.limitReached===!0&&k===void 0&&d.status==="completed"&&(k=$e(),d={...d,status:"completed_unverified",snapStatus:"completed",finalText:ee(d.finalText,k)});Pt({entry:l,term:d,verification:k});){l.repairAttempts+=1;let S=Fe(f,{...l.input,prompt:Ct({originalPrompt:l.input.prompt,previousFinalText:d.finalText,verification:k,attempt:l.repairAttempts})});l.promise=l.runBundle(S),G(v,f,l.promise),W=await P(l.promise),C+=W.totalTokensUsed,d=te(W,f),k=l.verification?Ce({verification:l.verification,term:d,before:await l.changedPathBaseline,after:Y(l.verification)?await Z(t,r):{paths:[]},mutationRecorder:l.mutationRecorder,ctx:t,acceptToolMutationEvidence:l.acceptToolMutationEvidence}):void 0,d.limitReached===!0&&k===void 0&&d.status==="completed"&&(k=$e(),d={...d,status:"completed_unverified",snapStatus:"completed",finalText:ee(d.finalText,k)})}if(k!==void 0&&!k.ok&&d.status==="completed"){let S=k.enforcement==="warn";d={...d,status:S?"completed_unverified":"failed",snapStatus:S?"completed":"failed",finalText:ee(d.finalText,k)}}return X(t.childProgressSnapshots,f,{status:d.snapStatus,finalText:d.finalText,endedAt:i()}),{taskId:f,name:l.name,status:d.status,finalText:d.finalText,...d.digest?{digest:d.digest}:{},...d.digestFailed?{digestFailed:!0}:{},...d.digestPending?{digestPending:!0}:{},...k!==void 0?{verification:k}:{},...d.limitReached?{limitReached:!0}:{},...d.provider?{provider:d.provider}:{},...d.model?{model:d.model}:{},...d.structured!==void 0?{structured:d.structured}:{},usage:{totalTokens:C}}},"wait"),output:a(async f=>{if(!u.has(f))throw new Error(`unknown workflow task: ${f}`);let m=u.get(f)?.name??f,l=t.childProgressSnapshots?.get(f);if(!l)return{taskId:f,name:m,status:"running"};let M=l.status==="aborted"?"stopped":l.status;return l.finalText!==void 0?{taskId:f,name:m,status:M,lastText:l.finalText}:{taskId:f,name:m,status:M}},"output"),send:a(async(f,m)=>{if(!u.has(f))throw new Error(`unknown workflow task: ${f}`);ge({to:f,priority:"user",mode:"prompt",content:m,registry:v,queue:s})},"send"),stop:a(async f=>{if(!u.has(f))throw new Error(`unknown workflow task: ${f}`);t.childAbortControllers?.get(f)?.abort()},"stop"),subscribeTaskSummaryUpdates:a(f=>(p.add(f),()=>{p.delete(f)}),"subscribeTaskSummaryUpdates")}}a(De,"createCodingWorkflowBackend");import{homedir as en}from"node:os";import{join as Xe}from"node:path";var $t=["structure, entry points, and control flow","edge cases, error handling, and failure modes","tests, validation, and existing coverage"],Ot="Deduplicate overlapping findings, keep concrete evidence (file:line), rank by relevance to the question, and explicitly note gaps left by any failed investigation.";function Ft(e,t){return["Investigate the following question (READ-ONLY \u2014 do not modify any files):",e,"",`Focus your investigation on: ${t}`,"","Report concrete findings backed by evidence (cite file:line). If you find nothing relevant for this focus, say so briefly."].join(`
11
- `)}a(Ft,"buildInvestigatorPrompt");function It(e){let t=Math.max(1,(e.maxAgents??8)-1);return(e.targets&&e.targets.length>0?e.targets:$t).slice(0,t).map((o,s)=>({name:`investigate-${s+1}`,prompt:Ft(e.question,o)}))}a(It,"resolveAngles");async function Nt(e,t){try{let n=await e.runAgent({name:t.name,prompt:t.prompt,readOnly:!0});return n===null?{angle:t.name,status:"failed",text:"[investigation failed] agent did not complete"}:{angle:t.name,status:n.status==="completed"?"completed":"failed",text:n.finalText}}catch(n){let o=n instanceof Error?n.message:String(n);return{angle:t.name,status:"failed",text:`[investigation failed] ${o}`}}}a(Nt,"investigate");async function Dt(e,t){let n=It(t),o=(await e.phase("investigate",()=>e.parallel(n.map(i=>()=>Nt(e,i)),t.maxConcurrency!==void 0?{concurrency:t.maxConcurrency}:void 0))).filter(i=>i!==null),s=o.some(i=>i.status!=="completed");return{synthesis:(await e.phase("synthesize",()=>e.synthesize({inputs:o.map(i=>`### ${i.angle} (${i.status})
12
- ${i.text}`),rubric:t.rubric??Ot}))).text,findings:o,degraded:s}}a(Dt,"runParallelInvestigation");var _e={meta:{name:"parallel-investigation",description:"Fan out read-only investigators over a question (split by target areas), then synthesize ranked, evidence-keeping findings.",maxAgents:8,maxConcurrency:4,readOnly:!0,phases:["investigate","synthesize"]},run:Dt};function _t(e){return{meta:e.meta,run:a((t,n)=>e.run(t,n),"run")}}a(_t,"erase");var qe=[_t(_e)];function je(e){return qe.find(t=>t.meta.name===e)}a(je,"getBuiltinWorkflow");function Kn(){return qe.map(e=>e.meta)}a(Kn,"listBuiltinWorkflows");import{mkdir as Ke,readdir as qt,readFile as I,rename as jt,unlink as oe,writeFile as ae}from"node:fs/promises";import{basename as Bt,dirname as re,join as E}from"node:path";import{pathToFileURL as Lt}from"node:url";var Ge=[".workflow.json",".ts",".mjs",".js"],N="0.7.49";function ze(){return"0.7.58"}a(ze,"currentKodaxWorkflowVersion");function Ut(e){return e.endsWith(".workflow.json")?"capability-generated":"trusted-local"}a(Ut,"executionForPath");function Vt(e){let t=Ge.find(n=>e.endsWith(n));return t?e.slice(0,-t.length):void 0}a(Vt,"stripWorkflowSuffix");function se(e){let t=e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").slice(0,80);if(!t||t==="."||t==="..")throw new Error("workflow name must contain at least one safe filename character");return t}a(se,"safeWorkflowName");function ie(e){return typeof e=="object"&&e!==null}a(ie,"isRecord");function Be(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`workflow run.json missing ${t}`);return n}a(Be,"readRequiredString");async function Le(e,t){if(!e)return[];let n;try{n=await qt(e)}catch{return[]}let o=new Map;for(let s of Ge)for(let r of n){if(!r.endsWith(s))continue;let i=Vt(r);if(!i||i.length===0||o.has(i))continue;let c=E(e,r);o.set(i,{name:i,path:c,source:t,execution:Ut(c)})}return[...o.values()]}a(Le,"scanDir");async function D(e){let t=await Le(e.personal,"personal"),n=await Le(e.project,"project"),o=new Map;for(let s of t)o.set(s.name,s);for(let s of n)o.set(s.name,s);return[...o.values()].sort((s,r)=>s.name.localeCompare(r.name))}a(D,"discoverSavedWorkflows");function Kt(e){return typeof e=="object"&&e!==null&&"meta"in e&&"run"in e&&typeof e.run=="function"}a(Kt,"isWorkflowModule");function Gt(e){let t=e.default;if(Kt(t))return t;let n=typeof t=="function"?t:e.run,o=e.workflow??e.meta;if(typeof n=="function"&&typeof o=="object"&&o!==null&&"name"in o)return{meta:o,run:n};throw new Error("invalid workflow module: expected a `{ meta, run }` default export, or `export const workflow = {...}` + a default run function")}a(Gt,"normalizeWorkflowModule");function zt(e){let t=JSON.parse(e);if(!ie(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 s=J(t);return{manifest:s.manifest,source:s.source,capsule:s,legacy:!1}}let n=t.source;if(typeof n!="string"||n.trim().length===0)throw new Error("generated workflow file source must be a non-empty string");let o=F(t.manifest);return{manifest:o,source:n,capsule:b({minKodaxVersion:N,manifest:o,source:n}),legacy:!0}}a(zt,"parseGeneratedWorkflowFile");async function ce(e){let t=zt(await I(e,"utf8"));return t.capsule??b({minKodaxVersion:N,manifest:t.manifest,source:t.source})}a(ce,"loadSavedWorkflowCapsule");async function Je(e){if(e.endsWith(".workflow.json"))return H(await ce(e));let t=await import(Lt(e).href);return Gt(t)}a(Je,"loadSavedWorkflow");function fe(e){if(e.mayUseWorktree===!0)return{environment:["git-repo","worktree-capable"]}}a(fe,"deriveRequirements");function U(e,t){z(t,{filename:`${e.name}.workflow.js`,requireAsyncRun:!0})}a(U,"assertGeneratedCapsuleSource");async function Jt(e){let t=se(e.name),n=F(e.manifest);U(n,e.source);let o=e.requires??fe(n),s=b({minKodaxVersion:e.minKodaxVersion??N,manifest:n,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...o!==void 0?{requires:o}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}});await Ke(e.dir,{recursive:!0});let r=E(e.dir,`${t}.workflow.json`);return await ae(r,`${JSON.stringify(s,null,2)}
13
- `,"utf8"),{name:t,path:r,source:"project",execution:"capability-generated"}}a(Jt,"saveGeneratedWorkflow");async function Ue(e,t){await ae(e,`${JSON.stringify(t,null,2)}
14
- `,"utf8")}a(Ue,"writeCapsuleFile");async function Ht(e){try{return await I(e,"utf8"),!0}catch{return!1}}a(Ht,"fileExists");async function Zn(e){let t=(await D(e.dirs)).filter(c=>c.name===e.name).filter(c=>e.source===void 0||c.source===e.source);if(t.length===0)throw new Error(`saved workflow not found: ${e.name}`);if(t.length>1)throw new Error(`ambiguous saved workflow name: ${e.name}`);let n=t[0];if(!n.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be renamed");let o=se(e.newName),s=E(re(n.path),`${o}.workflow.json`);if(s!==n.path&&await Ht(s))throw new Error(`saved workflow already exists: ${o}`);let r=await ce(n.path);U(r.manifest,r.source);let i=b({minKodaxVersion:r.minKodaxVersion,manifest:{...r.manifest,name:o},source:r.source,...r.intent!==void 0?{intent:r.intent}:{},...r.inputs!==void 0?{inputs:r.inputs}:{},...r.requires!==void 0?{requires:r.requires}:{},...r.provenance!==void 0?{provenance:r.provenance}:{}});return await ae(s,`${JSON.stringify(i,null,2)}
15
- `,"utf8"),s!==n.path&&await oe(n.path),{name:o,path:s,source:n.source,execution:"capability-generated"}}a(Zn,"renameSavedWorkflow");async function Qn(e){let t=(await D(e.dirs)).filter(o=>o.name===e.name).filter(o=>e.source===void 0||o.source===e.source);if(t.length===0)throw new Error(`saved workflow not found: ${e.name}`);if(t.length>1)throw new Error(`ambiguous saved workflow name: ${e.name}`);let n=t[0];if(!n.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be deleted");return await oe(n.path),n}a(Qn,"deleteSavedWorkflow");async function er(e){let t=se(e.name),n=(await D(e.dirs)).filter(g=>g.name===t).filter(g=>e.savedSource===void 0||g.source===e.savedSource);if(n.length===0)throw new Error(`saved workflow not found: ${t}`);if(n.length>1)throw new Error(`ambiguous saved workflow name: ${t}`);let o=n[0];if(!o.path.endsWith(".workflow.json"))throw new Error("only generated workflow capsules can be replaced");let s=F({...e.manifest,name:t});U(s,e.source);let r=e.requires??fe(s),i=b({minKodaxVersion:e.minKodaxVersion??N,manifest:s,source:e.source,...e.intent!==void 0?{intent:e.intent}:{},...e.inputs!==void 0?{inputs:e.inputs}:{},...r!==void 0?{requires:r}:{},...e.provenance!==void 0?{provenance:e.provenance}:{}}),c=await ce(o.path),w=new Date().toISOString().replace(/[:.]/g,"-"),u=E(re(o.path),".revisions",t),p=`${w}-${process.hrtime.bigint().toString(36)}`,v=E(u,`${t}-${p}.workflow.json`),h=E(re(o.path),`.${t}.${process.pid}.${Date.now().toString(36)}.tmp`);await Ke(u,{recursive:!0}),await Ue(v,c);try{await Ue(h,i),await jt(h,o.path)}catch(g){try{await oe(h)}catch{}throw g}return{name:t,path:o.path,source:o.source,execution:"capability-generated",previousPath:v}}a(er,"replaceSavedWorkflow");function Xt(e){if(!ie(e))return;let t=e.request;if(typeof t=="string"&&t.trim().length>0)return t;let n=e.question;if(typeof n=="string"&&n.trim().length>0)return n}a(Xt,"readOptionalOriginalRequest");function He(e){return Yt(e)}a(He,"buildCapsuleFromRun");async function Yt(e){let t=JSON.parse(await I(E(e.runDir,"run.json"),"utf8"));if(!ie(t))throw new Error("workflow run.json must be an object");let n=Be(t,"scriptSnapshotPath"),o=Be(t,"manifestSnapshotPath"),s=await I(n,"utf8"),r=F(JSON.parse(await I(o,"utf8")));U(r,s);let i=typeof t.runId=="string"&&t.runId.length>0?t.runId:Bt(e.runDir),c=Xt(t.args),w=fe(r),u=ve(r,c!==void 0?{originalRequest:c}:{}),p={description:"Provide new workflow args matching the generated request shape.",..."args"in t?{examples:[t.args]}:{}};return b({minKodaxVersion:N,manifest:r,source:s,intent:u,inputs:p,...w!==void 0?{requires:w}:{},provenance:{fromRunId:i,createdAt:new Date().toISOString(),kodaxVersion:ze()}})}a(Yt,"readCapsuleFromRun");async function tr(e){let t=await He(e);return{capsule:t,module:H(t)}}a(tr,"loadGeneratedWorkflowFromRun");async function nr(e){let t=await He(e);return Jt({dir:e.targetDir,name:e.name,manifest:t.manifest,source:t.source,...t.intent!==void 0?{intent:t.intent}:{},...t.inputs!==void 0?{inputs:t.inputs}:{},...t.requires!==void 0?{requires:t.requires}:{},...t.provenance!==void 0?{provenance:t.provenance}:{},minKodaxVersion:t.minKodaxVersion})}a(nr,"saveGeneratedWorkflowFromRun");function R(e,t,n,o){e.push({severity:t,requirement:n,message:o})}a(R,"addRequirementIssue");function Ve(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e.trim());if(t)return[Number(t[1]),Number(t[2]),Number(t[3])]}a(Ve,"parseSemver");function Zt(e,t){for(let n=0;n<3;n+=1){let o=e[n]-t[n];if(o!==0)return o}return 0}a(Zt,"compareSemver");function Qt(e,t,n){let o=Ve(t),s=Ve(n);if(!o){R(e,"error","kodax:min-version",`workflow minKodaxVersion is not valid semver: ${t}`);return}if(!s){R(e,"warning","kodax:min-version",`cannot verify workflow minKodaxVersion ${t}; current version is unknown`);return}Zt(s,o)<0&&R(e,"error","kodax:min-version",`workflow requires KodaX >= ${t}, current version is ${n}`)}a(Qt,"addMinVersionIssue");function ne(e,t,n,o){if(!n)return;if(!o){for(let r of n)R(e,"warning",`${t}:${r}`,`workflow requires ${t}:${r}, but no ${t} inventory was provided`);return}let s=new Set(o);for(let r of n)s.has(r)||R(e,"error",`${t}:${r}`,`missing required workflow ${t}: ${r}`)}a(ne,"addMissingItems");function rr(e,t={}){let n=J(e),o=[],s=n.requires;Qt(o,n.minKodaxVersion,t.kodaxVersion??ze()),s?.environment?.includes("git-repo")&&t.isGitRepo===!1&&R(o,"error","environment:git-repo","workflow requires a git repository"),s?.environment?.includes("worktree-capable")&&t.worktreeCapable===!1&&R(o,"error","environment:worktree-capable","workflow may request git worktree isolation");try{z(n.source,{filename:`${n.manifest.name}.workflow.js`,requireAsyncRun:!0})}catch(r){let i=r instanceof Error?r.message:String(r);R(o,"error","workflow:source",i)}return ne(o,"tools",s?.tools,t.availableTools),ne(o,"mcp",s?.mcp,t.availableMcp),ne(o,"skills",s?.skills,t.availableSkills),{ok:!o.some(r=>r.severity==="error"),issues:o}}a(rr,"preflightWorkflowCapsule");function tn(e){return{project:Xe(e,".kodax","workflows"),personal:Xe(en(),".kodax","workflows")}}a(tn,"defaultSavedWorkflowDirs");async function nn(e,t){let o=(await D(t)).find(s=>s.name===e);if(o)return Je(o.path)}a(nn,"resolveSavedByName");function Ye(e){let t=tn(e);return async n=>je(n)??await nn(n,t)}a(Ye,"createNestedWorkflowResolver");import{existsSync as rn,mkdirSync as on,readFileSync as an,writeFileSync as Ze}from"node:fs";import{join as _}from"node:path";var Qe="results";function et(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}a(et,"safeKey");function tt(e,t){let n=_(e,t);if(rn(n))try{return JSON.parse(an(n,"utf8"))}catch{return}}a(tt,"readResult");function nt(e,t={}){let n=_(e,Qe);on(n,{recursive:!0});let o=t.readFrom?_(t.readFrom,Qe):void 0;return{get:a(s=>{let r=`${et(s)}.json`,i=tt(n,r);if(i!==void 0)return i;if(o===void 0)return;let c=tt(o,r);if(c!==void 0){try{Ze(_(n,r),JSON.stringify(c),"utf8")}catch{}return c}},"get"),set:a((s,r)=>{try{Ze(_(n,`${et(s)}.json`),JSON.stringify(r),"utf8")}catch{}},"set")}}a(nt,"createFsResultCache");import{mkdirSync as sn,appendFileSync as cn,writeFileSync as V}from"node:fs";import{join as A}from"node:path";function fn(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,120);return t.length>0?t:"artifact"}a(fn,"safeWorkflowArtifactName");function rt(e,t={}){let n=t.now??(()=>Date.now()),o=A(e,"artifacts");sn(o,{recursive:!0});let s=A(e,"events.jsonl");return{runDir:e,onEvent:a(r=>{cn(s,`${JSON.stringify({...r,ts:n()})}
16
- `,"utf8")},"onEvent"),writeArtifact:a((r,i)=>{let c=A(o,`${fn(r)}.json`);return V(c,JSON.stringify(i,null,2),"utf8"),{name:r,path:c}},"writeArtifact"),writeScriptSnapshot:a(r=>{let i=A(e,"script.js");if(V(i,r.source,"utf8"),!r.manifest)return{scriptPath:i};let c=A(e,"manifest.json");return V(c,`${JSON.stringify(r.manifest,null,2)}
17
- `,"utf8"),{scriptPath:i,manifestPath:c}},"writeScriptSnapshot"),writeRunJson:a(r=>{let i=ke(r.processMetadata?.hostMetadata),c={runId:r.state.runId,workflow:r.meta.name,status:r.state.status,totalSpawned:r.state.totalSpawned,artifacts:r.state.artifacts.map(w=>w.name),eventCount:r.state.events.length,startedAt:r.startedAt,endedAt:r.endedAt,args:r.args,...r.resultSummary!==void 0?{resultSummary:r.resultSummary}:{},...r.processMetadata?.displayName!==void 0?{displayName:r.processMetadata.displayName}:{},...r.processMetadata?.goal!==void 0?{goal:r.processMetadata.goal}:{},...r.processMetadata?.source!==void 0?{source:r.processMetadata.source}:{},...r.processMetadata?.savedWorkflowName!==void 0?{savedWorkflowName:r.processMetadata.savedWorkflowName}:{},...r.processMetadata?.sourceRunId!==void 0?{sourceRunId:r.processMetadata.sourceRunId}:{},...r.processMetadata?.sourceWorkflowName!==void 0?{sourceWorkflowName:r.processMetadata.sourceWorkflowName}:{},...r.processMetadata?.revisionOf!==void 0?{revisionOf:r.processMetadata.revisionOf}:{},...i!==void 0?{hostMetadata:i}:{},...r.scriptSnapshot?{scriptSnapshotPath:r.scriptSnapshot.scriptPath,...r.scriptSnapshot.manifestPath?{manifestSnapshotPath:r.scriptSnapshot.manifestPath}:{}}:{}};V(A(e,"run.json"),`${JSON.stringify(c,null,2)}
18
- `,"utf8")},"writeRunJson")}}a(rt,"createRunGraphWriter");import{execFile as dn}from"node:child_process";import{promisify as ln}from"node:util";import{statSync as un}from"node:fs";import{join as mn}from"node:path";var wn=ln(dn);function le(e){return mn(e,"worktrees")}a(le,"workflowWorktreeBaseDir");var pn=360*60*1e3;function at(e,t){return wn("git",[...e],{cwd:t}).then(n=>n.stdout)}a(at,"defaultRunGit");function hn(e){return un(e).mtimeMs}a(hn,"defaultMtimeMs");function gn(e){let t=[],n,o,s=a(()=>{n&&t.push(o?{path:n,branch:o}:{path:n}),n=void 0,o=void 0},"flush");for(let r of e.split(/\r?\n/))r.startsWith("worktree ")?(s(),n=r.slice(9).trim()):r.startsWith("branch ")&&(o=r.slice(7).trim().replace(/^refs\/heads\//,""));return s(),t}a(gn,"parseWorktreeList");function ot(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}a(ot,"normalize");function st(e,t){let n=ot(e),o=ot(t);return n===o||n.startsWith(`${o}/`)}a(st,"isUnder");async function kn(e,t,n){try{let s=(await t(["status","--porcelain"],e.path)).split(/\r?\n/).filter(c=>c.trim().length>0).length,r=await t(["rev-list","--count","HEAD","--not","--remotes"],e.path),i=Number.parseInt(r.trim(),10)||0;return s>0||i>0}catch(o){return n.push(`retain ${e.path}: cannot verify worktree cleanliness: ${o instanceof Error?o.message:String(o)}`),!0}}a(kn,"worktreeHasChanges");async function it(e,t,n,o,s){if(await kn(e,n,s)){s.push(`retain ${e.path}: worktree has unmerged changes`);return}try{await n(["worktree","remove",e.path,"--force"],t),o.push(e.path)}catch(r){s.push(`remove ${e.path}: ${r instanceof Error?r.message:String(r)}`);return}if(e.branch)try{await n(["branch","-D",e.branch],t)}catch{}}a(it,"removeWorktree");async function ct(e,t,n){try{let o=await t(["worktree","list","--porcelain"],e);return gn(o)}catch(o){n.push(`list worktrees: ${o instanceof Error?o.message:String(o)}`);return}}a(ct,"listWorktrees");async function de(e,t,n){try{await t(["worktree","prune"],e)}catch(o){n.push(`prune: ${o instanceof Error?o.message:String(o)}`)}}a(de,"prune");async function ft(e,t={}){let n=[],o=[];if(!e.gitRoot)return{removed:o,warnings:n};let s=t.runGit??at,r=await ct(e.gitRoot,s,n);if(!r)return{removed:o,warnings:n};for(let i of r)st(i.path,e.baseDir)&&await it(i,e.gitRoot,s,o,n);return o.length>0&&await de(e.gitRoot,s,n),{removed:o,warnings:n}}a(ft,"sweepWorkflowRunWorktrees");async function dt(e,t={}){let n=[],o=[];if(!e.gitRoot)return{removed:o,warnings:n};let s=t.runGit??at,r=t.mtimeMs??hn,i=t.now??(()=>Date.now()),c=e.maxAgeMs??pn;await de(e.gitRoot,s,n);let w=await ct(e.gitRoot,s,n);if(!w)return{removed:o,warnings:n};for(let u of w){if(!st(u.path,e.workflowRunsRoot))continue;let p;try{p=i()-r(u.path)}catch{continue}p>=c&&await it(u,e.gitRoot,s,o,n)}return o.length>0&&await de(e.gitRoot,s,n),{removed:o,warnings:n}}a(dt,"pruneStaleWorkflowWorktrees");var vn=200,lt={maxAgents:64,tokenBudget:2e5};function Sn(e,t){let n=e.meta,o=K(n,t);return{name:n.name,description:n.description,phases:n.phases??[],...n.plannedAgents!==void 0?{plannedAgents:n.plannedAgents}:{},maxAgents:o.maxAgents??null,maxConcurrency:o.maxConcurrency??null,tokenBudget:o.tokenBudget??null,writesFiles:n.readOnly!==!0}}a(Sn,"buildApprovalSummary");function ue(e,t){if(e!==void 0)return!Number.isInteger(e)||e<=0?1:Math.min(e,t)}a(ue,"clampLimit");function ut(e,t,n){let o=ue(e,n),s=ue(t,n);return o===void 0?s:s===void 0?o:Math.min(o,s)}a(ut,"clampEffectiveLimit");function K(e,t){let n=ut(e.maxAgents,t?.maxAgents,lt.maxAgents),o=pe(),s=[e.maxConcurrency,t?.maxConcurrency].map(c=>ue(c,o)).filter(c=>c!==void 0),r=s.length===0?o:Math.min(o,...s),i=ut(e.tokenBudget,t?.tokenBudget,lt.tokenBudget);return{...n!==void 0?{maxAgents:n}:{},...r!==void 0?{maxConcurrency:r}:{},...i!==void 0?{tokenBudget:i}:{}}}a(K,"clampWorkflowLimits");function mt(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 o=n.text;if(typeof o=="string"&&o.trim().length>0)return o}for(let o of["summary","report","text","result"]){let s=t[o];if(typeof s=="string"&&s.trim().length>0)return s}}a(mt,"workflowResultSummary");async function me(e){let t=K(e.module.meta,e.hostPolicy),n=Sn(e.module,e.hostPolicy);if(e.approval&&!await e.approval(n))return{kind:"denied",summary:n};let o=e.now??(()=>Date.now()),s=e.ctx?.executionCwd??e.ctx?.gitRoot;await dt({workflowRunsRoot:yn(e.runDir),gitRoot:s},{now:o,...e.worktreeSweepDeps});let r=rt(e.runDir,{now:o}),i=e.onWorkflowProcessEvent?ye({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:a(()=>new Date(o()).toISOString(),"now")}):void 0,c=e.scriptSnapshot?r.writeScriptSnapshot(e.scriptSnapshot):void 0,w=e.backend??xn(e),p={...e.beforeSpawn?Mn(w,e.beforeSpawn):w,writeArtifact:a(async(x,we)=>r.writeArtifact(x,we),"writeArtifact")},v=o(),h;try{h=await Se({runId:e.runId,args:e.args,backend:p,limits:t,...e.signal?{signal:e.signal}:{},summarizeResult:mt,resolveWorkflowModule:Ye(s??process.cwd()),resultCache:nt(e.runDir,e.resumeFromRunDir?{readFrom:e.resumeFromRunDir}:{}),onEvent:a(x=>{r.onEvent(x),i&&e.onWorkflowProcessEvent?.(i.applyEvent(x)),e.onEvent?.(x)},"onEvent")},x=>e.module.run(x,e.args))}finally{await ft({baseDir:le(e.runDir),gitRoot:s},{now:o,...e.worktreeSweepDeps})}let g=h.ok?mt(h.result):void 0;return r.writeRunJson({meta:e.module.meta,args:e.args,state:h.state,startedAt:v,endedAt:o(),...c?{scriptSnapshot:c}:{},...g!==void 0?{resultSummary:g}:{},...e.processMetadata!==void 0?{processMetadata:e.processMetadata}:{}}),h.ok?{kind:"completed",result:h.result,state:h.state}:{kind:"failed",error:h.error,state:h.state}}a(me,"runWorkflowModule");function xn(e){if(!e.ctx||!e.childOptions)throw new Error("runWorkflowModule requires either a backend or ctx + childOptions");return De({ctx:e.ctx,childOptions:e.childOptions,runId:e.runId})}a(xn,"buildBackend");function Mn(e,t){return{...e,spawn:a(async n=>(await t(),e.spawn(n)),"spawn")}}a(Mn,"withBeforeSpawn");function Rn(e,t,n){let o=e?.onWorkflowAgentDigest;o&&(n.type==="agent_completed"||n.type==="agent_unverified"||n.type==="agent_failed"||n.type==="agent_summary_updated")&&o({runId:t,event:n})}a(Rn,"emitWorkflowAgentDigest");async function wt(e){let t={...Te({options:e.options,runtime:e.options.extensionRuntime,managedProtocolPayloadRef:{current:void 0}}),workflowWorktreeBaseDir:le(e.runDir)},n={maxIterationsPerChild:vn,parentRole:"worker",parentHarness:"tool-dispatch",parentOptions:{provider:e.options.provider,model:e.options.modelOverride??e.options.model,effort:e.options.effort,reasoningMode:e.options.reasoningMode,repoIntelligenceMode:e.options.context?.repoIntelligenceMode,repoIntelligenceTrace:e.options.context?.repoIntelligenceTrace,extensionRuntime:e.options.extensionRuntime,events:e.options.events},...e.options.guardrails?{guardrails:e.options.guardrails}:{},...t.planModeBlockCheck?{planModeBlockCheck:t.planModeBlockCheck}:{}},o=e.onWorkflowProcessEvent||e.options.events?.onWorkflowProcessEvent?r=>{e.onWorkflowProcessEvent?.(r),e.options.events?.onWorkflowProcessEvent?.(r)}:void 0,s=e.onEvent||e.options.events?.onWorkflowAgentDigest?r=>{e.onEvent?.(r),Rn(e.options.events,e.runId,r)}:void 0;return me({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}:{},...s?{onEvent:s}:{},...o?{onWorkflowProcessEvent:o}:{},...e.options.workflowHostPolicy?{hostPolicy:e.options.workflowHostPolicy}:{},...e.now?{now:e.now}:{},...e.scriptSnapshot?{scriptSnapshot:e.scriptSnapshot}:{},...e.resumeFromRunDir?{resumeFromRunDir:e.resumeFromRunDir}:{},...e.processMetadata?{processMetadata:e.processMetadata}:{},...e.beforeSpawn?{beforeSpawn:e.beforeSpawn}:{}})}a(wt,"runWorkflowFromOptions");function Wn(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 o=n.text;if(typeof o=="string"&&o.trim().length>0)return o}for(let o of["summary","report","text","result"]){let s=t[o];if(typeof s=="string"&&s.trim().length>0)return s}}a(Wn,"resultText");function bn(e){if(e.kind==="completed"){let t=Wn(e.result);return t!==void 0?{status:"completed",resultText:t}:{status:"completed"}}return e.kind==="denied"?{status:"denied"}:{status:"failed",error:e.error}}a(bn,"classifyOutcome");function Tn(e,t){return{kind:"failed",error:t instanceof Error?t:new Error(String(t)),state:{runId:e,status:"failed",totalSpawned:0,events:[],artifacts:[]}}}a(Tn,"failedOutcome");var En=1e3;function An(e={},t=xe(e)){let n=new Map,o=a(r=>r?{...r,runDir:n.get(r.runId)??""}:void 0,"withRunDir"),s=a((r,i)=>{if(n.set(r.runId,r.runDir),n.size>En){let u=new Set(t.list().map(p=>p.runId));for(let p of n.keys())p!==r.runId&&!u.has(p)&&n.delete(p)}let c=K(r.meta,r.hostPolicy),w=t.start({runId:r.runId,workflow:r.meta.name,...r.meta.phases!==void 0?{phases:r.meta.phases}:{},...c.maxAgents!==void 0?{maxAgents:c.maxAgents}:{},...r.meta.plannedAgents!==void 0?{plannedAgents:r.meta.plannedAgents}:{},...c.tokenBudget!==void 0?{tokenBudget:c.tokenBudget}:{},...r.processMetadata!==void 0?{processMetadata:r.processMetadata}:{},...r.signal?{signal:r.signal}:{},runFn:i,classify:bn,onError:a(u=>Tn(r.runId,u),"onError")});return{runId:w.runId,done:w.done,getSnapshot:a(()=>o(w.getSnapshot()),"getSnapshot"),getProcessSnapshot:a(()=>w.getProcessSnapshot(),"getProcessSnapshot")}},"startManaged");return{start:a(r=>s({runId:r.runId,runDir:r.runDir,meta:r.module.meta,hostPolicy:r.hostPolicy,processMetadata:r.processMetadata,signal:r.signal},i=>me({...r,signal:i.signal,beforeSpawn:i.beforeSpawn,onEvent:a(c=>{i.onEvent(c),r.onEvent?.(c)},"onEvent")})),"start"),startFromOptions:a(r=>s({runId:r.runId,runDir:r.runDir,meta:r.module.meta,hostPolicy:r.options.workflowHostPolicy,processMetadata:r.processMetadata,signal:r.signal},i=>wt({...r,signal:i.signal,beforeSpawn:i.beforeSpawn,onEvent:a(c=>{i.onEvent(c),r.onEvent?.(c)},"onEvent")})),"startFromOptions"),list:a(()=>t.list().map(r=>({...r,runDir:n.get(r.runId)??""})),"list"),get:a(r=>o(t.get(r)),"get"),subscribeWorkflowProcess:a(r=>t.subscribeWorkflowProcess(r),"subscribeWorkflowProcess"),getWorkflowProcessSnapshot:a(r=>t.getWorkflowProcessSnapshot(r),"getWorkflowProcessSnapshot"),listWorkflowProcessSnapshots:a(r=>t.listWorkflowProcessSnapshots(r),"listWorkflowProcessSnapshots"),pause:a(r=>t.pause(r),"pause"),resume:a(r=>t.resume(r),"resume"),stop:a((r,i)=>t.stop(r,i),"stop")}}a(An,"createWorkflowRunManager");var pt;function jr(){return pt??=An({},Me()),pt}a(jr,"getDefaultWorkflowRunManager");export{De as a,_e as b,qe as c,je as d,Kn as e,D as f,Gt as g,ce as h,Je as i,Jt as j,Zn as k,Qn as l,er as m,tr as n,nr as o,rr as p,fn as q,rt as r,lt as s,Sn as t,K as u,me as v,Rn as w,wt as x,An as y,jr as z};
@@ -1,2 +0,0 @@
1
- // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{a}from"./chunk-6AU6EPO6.js";import"./chunk-ZZDC75H4.js";import"./chunk-P4VF3JEP.js";import"./chunk-V4WSBIXB.js";export{a as loadCompactionConfig};
@@ -1,2 +0,0 @@
1
- // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{$ as hh,A as Ig,Aa as Ih,B as Jg,Ba as Jh,C as Kg,Ca as Kh,D as Lg,Da as Lh,E as Mg,Ea as Mh,F as Ng,Fa as Nh,G as Og,H as Pg,I as Qg,J as Rg,K as Sg,L as Tg,M as Ug,N as Vg,O as Wg,P as Xg,Q as Yg,R as Zg,S as _g,T as $g,U as ah,V as bh,W as ch,X as dh,Y as eh,Z as fh,_ as gh,a as _,aa as ih,b as $,ba as jh,c as aa,ca as kh,d as lg,da as lh,e as mg,ea as mh,f as ng,fa as nh,g as og,ga as oh,h as pg,ha as ph,i as qg,ia as qh,j as rg,ja as rh,k as sg,ka as sh,l as tg,la as th,m as ug,ma as uh,n as vg,na as vh,o as wg,oa as wh,p as xg,pa as xh,q as yg,qa as yh,r as zg,ra as zh,s as Ag,sa as Ah,t as Bg,ta as Bh,u as Cg,ua as Ch,v as Dg,va as Dh,w as Eg,wa as Eh,x as Fg,xa as Fh,y as Gg,ya as Gh,z as Hg,za as Hh}from"./chunk-NKHXRN7G.js";import{a as Ld,b as Md,c as Nd,d as Od,e as Pd,f as Qd,g as Rd,h as Sd,i as Td,j as se}from"./chunk-73Z7BK5H.js";import{a as Ud,b as Vd,c as Wd,d as Xd,e as Yd,f as Zd,g as _d,h as $d,i as ae,j as be,k as ce,l as de,m as ee,n as fe,o as ge,p as he,q as ie,r as je,s as ke,t as le,u as me,v as ne,w as oe,x as pe,y as qe,z as re}from"./chunk-PIQWODWN.js";import{A as yd,E as zd,F as Ad,G as Bd,H as Cd,K as Dd,M as te,N as ue,O as ve,P as we,Q as xe,R as ye,S as ze,T as Ae,V as Be,W as Ce,X as De,a as xa,b as ya,e as jd,ea as Ef,f as kd,fa as Ff,g as ld,h as md,i as nd,j as od,k as pd,la as Gf,ma as Hf,oa as If,p as qd,q as rd,t as sd,u as td,w as ud,x as vd,y as wd,z as xd}from"./chunk-CQ6EQG7E.js";import"./chunk-D6QVXQNI.js";import{a as Kd}from"./chunk-526OILYL.js";import{$b as ef,$c as Xf,A as bc,Aa as Zc,Ab as Fe,B as cc,Ba as _c,Bb as Ge,C as dc,Ca as $c,Cb as He,D as ec,Db as Ie,E as fc,Eb as Je,F as gc,Fb as Ke,G as hc,Ga as ad,Gb as Le,H as ic,Ha as bd,Hb as Me,I as jc,Ia as cd,Ib as Ne,Ic as Jf,J as kc,Ja as dd,Jb as Oe,Jc as Kf,Ka as ed,Kb as Pe,Kc as Lf,L as lc,La as fd,Lb as Qe,Lc as Mf,M as mc,Ma as gd,Mb as Re,Mc as Nf,N as nc,Nb as Se,Nc as Of,O as oc,Oa as hd,Ob as Te,Oc as Pf,P as pc,Pa as id,Pb as Ue,Pc as Qf,Q as qc,Qb as Ve,Qc as Rf,R as rc,Rb as We,Rc as Sf,S as sc,Sb as Xe,Sc as Tf,T as tc,Tb as Ye,U as uc,Ub as Ze,V as vc,Vb as _e,W as wc,Wb as $e,X as xc,Xb as af,Y as yc,Yb as bf,Yc as Uf,Z as zc,Zb as cf,Zc as Vf,_ as Ac,_b as df,_c as Wf,ac as ff,ad as Yf,ba as Bc,bc as gf,bd as Zf,ca as Cc,cc as hf,cd as _f,d as Kb,da as Dc,dc as jf,dd as $f,e as Lb,ea as Ec,ec as kf,ed as ag,fa as Fc,fc as lf,fd as bg,ga as Gc,gc as mf,gd as cg,ha as Hc,hc as nf,hd as dg,i as Mb,ic as of,id as eg,j as Nb,ja as Ic,jc as pf,jd as fg,k as Ob,ka as Jc,kc as qf,kd as gg,l as Pb,la as Kc,lc as rf,ld as hg,m as Qb,ma as Lc,mc as sf,md as ig,n as Rb,na as Mc,nc as tf,nd as jg,o as Sb,oa as Nc,oc as uf,p as Tb,pa as Oc,pb as Ed,pc as vf,q as Ub,qa as Pc,qb as Fd,qc as wf,r as Vb,ra as Qc,rb as Gd,rc as xf,rd as kg,s as Wb,sa as Rc,sb as Hd,sc as yf,t as Xb,ta as Sc,tb as Id,tc as zf,u as Yb,ua as Tc,ub as Jd,uc as Af,v as Zb,va as Uc,vc as Bf,w as _b,wa as Vc,wc as Cf,x as $b,xa as Wc,xc as Df,y as ac,ya as Xc,za as Yc,zb as Ee}from"./chunk-7QB55SYG.js";import{$ as o,A as i,Aa as L,B as j,Ba as M,C as k,Ca as N,D as l,Da as O,E as m,Ea as P,Fa as Q,Ga as R,Ha as S,Ia as T,Ja as U,Ka as V,La as W,Ma as X,Na as Y,Oa as Z,R as n,a,aa as p,b,c,fa as q,ga as r,ha as s,ia as t,j as d,ja as u,k as e,ka as v,la as w,ma as x,na as y,oa as z,pa as A,qa as B,ra as C,s as f,sa as D,t as g,ta as E,ua as F,va as G,wa as H,xa as I,ya as J,z as h,za as K}from"./chunk-HS2K74I4.js";import{$b as Xa,$c as tb,Bd as Ib,Cd as Jb,Yc as qb,Zc as rb,_b as Wa,_c as sb,a as za,ac as Ya,ad as ub,b as Aa,bc as Za,c as Ba,cc as _a,d as Ca,dc as $a,e as Da,ec as ab,f as Ea,fc as bb,gc as cb,h as Fa,hc as db,hd as vb,i as Ga,ic as eb,id as wb,j as Ha,jc as fb,jd as xb,k as Ia,ka as Oa,kc as gb,kd as yb,l as Ja,lc as hb,ld as zb,m as Ka,mb as Ua,mc as ib,md as Ab,n as La,na as Pa,nb as Va,nc as jb,nd as Bb,o as Ma,oc as kb,p as Na,pc as lb,pd as Cb,qc as mb,qd as Db,rc as nb,rd as Eb,sc as ob,sd as Fb,tc as pb,td as Gb,ua as Qa,ud as Hb,va as Ra,wa as Sa,xa as Ta}from"./chunk-ZZDC75H4.js";import{H as wa,a as ba,b as ca,c as da,d as ea,e as fa,f as ga,g as ha,h as ia,i as ja,j as ka,k as la,l as ma,m as na,n as oa,o as pa,p as qa,v as ra,w as sa,x as ta,y as ua,z as va}from"./chunk-P4VF3JEP.js";import"./chunk-V4WSBIXB.js";export{hh as AUTO_MODE_DENIAL_CONSECUTIVE_THRESHOLD,ih as AUTO_MODE_DENIAL_CUMULATIVE_THRESHOLD,Ch as BASH_POLICY_SPEC,yg as BLOCKER_REQUIRED_CONSECUTIVE_TURNS,nh as BREAKER_ERROR_THRESHOLD,oh as BREAKER_WINDOW_MS,Wd as BUILTIN_WORKFLOWS,Lb as CANCELLED_TOOL_RESULT_MESSAGE,Kb as CANCELLED_TOOL_RESULT_PREFIX,Zg as CODING_AGENT_MARKER,rg as CODING_INVARIANTS,Ef as CODING_SUMMARY_PROMPT,Ff as CODING_UPDATE_SUMMARY_PROMPT,Qe as CapabilityDeniedError,tg as Client,zf as CombinedExtensionRuntime,Re as ConstructionManifestError,Gf as DEFAULT_CODING_AGENT_NAME,Og as DEFAULT_DANGEROUS_PATTERNS,Oe as DEFAULT_HANDLER_TIMEOUT_MS,jd as DEFAULT_RESILIENCE_CONFIG,Ng as DEFAULT_SAFE_PATTERNS,$e as DEFAULT_SELF_MODIFY_BUDGET,yh as DEFAULT_SPECULATIVE_WINDOW_MS,Nb as DEFAULT_TOOL_OUTPUT_MAX_BYTES,Mb as DEFAULT_TOOL_OUTPUT_MAX_LINES,Md as DEFAULT_WORKFLOW_GENERATION_TIMEOUT_MS,Na as DefaultSummaryCompaction,Wg as EMIT_VERDICT_TOOL_NAME,xa as ErrorCategory,cd as GENERATOR_AGENT_NAME,ca as ImageResizeError,Ga as KODAX_API_MIN_INTERVAL,s as KODAX_DEFAULT_PROVIDER,Aa as KODAX_DEFAULT_TIMEOUT,ta as KODAX_FILE_MEDIA_TYPES,Ba as KODAX_HARD_TIMEOUT,ra as KODAX_IMAGE_MEDIA_TYPES,Ea as KODAX_MAX_INCOMPLETE_RETRIES,Ca as KODAX_MAX_RETRIES,za as KODAX_MAX_TOKENS,r as KODAX_PROVIDERS,q as KODAX_PROVIDER_SNAPSHOTS,f as KODAX_REASONING_MODE_SEQUENCE,Da as KODAX_RETRY_BASE_DELAY,g as KODAX_STABLE_EFFORT_INTENTS,Fa as KODAX_STAGGER_DELAY,Uf as KODAX_TOOLS,Yb as KODAX_UNDERLYING_CAPABILITY_TOPICS,sa as KODAX_VIDEO_MEDIA_TYPES,o as KodaXAnthropicCompatProvider,n as KodaXBaseProvider,tg as KodaXClient,a as KodaXError,yf as KodaXExtensionRuntime,ba as KodaXMediaError,p as KodaXOpenAICompatProvider,b as KodaXProviderError,c as KodaXRateLimitError,$ as KodaXSessionError,aa as KodaXTerminalError,_ as KodaXToolError,qb as LINEAGE_ENTRY_TYPES,Gd as LSP_SERVERS,sb as LineageCompaction,rb as LineageExtension,Hd as LspService,Zb as MANUAL_REGISTRY,Xb as MANUAL_TOPIC_IDS,ia as MAX_DIMENSION,bb as McpAuthRequiredError,nb as McpCapabilityProvider,ab as McpExpiredSessionError,ob as McpManager,mb as McpServerRuntime,na as PASTE_TMP_DIR_ENV,oa as PASTE_TMP_TTL_MS,bd as PLANNER_AGENT_NAME,Ha as PROMISE_PATTERN,ue as PROMPT_SECTION_REGISTRY,Yg as PROTOCOL_EMITTER_TOOLS,pd as ProviderRecoveryCoordinator,Ob as READ_DEFAULT_LIMIT,Qb as READ_MAX_LINE_CHARS,Pb as READ_PREFLIGHT_SIZE_BYTES,uf as REPO_EXPLORER_AGENT_NAME,vf as REPO_EXPLORER_TOOL_NAMES,Pa as Runner,ad as SCOUT_AGENT_NAME,Ae as SELF_KNOWLEDGE_ROUTING_RULE,te as SYSTEM_PROMPT,ke as SYSTEM_WORKFLOW_LIMITS,nd as StableBoundaryTracker,ja as TARGET_RAW_SIZE_BYTES,fd as TASK_ENGINE_ROLE_AGENTS,ug as TOOL_RESULT_TRUNCATION_GUARDRAIL_NAME,Fh as TRACING_ENV,dd as WORKER_AGENT_NAME,Ld as WORKFLOW_GENERATION_SYSTEM_PROMPT,gf as _resetRuntimeForTesting,kf as activate,pc as analyzeChangedScope,Ze as appendAuditEntry,Ab as appendSessionLineageLabel,Of as applyAccountingDelta,Bb as applySessionCompaction,Oc as applyToolResultGuardrail,Hb as archiveOldIslands,mh as autoModeDenialShouldFallback,vh as bashSignalCollector,Gh as bootstrapTracing,ng as boundedRevise,rh as breakerShouldFallback,og as budgetCeiling,le as buildApprovalSummary,Rf as buildBlockedGoal,Be as buildCapabilityContextSections,_g as buildClassifierPrompt,Sf as buildCompleteGoal,Nf as buildCreatedGoal,Ad as buildFallbackRoutingDecision,Cg as buildGoalRuntimeBinding,lb as buildInitializeCapabilities,We as buildLlmReviewPrompt,$b as buildManualToolDescription,Gg as buildMcpReverseCapabilities,Pf as buildPausedGoal,qd as buildPromptMessageContent,ye as buildPromptSnapshot,ud as buildProviderCapabilitySnapshot,Bd as buildProviderPolicyHintsForDecision,vd as buildProviderPolicyPromptNotes,oc as buildRepoIntelligenceContext,Bc as buildRepoIntelligenceIndex,lc as buildRepoOverview,Qf as buildResumedGoal,ze as buildSelfKnowledgeRoutingRule,Fb as buildSessionTree,De as buildSystemPrompt,Ce as buildSystemPromptSnapshot,Qd as buildWorkflowGenerationSkillContext,Pd as buildWorkflowGenerationUserPrompt,uh as checkAbsoluteDeny,rd as checkIncompleteToolCalls,Dd as checkPromiseSignal,me as clampWorkflowLimits,ah as classify,Qg as classifyBashCommand,ya as classifyError,ld as classifyResilienceError,Va as cleanupIncompleteToolCalls,T as clearRuntimeModelProviders,xh as collectAllSignals,Af as combineExtensionRuntimes,Sg as computeInputSignature,bh as computeRulesFingerprint,ff as configureRuntime,Sc as convertCapabilityReadResult,Rc as convertProviderSearchResults,Gb as countActiveLineageMessages,Ja as countTokens,Ka as createAgent,jh as createAutoModeDenialTracker,Bh as createAutoModeToolGuardrail,Pg as createBashClassifierConfig,Eh as createBashPrefixExtractor,ag as createBuiltinToolDefinition,ph as createCircuitBreaker,Ud as createCodingWorkflowBackend,Se as createCtxProxy,F as createCustomProvider,Hf as createDefaultCodingAgent,Rg as createDenialTracker,Bf as createExtensionRuntime,ga as createFileArtifactFromPath,La as createHandoff,fa as createImageArtifactFromPath,Ma as createInMemorySession,Jg as createKodaXTaskRunner,Xa as createMcpCapabilityId,pb as createMcpManager,cb as createMcpTransport,ve as createPromptSection,Cd as createReasoningPlan,je as createRunGraphWriter,lg as createSessionControl,vb as createSessionLineage,vg as createToolResultTruncationGuardrail,ha as createVideoArtifactFromPath,Ih as createWorkflowLifecycleController,Lh as createWorkflowPatternTemplateModule,qe as createWorkflowRunManager,Mh as decideWorkflowInvocation,Je as dedupeExtensionPathsByEntrypoint,Wa as defaultMcpCacheDir,Pe as defaultPolicy,de as deleteSavedWorkflow,ef as disableSelfModify,gb as discoverAuthorizationServerMetadata,Ne as discoverDefaultExtensions,Me as discoverExtensionsInDirectory,Le as discoverExtensionsInDirectoryDetailed,tf as discoverMarkdownAgents,hb as discoverOAuthEndpoints,fb as discoverProtectedResourceMetadata,Zd as discoverSavedWorkflows,id as drainPendingSwaps,j as effortToLegacyReasoningMode,Xg as emitVerdict,oe as emitWorkflowAgentDigest,wa as enqueueWithArtifacts,wf as ensureBuiltinRepoExplorerAgent,Ia as estimateTokens,wd as evaluateProviderPolicy,Ke as excludeExtensionPathsByEntrypoint,Ee as exec,kg as executeTool,Ib as extractArtifactLedger,Dh as extractCommandPrefix,td as extractComparableUserMessageText,Qc as extractHtmlTitle,eb as extractInsufficientScope,sd as extractPromptComparableText,db as extractResourceMetadataUrl,ub as extractTitleFromMessages,wh as fileSignalCollector,Uc as finalizeRetrievalResult,qf as findByVersion,Cb as findPreviousUserEntryId,Eb as forkSessionLineage,$c as formatAgentsForPrompt,Lg as formatParallelDispatchResult,Rb as formatSize,tb as generateSessionId,Sd as generateWorkflow,Td as generateWorkflowFromOptions,Df as getActiveExtensionRuntime,Ra as getAgentConfigHome,Sa as getAgentConfigPath,cg as getAllRegisteredTools,Ta as getAppDataDir,W as getAvailableProviderNames,$f as getBuiltinRegisteredToolDefinition,_f as getBuiltinToolDefinition,Xd as getBuiltinWorkflow,N as getCustomModelCapabilities,H as getCustomProvider,K as getCustomProviderList,M as getCustomProviderModelDescriptors,L as getCustomProviderModels,J as getCustomProviderNames,He as getDefaultExtensionDirectory,Id as getDefaultLspService,re as getDefaultWorkflowRunManager,Vg as getDenialContext,Gc as getImpactEstimate,Zc as getKodaxGlobalDir,$a as getMcpCachePaths,C as getModelCapabilities,ua as getModelInputCapabilities,Dc as getModuleContext,Fc as getProcessContext,t as getProvider,x as getProviderConfiguredCapabilityProfile,w as getProviderConfiguredReasoningCapability,y as getProviderList,v as getProviderModel,B as getProviderModelDescriptors,z as getProviderModels,Yf as getRegisteredToolDefinition,Cc as getRepoIntelligenceIndex,mc as getRepoOverview,Hc as getRepoRoutingSignals,hg as getRequiredToolParams,Q as getRuntimeModelProvider,S as getRuntimeModelProviderNames,wb as getSessionLineagePath,xb as getSessionMessagesFromLineage,Ec as getSymbolContext,Wf as getTool,Xf as getToolDefinition,Zf as getToolRegistrations,Nc as getToolResultPolicy,Kh as getWorkflowPatternTemplate,Kf as goalTokenDelta,hd as hasPendingSwap,da as inferImageMediaType,zd as inferTaskType,ea as inferVideoMediaType,ec as inspectEditFailure,Ac as inspectRepoIntelligenceRuntime,I as isCustomProviderName,Ug as isDeniedRecently,V as isKnownProvider,Kg as isParallelDispatchDirective,u as isProviderConfigured,A as isProviderName,R as isRuntimeModelProviderName,md as isSessionRecoveryCandidateError,Ge as isSupportedExtensionModulePath,eg as isToolFileMutation,gg as isToolMutation,fg as isToolNetworkRead,dg as isToolPlanModeAllowed,Tf as isValidTokenBudget,Ed as languageIdForPath,rf as listAll,Z as listAllModelCapabilities,nf as listArtifacts,D as listBuiltinModelCapabilities,bg as listBuiltinToolDefinitions,Yd as listBuiltinWorkflows,pf as listConstructed,O as listCustomProviderModelCapabilities,jg as listToolDefinitions,ig as listTools,Jh as listWorkflowPatternTemplates,_c as loadAgentsFiles,sf as loadAgentsFromMarkdown,fh as loadAutoRules,fe as loadGeneratedWorkflowFromRun,Te as loadHandler,ae as loadSavedWorkflow,$d as loadSavedWorkflowCapsule,kb as loadValidToken,Jf as makeDisabledGoalToolsContext,i as mapLegacyReasoningModeToEffortIntent,Fg as mcpRootsFromWorkspace,Jb as mergeArtifactLedger,Ya as normalizeMcpCapabilityId,ka as normalizePastedImage,h as normalizeReasoningEffortValue,_d as normalizeWorkflowModule,we as orderPromptSections,Vd as parallelInvestigation,eh as parseAutoRules,$g as parseClassifierOutput,dc as parseEditToolError,Xe as parseLlmReviewVerdict,Za as parseMcpCapabilityId,sh as parseModelSpec,k as parseReasoningEffortEnv,e as parseTimeoutSecEnvMs,Rd as parseWorkflowGeneration,jb as performOAuthLogin,pa as persistImageAsBlock,Vb as persistToolOutput,he as preflightWorkflowCapsule,Ic as prewarmRepoIntelligenceCaches,Kd as providerResilienceConfigFromTimeouts,qa as prunePasteTmpDir,ma as readAndNormalizeClipboardImage,of as readArtifact,_e as readAuditEntries,af as readBudget,la as readClipboardImage,df as readDisableState,zh as readSpeculativeWindowFromEnv,ch as readTrustState,yd as reasoningModeToDepth,od as reconstructMessagesWithToolGuard,lh as recordAutoModeAllow,kh as recordAutoModeBlock,wg as recordBlockerAttempt,qh as recordBreakerError,Tg as recordDenial,sg as registerCodingInvariants,Eg as registerConfiguredMcpCapabilityProvider,G as registerCustomProviders,P as registerModelProvider,ib as registerOAuthClient,Hg as registerOfficialSandboxExtension,Oa as registerPresetDispatcher,Vf as registerTool,lf as rehydrateActiveArtifacts,bf as remainingSelfModifyBudget,ce as renameSavedWorkflow,qc as renderChangedScope,xc as renderImpactEstimate,uc as renderModuleContext,wc as renderProcessContext,xe as renderPromptSections,nc as renderRepoOverview,Tc as renderRetrievalResult,vc as renderSymbolContext,ee as replaceSavedWorkflow,Fd as reportLspDiagnostics,xg as resetBlockerCounter,cf as resetBudget,th as resolveClassifierModel,gd as resolveConstructedAgent,Ie as resolveExtensionEntrypoint,_b as resolveKodaXManual,Y as resolveModelCapabilities,U as resolveProvider,X as resolveProviderModelDescriptors,l as resolveReasoningEffort,m as resolveReasoningEffortForModelSwitch,xd as resolveReasoningMode,zc as resolveRepoIntelligenceMode,yc as resolveRepoIntelligenceRuntimeConfig,kd as resolveResilienceConfig,yb as resolveSessionLineageTarget,pg as resolveToolCapability,Nd as resolveWorkflowGenerationTimeoutMs,Hh as resolveWorkflowIdentity,mf as revoke,Db as rewindSessionLineage,xf as rollbackSelfModify,Ue as runAstRules,If as runKodaX,Ye as runLlmReview,Dg as runManagedTask,Ig as runOrchestration,pe as runWorkflowFromOptions,ne as runWorkflowModule,ie as safeWorkflowArtifactName,be as saveGeneratedWorkflow,ge as saveGeneratedWorkflowFromRun,_a as searchMcpCatalog,Cf as setActiveExtensionRuntime,Qa as setAgentConfigHome,zb as setSessionLineageActiveEntry,Mf as shouldFlipBudgetLimited,Jd as shutdownDefaultLspService,Ah as speculativeRace,hf as stage,mg as startKodaX,se as startManagedWorkflow,gh as stripAssistantText,Pc as stripHtmlToText,jf as testArtifact,d as timeoutSecToMs,kc as toolAskUserQuestion,gc as toolBash,tc as toolChangedDiff,sc as toolChangedScope,Xc as toolCodeSearch,cc as toolEdit,hc as toolGlob,ic as toolGrep,Mc as toolImpactEstimate,fc as toolInsertAfterAnchor,Jc as toolModuleContext,qg as toolPermission,Lc as toolProcessContext,Wb as toolRead,rc as toolRepoOverview,Yc as toolSemanticLookup,Kc as toolSymbolContext,jc as toolUndo,Wc as toolWebFetch,Vc as toolWebSearch,bc as toolWrite,Sb as truncateHead,Ub as truncateLine,Tb as truncateTail,dh as trustProjectRules,Lf as turnWallTimeDelta,Ua as validateAndFixToolHistory,E as validateCustomProviderConfig,Od as validateGeneratedWorkflowSource,va as validateInputArtifactsForModel,Mg as validateSubtaskIndependence,Ve as validateToolSchemaForProvider,Bg as verifyGoalCompletion,Fe as webhook,zg as withGoalBeforeNextTurn,Ag as withGoalStopHook,ac as withManualToolBranding,ed as workerAgent,Nh as workflowStartOutcomeConsumesTurn};
@@ -1,2 +0,0 @@
1
- // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{$,A,Aa,B,Ba,C,Ca,D,Da,E,Ea,F,Fa,G,Ga,H,Ha,I,Ia,J,Ja,K,Ka,L,La,M,Ma,N,Na,O,Oa,P,Pa,Q,Qa,R,Ra,S,Sa,T,Ta,U,Ua,V,Va,W,Wa,X,Xa,Y,Ya,Z,Za,_,_a,a,aa,b,ba,c,ca,d,da,e,ea,f,fa,g,ga,h,ha,i,ia,j,ja,k,ka,l,la,m,ma,n,na,o,oa,p,pa,q,qa,r,ra,s,sa,t,ta,u,ua,v,va,w,wa,x,xa,y,ya,z,za}from"./chunk-HS2K74I4.js";import"./chunk-V4WSBIXB.js";export{Ra as DEFAULT_COST_RATES,i as KODAX_API_MIN_INTERVAL,g as KODAX_CAPPED_MAX_OUTPUT_TOKENS,ha as KODAX_DEFAULT_PROVIDER,u as KODAX_DEFAULT_THINKING_BUDGETS,h as KODAX_ESCALATED_MAX_OUTPUT_TOKENS,f as KODAX_MAX_TOKENS,ga as KODAX_PROVIDERS,fa as KODAX_PROVIDER_SNAPSHOTS,s as KODAX_REASONING_MODE_SEQUENCE,v as KODAX_REASONING_SAFETY_RESERVE,t as KODAX_STABLE_EFFORT_INTENTS,$ as KodaXAnthropicCompatProvider,R as KodaXBaseProvider,a as KodaXError,d as KodaXNetworkError,aa as KodaXOpenAICompatProvider,b as KodaXProviderError,c as KodaXRateLimitError,e as KodaXToolCallIdError,M as WORKFLOW_MAX_CONCURRENCY_ABSOLUTE,L as WORKFLOW_MAX_CONCURRENCY_DEFAULT,p as addRejectedEffort,Ta as calculateCost,m as capabilityCacheKey,H as clampThinkingBudget,T as classifyStopReason,W as classifyVerifyError,Ia as clearRuntimeModelProviders,Ua as createCostTracker,ua as createCustomProvider,B as effortToLegacyReasoningMode,K as extractHeadersFromError,Ya as formatCost,Za as formatCostReport,La as getAvailableProviderNames,ba as getCodexCliDefaultModel,da as getCodexCliKnownModels,Sa as getCostRate,Ca as getCustomModelCapabilities,wa as getCustomProvider,za as getCustomProviderList,Ba as getCustomProviderModelDescriptors,Aa as getCustomProviderModels,ya as getCustomProviderNames,F as getDefaultThinkingDepthForMode,ca as getGeminiCliDefaultModel,ea as getGeminiCliKnownModels,ra as getModelCapabilities,ia as getProvider,ma as getProviderConfiguredCapabilityProfile,la as getProviderConfiguredReasoningCapability,na as getProviderList,ka as getProviderModel,qa as getProviderModelDescriptors,oa as getProviderModels,w as getReasoningCapability,o as getRejectedEfforts,P as getRunScopedConfig,Fa as getRuntimeModelProvider,Ha as getRuntimeModelProviderNames,Xa as getSummary,X as insertCacheBoundary,Y as isCacheBoundary,U as isCleanStop,xa as isCustomProviderName,Ka as isKnownProvider,ja as isProviderConfigured,pa as isProviderName,x as isReasoningEnabled,Ga as isRuntimeModelProviderName,Oa as listAllModelCapabilities,sa as listBuiltinModelCapabilities,Da as listCustomProviderModelCapabilities,Qa as listProviderModels,Z as lowerCacheBoundaries,I as mapDepthToOpenAIReasoningEffort,A as mapLegacyReasoningModeToEffortIntent,n as narrowReasoningProfile,Q as normalizeCapabilityProfile,z as normalizeReasoningEffortValue,y as normalizeReasoningRequest,C as parseReasoningEffortEnv,J as parseRetryAfter,k as parseTimeoutSecEnvMs,S as parseToolInputWithSalvage,Va as recordRetry,Wa as recordUsage,va as registerCustomProviders,Ea as registerModelProvider,q as removeCacheEntry,l as resolveLlmTimeoutConfig,Na as resolveModelCapabilities,Ja as resolveProvider,Ma as resolveProviderModelDescriptors,D as resolveReasoningEffort,E as resolveReasoningEffortForModelSwitch,G as resolveThinkingBudget,N as resolveWorkflowMaxConcurrency,V as runVerifyCredential,O as runWithScopedConfig,r as sanitizeCapabilityCache,_a as sideQuery,_ as stripCacheBoundaries,j as timeoutSecToMs,ta as validateCustomProviderConfig,Pa as verifyProviderCredential};
@@ -1,2 +0,0 @@
1
- // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{j as a}from"./chunk-73Z7BK5H.js";import"./chunk-PIQWODWN.js";import"./chunk-526OILYL.js";import"./chunk-7QB55SYG.js";import"./chunk-HS2K74I4.js";import"./chunk-ZZDC75H4.js";import"./chunk-P4VF3JEP.js";import"./chunk-V4WSBIXB.js";export{a as startManagedWorkflow};
@@ -1,2 +0,0 @@
1
- // @kodax-ai/kodax — bundled distribution. See docs/ADR.md ADR-022 + ADR-024.
2
- import{y as a,z as b}from"./chunk-PIQWODWN.js";import"./chunk-7QB55SYG.js";import"./chunk-HS2K74I4.js";import"./chunk-ZZDC75H4.js";import"./chunk-P4VF3JEP.js";import"./chunk-V4WSBIXB.js";export{a as createWorkflowRunManager,b as getDefaultWorkflowRunManager};