@kodax-ai/kodax 0.7.58 → 0.7.60

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 (73) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +11 -4
  3. package/README_CN.md +10 -4
  4. package/dist/chunks/{agent-YJNC2755.js → agent-L5FC3YOY.js} +1 -1
  5. package/dist/chunks/argument-completer-BQDAYT7W.js +2 -0
  6. package/dist/chunks/chunk-2RLIKZOZ.js +18 -0
  7. package/dist/chunks/chunk-4K5BDO7S.js +721 -0
  8. package/dist/chunks/{chunk-XXEIFNBE.js → chunk-5TRQBMPR.js} +1 -1
  9. package/dist/chunks/{chunk-QHWXPJEG.js → chunk-6DWXUZMO.js} +166 -167
  10. package/dist/chunks/{chunk-CV6JHPEO.js → chunk-6OZ5KWG3.js} +1 -1
  11. package/dist/chunks/chunk-IJN6ZJVI.js +310 -0
  12. package/dist/chunks/chunk-QFCF3GNT.js +326 -0
  13. package/dist/chunks/{chunk-HS2K74I4.js → chunk-S4GVQO3W.js} +13 -13
  14. package/dist/chunks/{chunk-6AU6EPO6.js → chunk-SGNM3UP6.js} +1 -1
  15. package/dist/chunks/chunk-U6BNMGSK.js +17 -0
  16. package/dist/chunks/{chunk-526OILYL.js → chunk-UA744TZM.js} +1 -1
  17. package/dist/chunks/{chunk-NKHXRN7G.js → chunk-XULI4U7I.js} +119 -117
  18. package/dist/chunks/chunk-ZL5CEANW.js +7 -0
  19. package/dist/chunks/chunk-ZPD7IUKW.js +322 -0
  20. package/dist/chunks/compaction-config-E4LN3M53.js +2 -0
  21. package/dist/chunks/{construction-bootstrap-CIXFH5SE.js → construction-bootstrap-GIFDM4L5.js} +1 -1
  22. package/dist/chunks/dist-73L4OYPD.js +2 -0
  23. package/dist/chunks/dist-7PXDYX2R.js +2 -0
  24. package/dist/chunks/host-FLG7FJZT.js +2 -0
  25. package/dist/chunks/{paste-Y4DVUWSM.js → paste-FDYM7SZX.js} +1 -1
  26. package/dist/chunks/run-manager-IU5COC6X.js +2 -0
  27. package/dist/chunks/{utils-FLVVQHM7.js → utils-NP42DKL3.js} +1 -1
  28. package/dist/index.d.ts +13 -12
  29. package/dist/index.js +2 -2
  30. package/dist/kodax_cli.js +1063 -1020
  31. package/dist/provider-capabilities.json +971 -986
  32. package/dist/sdk-agent.d.ts +27 -15
  33. package/dist/sdk-agent.js +1 -1
  34. package/dist/sdk-coding.d.ts +84 -17
  35. package/dist/sdk-coding.js +1 -1
  36. package/dist/sdk-llm.d.ts +6 -6
  37. package/dist/sdk-llm.js +1 -1
  38. package/dist/sdk-mcp.js +1 -1
  39. package/dist/sdk-media.d.ts +1 -1
  40. package/dist/sdk-media.js +1 -1
  41. package/dist/sdk-repl.d.ts +13 -11
  42. package/dist/sdk-repl.js +2 -2
  43. package/dist/sdk-session.d.ts +7 -6
  44. package/dist/sdk-session.js +1 -1
  45. package/dist/sdk-skills.d.ts +4 -231
  46. package/dist/sdk-skills.js +1 -1
  47. package/dist/types-chunks/{base.d-BA9Doaj_.d.ts → base.d-DalIRhbb.d.ts} +1 -1
  48. package/dist/types-chunks/{bash-prefix-extractor.d-D3cddmyV.d.ts → bash-prefix-extractor.d-Ds1THKeH.d.ts} +88 -27
  49. package/dist/types-chunks/{capability-learning.d-DRV80ISB.d.ts → capability-learning.d-BQB0M70w.d.ts} +1 -1
  50. package/dist/types-chunks/{guardrail.d-iK7FwMdW.d.ts → guardrail.d-CdqJwwN7.d.ts} +3 -3
  51. package/dist/types-chunks/{process.d-DHow2y2G.d.ts → process.d-C93UMgPK.d.ts} +39 -6
  52. package/dist/types-chunks/{resolver.d-DDOfVYDr.d.ts → resolver.d-CGkfRULj.d.ts} +58 -4
  53. package/dist/types-chunks/{run-manager.d-ByDcJc5g.d.ts → run-manager.d-DLK3ed-T.d.ts} +5 -5
  54. package/dist/types-chunks/{sdk-session-21Tt3N_x.d.ts → sdk-session-CtwN7iBO.d.ts} +56 -8
  55. package/dist/types-chunks/{storage.d-BsZrBPYu.d.ts → storage.d-DlZS0g8w.d.ts} +2 -2
  56. package/dist/types-chunks/{types.d-Ci5YPFEh.d.ts → types.d-Bp4Lm1jv.d.ts} +37 -3
  57. package/dist/types-chunks/{types.d-D4ZA8LJV.d.ts → types.d-CSZAMmU-.d.ts} +4 -1
  58. package/dist/types-chunks/types.d-vJExiRje.d.ts +232 -0
  59. package/dist/types-chunks/{utils.d-BURxOxFd.d.ts → utils.d-Boz9k2HB.d.ts} +6 -5
  60. package/package.json +1 -1
  61. package/dist/chunks/argument-completer-QGBNXTYJ.js +0 -2
  62. package/dist/chunks/chunk-73Z7BK5H.js +0 -15
  63. package/dist/chunks/chunk-7QB55SYG.js +0 -326
  64. package/dist/chunks/chunk-CQ6EQG7E.js +0 -322
  65. package/dist/chunks/chunk-OBPB5BQ6.js +0 -310
  66. package/dist/chunks/chunk-P4VF3JEP.js +0 -7
  67. package/dist/chunks/chunk-PIQWODWN.js +0 -18
  68. package/dist/chunks/chunk-ZZDC75H4.js +0 -681
  69. package/dist/chunks/compaction-config-OPMRZSAK.js +0 -2
  70. package/dist/chunks/dist-JSE7NICF.js +0 -2
  71. package/dist/chunks/dist-SDNQOW52.js +0 -2
  72. package/dist/chunks/host-H7FQMMRC.js +0 -2
  73. 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';
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';
1
+ import { b as PermissionMode, F as FileSessionStorage, S as SessionData } from './storage.d-DlZS0g8w.js';
2
+ import { E as KodaXReasoningMode, j as KodaXMessage, c as KodaXContentBlock, R as KodaXTaskResultMetadata } from './types.d-Bp4Lm1jv.js';
3
+ import { m as KodaXAgentMode } from './bash-prefix-extractor.d-Ds1THKeH.js';
4
+ import { aj as KodaXSessionUiHistoryItem, an as KodaXSessionUiToolCall, a0 as KodaXJsonValue } from './process.d-C93UMgPK.js';
5
5
 
6
6
  /**
7
7
  * TextBuffer - Text buffer management class - 文本缓冲区管理类
@@ -738,6 +738,13 @@ type RestoredHistorySeed = {
738
738
  } | {
739
739
  type: "thinking";
740
740
  text: string;
741
+ } | {
742
+ type: "sidecar";
743
+ text: string;
744
+ verdict?: "revise" | "blocked";
745
+ } | {
746
+ type: "task_completed";
747
+ text: string;
741
748
  } | {
742
749
  type: "tool_summary";
743
750
  text: string;
@@ -745,7 +752,7 @@ type RestoredHistorySeed = {
745
752
  type: "tool_group";
746
753
  tools: KodaXSessionUiToolCall[];
747
754
  };
748
- /** Convert a RestoredHistorySeed to a CreatableHistoryItem. tool_summary → event with icon. */
755
+ /** Convert a RestoredHistorySeed to a CreatableHistoryItem. tool_summary / task_completed → event with icon. */
749
756
  declare function seedToHistoryItem(seed: RestoredHistorySeed): CreatableHistoryItem;
750
757
  declare function toolCallSeedToHistoryToolCall(tool: KodaXSessionUiToolCall): ToolCall;
751
758
  /**
@@ -755,6 +762,15 @@ interface HistorySeedSourceMessage {
755
762
  role: KodaXMessage["role"];
756
763
  content: string | KodaXContentBlock[];
757
764
  _synthetic?: boolean;
765
+ /**
766
+ * Provenance marker persisted on host-injected messages. `'sidecar-verifier'`
767
+ * tags the synthetic user message the Sidecar Verifier injects on a `revise`
768
+ * verdict; `'task-completed'` tags the synthetic user message carrying a
769
+ * dispatch_child_task / run_workflow `<task-completed>` result banner. Both are
770
+ * rendered under their own identity on restore instead of being swallowed by
771
+ * the generic `_synthetic` skip.
772
+ */
773
+ _source?: string;
758
774
  }
759
775
  declare function extractHistorySeedsFromMessage(message: HistorySeedSourceMessage): RestoredHistorySeed[];
760
776
  declare function extractHistorySeedsFromMessages(messages: readonly HistorySeedSourceMessage[]): RestoredHistorySeed[];
@@ -849,21 +865,44 @@ interface SessionSummary {
849
865
  * surfaced when `includeArchived` is set). */
850
866
  readonly archived?: boolean;
851
867
  }
852
- type SessionTranscriptEntryType = 'message' | 'compaction' | 'branch_summary';
868
+ type SessionTranscriptEntryType = 'message' | 'compaction' | 'branch_summary' | 'client_notice'
869
+ /**
870
+ * Synthetic task/workflow completion entry derived from `_taskResult`,
871
+ * `_taskResults`, or legacy `<task-completed>` banners. The original
872
+ * `KodaXMessage` is still exposed on `message`, but consumers that want a
873
+ * complete transcript should not filter only `type === 'message'`.
874
+ */
875
+ | 'task_result';
876
+ type SessionTranscriptEntrySource = 'user' | 'assistant' | 'workflow' | 'child_task' | 'system' | 'client';
853
877
  interface SessionTranscriptEntry {
854
878
  readonly entryId: string;
855
879
  readonly parentId: string | null;
880
+ /** Stable logical identity shared by cloned/forked copies of the same entry. */
881
+ readonly logicalId: string;
882
+ /** Root source physical entry id when this transcript entry was cloned/forked. */
883
+ readonly sourceEntryId?: string;
856
884
  readonly timestamp: string;
857
885
  readonly type: SessionTranscriptEntryType;
886
+ readonly source?: SessionTranscriptEntrySource;
887
+ readonly turnId?: string;
858
888
  readonly message: KodaXMessage;
859
889
  readonly active: boolean;
860
890
  readonly summary?: string;
891
+ readonly payload?: unknown;
892
+ readonly taskResults?: readonly KodaXTaskResultMetadata[];
861
893
  }
862
894
  interface FullTranscriptSessionData extends Omit<SessionData, 'messages'> {
863
895
  readonly messages: KodaXMessage[];
864
896
  readonly activeMessages: KodaXMessage[];
865
897
  readonly transcriptEntries: SessionTranscriptEntry[];
866
898
  }
899
+ interface AppendClientNoticeOptions {
900
+ readonly source?: string;
901
+ readonly content: string;
902
+ readonly timestamp?: string;
903
+ readonly turnId?: string;
904
+ readonly payload?: KodaXJsonValue;
905
+ }
867
906
  interface ListSessionsOptions {
868
907
  /**
869
908
  * Alias for gitRoot; backwards-compat with KodaX Space terminology.
@@ -901,6 +940,7 @@ interface SessionManager {
901
940
  listSessions: typeof listSessions;
902
941
  loadSession: typeof loadSession;
903
942
  loadFullTranscript: typeof loadFullTranscript;
943
+ appendClientNotice: typeof appendClientNotice;
904
944
  forkSession: typeof forkSession;
905
945
  rewindSession: typeof rewindSession;
906
946
  setActiveEntry: typeof setActiveEntry;
@@ -941,6 +981,14 @@ declare function loadSession(id: string): Promise<SessionData | null>;
941
981
  * append order and keeps the active branch in `activeMessages`.
942
982
  */
943
983
  declare function loadFullTranscript(id: string): Promise<FullTranscriptSessionData | null>;
984
+ /**
985
+ * Append a host-owned transcript notice that never enters model context.
986
+ *
987
+ * Use this for local slash-command output such as `/doctor`, `/mcp status`,
988
+ * or host-side status panes. It is visible through `loadFullTranscript()` but
989
+ * `loadSession()` keeps returning only the active model messages.
990
+ */
991
+ declare function appendClientNotice(id: string, options: AppendClientNoticeOptions): Promise<SessionTranscriptEntry | null>;
944
992
  /**
945
993
  * Fork a session at an optional selector.
946
994
  * Returns null for a missing session. NEVER throws.
@@ -1038,5 +1086,5 @@ declare function createSessionManager(opts?: {
1038
1086
  sessionsDir?: string;
1039
1087
  }): SessionManager;
1040
1088
 
1041
- export { DEFAULT_UI_STATE as D, StreamingState as O, TOOL_STATUS_ICONS as T, TextBuffer as U, ToolCallStatus as _, archiveSession as a5, createSessionManager as a6, deleteSession as a7, extractHistorySeedsFromMessage as a8, extractHistorySeedsFromMessages as a9, extractTextContent as aa, extractTitle as ab, forkSession as ac, formatMessagePreview as ad, listRunningSessions as ae, listSessions as af, loadFullTranscript as ag, loadSession as ah, restoreHistoryItemsFromSession as ai, rewindSession as aj, seedToHistoryItem as ak, setActiveEntry as al, toolCallSeedToHistoryToolCall as am, trimPersistedUiHistorySnapshot as an, unarchiveSession as ao, watchSessions as ap, KeypressHandlerPriority as v };
1042
- export type { UIActions as $, AppProps as A, RunningSessionInfo as B, Completer as C, SessionSummary as E, FullTranscriptSessionData as F, SessionTranscriptEntry as G, HistoryEntry as H, InputPromptProps as I, SessionTranscriptEntryType as J, KeyInfo as K, LegacyMessageListProps as L, Message as M, StatusBarProps as N, PastedContent as P, Suggestion as Q, RestoreHistoryItemsFromSessionInput as R, SessionManager as S, TextBufferOptions as V, Theme as W, ThemeColors as X, ThemeSymbols as Y, ToolCall as Z, AppState as a, UIState as a0, UseTextBufferReturn as a1, VisualCursor as a2, VisualLayout as a3, WatchSessionsCallback as a4, Completion as b, CreatableHistoryItem as c, CursorPosition as d, DeleteSessionResult as e, HistoryItem as f, HistoryItemAssistant as g, HistoryItemBase as h, HistoryItemError as i, HistoryItemEvent as j, HistoryItemHint as k, HistoryItemInfo as l, HistoryItemSidecar as m, HistoryItemSystem as n, HistoryItemThinking as o, HistoryItemToolGroup as p, HistoryItemType as q, HistoryItemUser as r, HistorySeedSourceMessage as s, KeypressEvent as t, KeypressHandler as u, ListSessionsOptions as w, PromptEditingMode as x, PromptSubmitPayload as y, RestoredHistorySeed as z };
1089
+ export { ToolCallStatus as $, DEFAULT_UI_STATE as D, StreamingState as Q, TOOL_STATUS_ICONS as U, TextBuffer as V, appendClientNotice as a6, archiveSession as a7, createSessionManager as a8, deleteSession as a9, extractHistorySeedsFromMessage as aa, extractHistorySeedsFromMessages as ab, extractTextContent as ac, extractTitle as ad, forkSession as ae, formatMessagePreview as af, listRunningSessions as ag, listSessions as ah, loadFullTranscript as ai, loadSession as aj, restoreHistoryItemsFromSession as ak, rewindSession as al, seedToHistoryItem as am, setActiveEntry as an, toolCallSeedToHistoryToolCall as ao, trimPersistedUiHistorySnapshot as ap, unarchiveSession as aq, watchSessions as ar, KeypressHandlerPriority as w };
1090
+ export type { AppProps as A, RestoredHistorySeed as B, Completer as C, RunningSessionInfo as E, FullTranscriptSessionData as F, SessionSummary as G, HistoryEntry as H, InputPromptProps as I, SessionTranscriptEntry as J, KeyInfo as K, LegacyMessageListProps as L, Message as M, SessionTranscriptEntryType as N, StatusBarProps as O, PastedContent as P, RestoreHistoryItemsFromSessionInput as R, SessionManager as S, Suggestion as T, TextBufferOptions as W, Theme as X, ThemeColors as Y, ThemeSymbols as Z, ToolCall as _, AppState as a, UIActions as a0, UIState as a1, UseTextBufferReturn as a2, VisualCursor as a3, VisualLayout as a4, WatchSessionsCallback as a5, AppendClientNoticeOptions as b, Completion as c, CreatableHistoryItem as d, CursorPosition as e, DeleteSessionResult as f, HistoryItem as g, HistoryItemAssistant as h, HistoryItemBase as i, HistoryItemError as j, HistoryItemEvent as k, HistoryItemHint as l, HistoryItemInfo as m, HistoryItemSidecar as n, HistoryItemSystem as o, HistoryItemThinking as p, HistoryItemToolGroup as q, HistoryItemType as r, HistoryItemUser as s, HistorySeedSourceMessage as t, KeypressEvent as u, KeypressHandler as v, ListSessionsOptions as x, PromptEditingMode as y, PromptSubmitPayload as z };
@@ -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-Ds1THKeH.js';
2
+ import { a6 as KodaXSessionData, ab as KodaXSessionLineage, ae as KodaXSessionNavigationOptions, af as KodaXSessionRuntimeInfo, ah as KodaXSessionStorage } from './process.d-C93UMgPK.js';
3
3
 
4
4
  /**
5
5
  * Permission Types
@@ -113,6 +113,17 @@ interface KodaXCacheBoundary {
113
113
  hint?: 'system' | 'tools' | 'role-prompt';
114
114
  }
115
115
  type KodaXContentBlock = KodaXTextBlock | KodaXToolUseBlock | KodaXToolResultBlock | KodaXImageBlock | KodaXThinkingBlock | KodaXRedactedThinkingBlock | KodaXCacheBoundary;
116
+ type KodaXTaskResultSource = 'workflow' | 'child_task';
117
+ interface KodaXTaskResultMetadata {
118
+ type: 'task_result';
119
+ source: KodaXTaskResultSource;
120
+ taskId: string;
121
+ runId?: string;
122
+ status: 'completed' | 'failed' | 'cancelled';
123
+ title?: string;
124
+ summary?: string;
125
+ artifactRefs?: string[];
126
+ }
116
127
  interface KodaXMessage {
117
128
  role: 'user' | 'assistant' | 'system';
118
129
  content: string | KodaXContentBlock[];
@@ -122,10 +133,33 @@ interface KodaXMessage {
122
133
  * Identifies which subsystem injected a synthetic message so consumers can
123
134
  * render/attribute it distinctly instead of treating it like a user query.
124
135
  * Absent on genuine user/assistant/system messages. Known values include
125
- * `'sidecar-verifier'` (Sidecar Verifier revise feedback). Exposed verbatim
126
- * through `KodaXResult.messages` and session-load APIs for SDK consumers.
136
+ * `'sidecar-verifier'` (Sidecar Verifier revise feedback) and `'task-completed'`
137
+ * (a dispatch_child_task / run_workflow `<task-completed>` result banner spliced
138
+ * into the transcript; a rare same-wake mix with a system-reminder shares this
139
+ * one label, content preserved). Exposed verbatim through `KodaXResult.messages`
140
+ * and session-load APIs for SDK consumers.
127
141
  */
128
142
  _source?: string;
143
+ /** Structured task/workflow result metadata for synthetic task-completed messages. */
144
+ _taskResult?: KodaXTaskResultMetadata;
145
+ /** Multiple task results when one synthetic wake message contains several banners. */
146
+ _taskResults?: KodaXTaskResultMetadata[];
147
+ /**
148
+ * Stable SDK turn id that owns this transcript message. Optional for older
149
+ * sessions and provider-internal synthetic messages.
150
+ */
151
+ turnId?: string;
152
+ /**
153
+ * ISO-8601 timestamp of when this message was finalized (assistant: when the
154
+ * LLM stream completed; user: when submitted/injected). Optional and
155
+ * best-effort: messages persisted before this field existed, or produced by a
156
+ * path not yet updated to stamp it, will not carry it. `createSessionLineage`
157
+ * prefers this value for the session entry's timestamp and falls back to the
158
+ * accounting-time clock when absent, so a whole managed task no longer
159
+ * collapses to a single save-time millisecond. Not authoritative for ordering
160
+ * (array order is) — treat as display metadata (e.g. per-message "N ago").
161
+ */
162
+ timestamp?: string;
129
163
  }
130
164
  interface KodaXTokenUsage {
131
165
  inputTokens: number;
@@ -595,4 +629,4 @@ interface KodaXProviderStreamOptions {
595
629
  signal?: AbortSignal;
596
630
  }
597
631
 
598
- export type { KodaXToolResultBlock as $, KodaXReasoningCapability as A, KodaXReasoningEffortPreset as B, KodaXReasoningEffortRequest as C, KodaXReasoningEffortWireStrategy as D, KodaXReasoningMode as E, KodaXReasoningProfile as F, KodaXReasoningRequest as G, KodaXRedactedThinkingBlock as H, KodaXReviewScale as I, KodaXRiskLevel as J, KodaXAssuranceIntent as K, KodaXStableEffortIntent as L, KodaXStreamResult as M, KodaXTaskActionability as N, KodaXTaskBudgetOverrides as O, KodaXTaskComplexity as P, KodaXTaskFamily as Q, KodaXTaskRoutingDecision as R, KodaXTaskType as S, KodaXTaskWorkIntent as T, KodaXTextBlock as U, KodaXThinkingBlock as V, KodaXThinkingBudgetMap as W, KodaXThinkingDepth as X, KodaXThinkingWireStrategy as Y, KodaXTokenUsage as Z, KodaXToolDefinition as _, KodaXCacheBoundary as a, KodaXToolResultContentItem as a0, KodaXToolResultImageItem as a1, KodaXToolResultTextItem as a2, KodaXToolUseBlock as a3, KodaXVerifyCredentialResult as a4, KodaXVerifyStrategy as a5, KodaXWireReasoningEffort as a6, KodaXChildFanoutClass as b, KodaXContentBlock as c, KodaXCustomProviderConfig as d, KodaXExecutionMode as e, KodaXExecutionPattern as f, KodaXHarnessProfile as g, KodaXImageBlock as h, KodaXListModelsResult as i, KodaXMessage as j, KodaXModelDescriptor as k, KodaXMutationSurface as l, KodaXNormalizedReasoningRequest as m, KodaXProtocolFamily as n, KodaXProviderCapabilityProfile as o, KodaXProviderConfig as p, KodaXProviderContextFidelity as q, KodaXProviderConversationSemantics as r, KodaXProviderEvidenceSupport as s, KodaXProviderLongRunningSupport as t, KodaXProviderMcpSupport as u, KodaXProviderMultimodalSupport as v, KodaXProviderSessionSupport as w, KodaXProviderStreamOptions as x, KodaXProviderToolCallingFidelity as y, KodaXProviderTransport as z };
632
+ export type { KodaXTokenUsage as $, KodaXReasoningCapability as A, KodaXReasoningEffortPreset as B, KodaXReasoningEffortRequest as C, KodaXReasoningEffortWireStrategy as D, KodaXReasoningMode as E, KodaXReasoningProfile as F, KodaXReasoningRequest as G, KodaXRedactedThinkingBlock as H, KodaXReviewScale as I, KodaXRiskLevel as J, KodaXAssuranceIntent as K, KodaXStableEffortIntent as L, KodaXStreamResult as M, KodaXTaskActionability as N, KodaXTaskBudgetOverrides as O, KodaXTaskComplexity as P, KodaXTaskFamily as Q, KodaXTaskResultMetadata as R, KodaXTaskResultSource as S, KodaXTaskRoutingDecision as T, KodaXTaskType as U, KodaXTaskWorkIntent as V, KodaXTextBlock as W, KodaXThinkingBlock as X, KodaXThinkingBudgetMap as Y, KodaXThinkingDepth as Z, KodaXThinkingWireStrategy as _, KodaXCacheBoundary as a, KodaXToolDefinition as a0, KodaXToolResultBlock as a1, KodaXToolResultContentItem as a2, KodaXToolResultImageItem as a3, KodaXToolResultTextItem as a4, KodaXToolUseBlock as a5, KodaXVerifyCredentialResult as a6, KodaXVerifyStrategy as a7, KodaXWireReasoningEffort as a8, KodaXChildFanoutClass as b, KodaXContentBlock as c, KodaXCustomProviderConfig as d, KodaXExecutionMode as e, KodaXExecutionPattern as f, KodaXHarnessProfile as g, KodaXImageBlock as h, KodaXListModelsResult as i, KodaXMessage as j, KodaXModelDescriptor as k, KodaXMutationSurface as l, KodaXNormalizedReasoningRequest as m, KodaXProtocolFamily as n, KodaXProviderCapabilityProfile as o, KodaXProviderConfig as p, KodaXProviderContextFidelity as q, KodaXProviderConversationSemantics as r, KodaXProviderEvidenceSupport as s, KodaXProviderLongRunningSupport as t, KodaXProviderMcpSupport as u, KodaXProviderMultimodalSupport as v, KodaXProviderSessionSupport as w, KodaXProviderStreamOptions as x, KodaXProviderToolCallingFidelity as y, KodaXProviderTransport as z };
@@ -1,4 +1,5 @@
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, aP as RunnerToolCall, e as Agent, g as AgentMessage, aS as RunnerToolResult, a$ as Span, _ as KodaXInputArtifact } from './process.d-C93UMgPK.js';
2
+ import { R as KodaXTaskResultMetadata } from './types.d-Bp4Lm1jv.js';
2
3
 
3
4
  /**
4
5
  * Guardrail Runtime — FEATURE_085 (v0.7.26).
@@ -185,6 +186,7 @@ interface QueuedMessage {
185
186
  readonly mode: MessageMode;
186
187
  readonly content: string;
187
188
  readonly inputArtifacts?: readonly QueuedInputArtifact[];
189
+ readonly taskResult?: KodaXTaskResultMetadata;
188
190
  /** Wall-clock timestamp (`Date.now()`) for tracing only — not used for ordering. */
189
191
  readonly enqueuedAt: number;
190
192
  }
@@ -271,6 +273,7 @@ interface EnqueueInput {
271
273
  readonly content: string;
272
274
  readonly agentId?: string;
273
275
  readonly inputArtifacts?: readonly QueuedInputArtifact[];
276
+ readonly taskResult?: KodaXTaskResultMetadata;
274
277
  }
275
278
 
276
279
  export { GuardrailBlockedError as G, GuardrailEscalateError as b, collectGuardrails as h, runOutputGuardrails as i, runToolAfterGuardrails as j, runToolBeforeGuardrails as k, runInputGuardrails as r };
@@ -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';
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';
1
+ import { Q as KodaXOptions, v as KodaXContextTokenSnapshot, a6 as KodaXSkillDynamicContextPolicy, m as KodaXAgentMode, V as KodaXRepoIntelligenceMode, a7 as KodaXSkillInvocationContext } from './bash-prefix-extractor.d-Ds1THKeH.js';
2
+ import { c as SessionStorage$1, b as PermissionMode } from './storage.d-DlZS0g8w.js';
3
+ import { aj as KodaXSessionUiHistoryItem, ab as KodaXSessionLineage, a2 as KodaXSessionArtifactLedgerEntry, R as KodaXExtensionSessionState, Q as KodaXExtensionSessionRecord, af as KodaXSessionRuntimeInfo, ah as KodaXSessionStorage, a6 as KodaXSessionData, bN as WorkflowProcessSource } from './process.d-C93UMgPK.js';
4
+ import { j as KodaXMessage, E as KodaXReasoningMode, o as KodaXProviderCapabilityProfile, d as KodaXCustomProviderConfig } from './types.d-Bp4Lm1jv.js';
5
+ import { A as AgentsFile, f as AutoModeStats, l as KodaXMcpServersConfig } from './guardrail.d-CdqJwwN7.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.60",
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};