taskflow-core 0.1.8 → 0.2.0

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 (115) hide show
  1. package/README.md +80 -25
  2. package/dist/deterministic.d.ts +8 -0
  3. package/dist/deterministic.d.ts.map +1 -1
  4. package/dist/deterministic.js +23 -1
  5. package/dist/deterministic.js.map +1 -1
  6. package/dist/exec/driver.d.ts +47 -0
  7. package/dist/exec/driver.d.ts.map +1 -0
  8. package/dist/exec/driver.js +397 -0
  9. package/dist/exec/driver.js.map +1 -0
  10. package/dist/exec/events.d.ts +76 -0
  11. package/dist/exec/events.d.ts.map +1 -0
  12. package/dist/exec/events.js +108 -0
  13. package/dist/exec/events.js.map +1 -0
  14. package/dist/exec/fold.d.ts +45 -0
  15. package/dist/exec/fold.d.ts.map +1 -0
  16. package/dist/exec/fold.js +122 -0
  17. package/dist/exec/fold.js.map +1 -0
  18. package/dist/exec/index.d.ts +17 -0
  19. package/dist/exec/index.d.ts.map +1 -0
  20. package/dist/exec/index.js +17 -0
  21. package/dist/exec/index.js.map +1 -0
  22. package/dist/exec/kernel-policy.d.ts +35 -0
  23. package/dist/exec/kernel-policy.d.ts.map +1 -0
  24. package/dist/exec/kernel-policy.js +184 -0
  25. package/dist/exec/kernel-policy.js.map +1 -0
  26. package/dist/exec/step-kinds.d.ts +41 -0
  27. package/dist/exec/step-kinds.d.ts.map +1 -0
  28. package/dist/exec/step-kinds.js +574 -0
  29. package/dist/exec/step-kinds.js.map +1 -0
  30. package/dist/exec/step.d.ts +93 -0
  31. package/dist/exec/step.d.ts.map +1 -0
  32. package/dist/exec/step.js +436 -0
  33. package/dist/exec/step.js.map +1 -0
  34. package/dist/flowir/canonical-hash.d.ts +101 -0
  35. package/dist/flowir/canonical-hash.d.ts.map +1 -0
  36. package/dist/flowir/canonical-hash.js +219 -0
  37. package/dist/flowir/canonical-hash.js.map +1 -0
  38. package/dist/flowir/compile.d.ts +49 -0
  39. package/dist/flowir/compile.d.ts.map +1 -0
  40. package/dist/flowir/compile.js +219 -0
  41. package/dist/flowir/compile.js.map +1 -0
  42. package/dist/flowir/cond.d.ts +76 -0
  43. package/dist/flowir/cond.d.ts.map +1 -0
  44. package/dist/flowir/cond.js +214 -0
  45. package/dist/flowir/cond.js.map +1 -0
  46. package/dist/flowir/index.d.ts +20 -23
  47. package/dist/flowir/index.d.ts.map +1 -1
  48. package/dist/flowir/index.js +47 -35
  49. package/dist/flowir/index.js.map +1 -1
  50. package/dist/flowir/meta.d.ts +4 -4
  51. package/dist/flowir/meta.d.ts.map +1 -1
  52. package/dist/flowir/phasefp.d.ts.map +1 -1
  53. package/dist/flowir/phasefp.js +13 -1
  54. package/dist/flowir/phasefp.js.map +1 -1
  55. package/dist/flowir/schema.d.ts +260 -0
  56. package/dist/flowir/schema.d.ts.map +1 -0
  57. package/dist/flowir/schema.js +234 -0
  58. package/dist/flowir/schema.js.map +1 -0
  59. package/dist/flowir/translate.d.ts.map +1 -1
  60. package/dist/flowir/translate.js +3 -0
  61. package/dist/flowir/translate.js.map +1 -1
  62. package/dist/host/runner-types.d.ts +3 -0
  63. package/dist/host/runner-types.d.ts.map +1 -1
  64. package/dist/index.d.ts +2 -0
  65. package/dist/index.d.ts.map +1 -1
  66. package/dist/index.js +2 -0
  67. package/dist/index.js.map +1 -1
  68. package/dist/rates.d.ts +121 -0
  69. package/dist/rates.d.ts.map +1 -0
  70. package/dist/rates.js +187 -0
  71. package/dist/rates.js.map +1 -0
  72. package/dist/replay.d.ts +43 -50
  73. package/dist/replay.d.ts.map +1 -1
  74. package/dist/replay.js +629 -19
  75. package/dist/replay.js.map +1 -1
  76. package/dist/runner-core.d.ts +24 -0
  77. package/dist/runner-core.d.ts.map +1 -1
  78. package/dist/runner-core.js +225 -32
  79. package/dist/runner-core.js.map +1 -1
  80. package/dist/runtime/phases/approval.d.ts +23 -0
  81. package/dist/runtime/phases/approval.d.ts.map +1 -0
  82. package/dist/runtime/phases/approval.js +38 -0
  83. package/dist/runtime/phases/approval.js.map +1 -0
  84. package/dist/runtime/phases/expand.d.ts +29 -0
  85. package/dist/runtime/phases/expand.d.ts.map +1 -0
  86. package/dist/runtime/phases/expand.js +126 -0
  87. package/dist/runtime/phases/expand.js.map +1 -0
  88. package/dist/runtime/phases/parallel.d.ts +26 -0
  89. package/dist/runtime/phases/parallel.d.ts.map +1 -0
  90. package/dist/runtime/phases/parallel.js +15 -0
  91. package/dist/runtime/phases/parallel.js.map +1 -0
  92. package/dist/runtime/phases/race.d.ts +31 -0
  93. package/dist/runtime/phases/race.d.ts.map +1 -0
  94. package/dist/runtime/phases/race.js +220 -0
  95. package/dist/runtime/phases/race.js.map +1 -0
  96. package/dist/runtime/phases/script.d.ts +38 -0
  97. package/dist/runtime/phases/script.d.ts.map +1 -0
  98. package/dist/runtime/phases/script.js +139 -0
  99. package/dist/runtime/phases/script.js.map +1 -0
  100. package/dist/runtime.d.ts +29 -16
  101. package/dist/runtime.d.ts.map +1 -1
  102. package/dist/runtime.js +554 -292
  103. package/dist/runtime.js.map +1 -1
  104. package/dist/schema.d.ts +36 -4
  105. package/dist/schema.d.ts.map +1 -1
  106. package/dist/schema.js +86 -10
  107. package/dist/schema.js.map +1 -1
  108. package/dist/store.d.ts +6 -0
  109. package/dist/store.d.ts.map +1 -1
  110. package/dist/store.js.map +1 -1
  111. package/dist/trace.d.ts +4 -1
  112. package/dist/trace.d.ts.map +1 -1
  113. package/dist/trace.js +33 -26
  114. package/dist/trace.js.map +1 -1
  115. package/package.json +5 -4
@@ -0,0 +1,93 @@
1
+ /**
2
+ * exec/step — per-node handlers for the event-sourced kernel (RFC §6.3, S2).
3
+ *
4
+ * Kernel covers `EVENT_KERNEL_PHASE_TYPES` (PHASE_TYPES minus `race`/`expand` —
5
+ * currently 10 kinds). Complex paths live in `./step-kinds.ts`. Does **not**
6
+ * import `runtime.ts` (avoids circular deps with the strangler).
7
+ */
8
+ import type { Phase, Taskflow } from "../schema.ts";
9
+ import { PHASE_TYPES } from "../schema.ts";
10
+ import type { RunState } from "../store.ts";
11
+ import type { AgentConfig } from "../agents.ts";
12
+ import type { RunOptions, RunResult } from "../host/runner-types.ts";
13
+ import type { Event } from "./events.ts";
14
+ import { type UsageStats } from "../usage.ts";
15
+ import { type InterpolationContext } from "../interpolate.ts";
16
+ /** All DSL phase types — S2 kernel is complete. */
17
+ /** Kernel kinds: original 10. Horizon B `race`/`expand` run on the imperative
18
+ * path until dedicated step handlers land (canUseEventKernel excludes them). */
19
+ export declare const EVENT_KERNEL_PHASE_TYPES: readonly (typeof PHASE_TYPES)[number][];
20
+ export type EventKernelPhaseType = (typeof EVENT_KERNEL_PHASE_TYPES)[number];
21
+ export type RunTaskFn = (cwd: string, agents: AgentConfig[], agentName: string, task: string, opts: RunOptions, globalThinking?: string) => Promise<RunResult>;
22
+ /** Mirrors runtime ApprovalRequest — kept local to avoid step↔runtime cycles. */
23
+ export interface KernelApprovalRequest {
24
+ phaseId: string;
25
+ message: string;
26
+ upstream?: string;
27
+ }
28
+ export interface KernelApprovalDecision {
29
+ decision: "approve" | "reject" | "edit";
30
+ note?: string;
31
+ }
32
+ export interface NestedFlowResult {
33
+ finalOutput: string;
34
+ ok: boolean;
35
+ usage: UsageStats;
36
+ events: Event[];
37
+ blocked?: boolean;
38
+ }
39
+ export interface StepDeps {
40
+ cwd: string;
41
+ agents: AgentConfig[];
42
+ runTask: RunTaskFn;
43
+ signal?: AbortSignal;
44
+ globalThinking?: string;
45
+ requestApproval?: (req: KernelApprovalRequest) => Promise<KernelApprovalDecision>;
46
+ loadFlow?: (name: string) => Taskflow | undefined;
47
+ /** Sub-flow call stack (recursion guard). */
48
+ stack?: string[];
49
+ /** Nested flow runner (driver injects runEventKernel). */
50
+ runNested?: (opts: {
51
+ def: Taskflow;
52
+ args: Record<string, unknown>;
53
+ stack: string[];
54
+ }) => Promise<NestedFlowResult>;
55
+ }
56
+ export interface StepContext {
57
+ state: RunState;
58
+ deps: StepDeps;
59
+ steps: InterpolationContext["steps"];
60
+ args: Record<string, unknown>;
61
+ }
62
+ export interface StepResult {
63
+ events: Event[];
64
+ output?: string;
65
+ status: "done" | "failed" | "skipped" | "timedOut";
66
+ error?: string;
67
+ /** Token/cost usage for this phase (empty for script / skipped). */
68
+ usage: UsageStats;
69
+ /** Total runner attempts, including automatic transient retries. */
70
+ attempts?: number;
71
+ gate?: {
72
+ verdict: "pass" | "block";
73
+ reason?: string;
74
+ };
75
+ approval?: {
76
+ decision: "approve" | "reject" | "edit";
77
+ note?: string;
78
+ auto?: boolean;
79
+ };
80
+ warnings?: string[];
81
+ }
82
+ /** Accumulate usage from subagent-call events in a result. */
83
+ export declare function usageFromEvents(events: readonly Event[]): UsageStats;
84
+ /** Run a shell script phase (no LLM). Captures stdout. */
85
+ export declare function stepScript(phase: Phase, ctx: StepContext): Promise<StepResult>;
86
+ /** Run a single agent phase via the injected runner. */
87
+ export declare function stepAgent(phase: Phase, ctx: StepContext): Promise<StepResult>;
88
+ /**
89
+ * Dispatch one phase kind. Returns null if kind is not handled by this slice.
90
+ * Emits phase-start → optional when-guard decision → work → phase-end.
91
+ */
92
+ export declare function stepPhase(phase: Phase, ctx: StepContext): Promise<StepResult | null>;
93
+ //# sourceMappingURL=step.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"step.d.ts","sourceRoot":"","sources":["../../src/exec/step.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAyC,WAAW,EAAE,MAAM,cAAc,CAAC;AAClF,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACrE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;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AE,MAAM,EAAE,CAAC;CACpB;AA8BD,8DAA8D;AAC9D,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,KAAK,EAAE,GAAG,UAAU,CAcpE;AAaD,0DAA0D;AAC1D,wBAAsB,UAAU,CAAC,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,CAEpF;AAED,wDAAwD;AACxD,wBAAsB,SAAS,CAAC,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,CAEnF;AA+TD;;;GAGG;AACH,wBAAsB,SAAS,CAAC,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CA2E1F"}
@@ -0,0 +1,436 @@
1
+ /**
2
+ * exec/step — per-node handlers for the event-sourced kernel (RFC §6.3, S2).
3
+ *
4
+ * Kernel covers `EVENT_KERNEL_PHASE_TYPES` (PHASE_TYPES minus `race`/`expand` —
5
+ * currently 10 kinds). Complex paths live in `./step-kinds.ts`. Does **not**
6
+ * import `runtime.ts` (avoids circular deps with the strangler).
7
+ */
8
+ import { dependenciesOf, MAX_DYNAMIC_MAP_ITEMS, PHASE_TYPES } from "../schema.js";
9
+ import { EVENT_SCHEMA_VERSION } from "./events.js";
10
+ import { aggregateUsage, emptyUsage } from "../usage.js";
11
+ import { coerceArray, evaluateCondition, interpolate, safeParse, } from "../interpolate.js";
12
+ import { abortableDelay, isFailed as isFailedResult, isTransientError, mapWithConcurrencyLimit, PHASE_TIMEOUT_ABORT_GRACE_MS } from "../runner-core.js";
13
+ import { runScriptCommand, scriptResultToPhaseState, scriptSpawnErrorToPhaseState, } from "../runtime/phases/script.js";
14
+ import { executeApprovalBody, executeFlowBody, executeGateBody, executeLoopBody, executeReduceBody, executeTournamentBody, } from "./step-kinds.js";
15
+ import { kernelAttemptsOverBudget } from "./kernel-policy.js";
16
+ /** All DSL phase types — S2 kernel is complete. */
17
+ /** Kernel kinds: original 10. Horizon B `race`/`expand` run on the imperative
18
+ * path until dedicated step handlers land (canUseEventKernel excludes them). */
19
+ export const EVENT_KERNEL_PHASE_TYPES = PHASE_TYPES.filter((t) => t !== "race" && t !== "expand");
20
+ function baseEvent(ctx, phaseId, kind, extra = {}) {
21
+ return {
22
+ v: EVENT_SCHEMA_VERSION,
23
+ ts: Date.now(),
24
+ runId: ctx.state.runId,
25
+ phaseId,
26
+ kind,
27
+ ...extra,
28
+ };
29
+ }
30
+ /** Accumulate usage from subagent-call events in a result. */
31
+ export function usageFromEvents(events) {
32
+ const u = emptyUsage();
33
+ for (const e of events) {
34
+ const usage = e.output?.usage;
35
+ if (!usage)
36
+ continue;
37
+ u.input += usage.input ?? 0;
38
+ u.output += usage.output ?? 0;
39
+ u.cacheRead += usage.cacheRead ?? 0;
40
+ u.cacheWrite += usage.cacheWrite ?? 0;
41
+ u.cost += usage.cost ?? 0;
42
+ u.turns += usage.turns ?? 0;
43
+ if (typeof usage.contextTokens === "number")
44
+ u.contextTokens = usage.contextTokens;
45
+ }
46
+ return u;
47
+ }
48
+ /** Format fan-out results like the imperative runtime's mergePhaseState text. */
49
+ function combineFanoutText(results) {
50
+ return results
51
+ .map((r, i) => {
52
+ const label = `### [${i + 1}/${results.length}] ${r.agent}${isFailedResult(r) ? " (failed)" : ""}`;
53
+ const content = isFailedResult(r) ? r.errorMessage || r.stderr || r.output : r.output;
54
+ return `${label}\n\n${content}`;
55
+ })
56
+ .join("\n\n---\n\n");
57
+ }
58
+ /** Run a shell script phase (no LLM). Captures stdout. */
59
+ export async function stepScript(phase, ctx) {
60
+ return stepPhase({ ...phase, type: "script" }, ctx);
61
+ }
62
+ /** Run a single agent phase via the injected runner. */
63
+ export async function stepAgent(phase, ctx) {
64
+ return stepPhase({ ...phase, type: "agent" }, ctx);
65
+ }
66
+ async function executeScriptBody(phase, ctx) {
67
+ const run = phase.run;
68
+ if (!run || (Array.isArray(run) && run.length === 0)) {
69
+ const err = "script phase missing `run`";
70
+ return { midEvents: [], status: "failed", error: err, usage: emptyUsage() };
71
+ }
72
+ const argv = Array.isArray(run) ? run.map(String) : [String(run)];
73
+ const timeoutMs = phase.timeout ?? 60_000;
74
+ let phaseState;
75
+ try {
76
+ const result = await runScriptCommand({
77
+ interpRunText: argv,
78
+ arrayForm: Array.isArray(run),
79
+ cwd: ctx.deps.cwd,
80
+ signal: ctx.deps.signal,
81
+ timeoutMs,
82
+ });
83
+ phaseState = scriptResultToPhaseState(phase, result, { inputHash: "", timeoutMs });
84
+ }
85
+ catch (err) {
86
+ phaseState = scriptSpawnErrorToPhaseState(phase.id, err, { inputHash: "" });
87
+ }
88
+ const status = phaseState.timedOut
89
+ ? "timedOut"
90
+ : phaseState.status === "done"
91
+ ? "done"
92
+ : "failed";
93
+ const text = phaseState.output ?? "";
94
+ const usage = emptyUsage();
95
+ const midEvents = [
96
+ baseEvent(ctx, phase.id, "subagent-call", {
97
+ input: {
98
+ agent: "script",
99
+ task: Array.isArray(run) ? argv.join(" ") : String(run),
100
+ nodePath: phase.id,
101
+ },
102
+ output: {
103
+ text,
104
+ usage,
105
+ stopReason: phaseState.timedOut ? "timeout" : phaseState.status === "done" ? "end" : "error",
106
+ },
107
+ }),
108
+ ];
109
+ return {
110
+ midEvents,
111
+ output: text,
112
+ status,
113
+ error: status === "done" ? undefined : phaseState.error,
114
+ usage,
115
+ };
116
+ }
117
+ async function runOneAgent(ctx, phase, agentName, task, nodePath, mapIndex) {
118
+ // Per-phase timeout: AbortController chained to run signal (matches runtime).
119
+ const phaseTimeoutMs = typeof phase.timeout === "number" && Number.isFinite(phase.timeout) && phase.timeout >= 1000
120
+ ? phase.timeout
121
+ : undefined;
122
+ const attempts = [];
123
+ let r;
124
+ for (let attempt = 0; attempt < 4; attempt++) {
125
+ if (ctx.deps.signal?.aborted)
126
+ break;
127
+ let timedOut = false;
128
+ let timer;
129
+ let forceReturnTimer;
130
+ let onParentAbort;
131
+ let callSignal = ctx.deps.signal;
132
+ let timeoutController;
133
+ if (phaseTimeoutMs) {
134
+ const ac = new AbortController();
135
+ timeoutController = ac;
136
+ callSignal = ac.signal;
137
+ if (ctx.deps.signal?.aborted)
138
+ ac.abort();
139
+ else if (ctx.deps.signal) {
140
+ onParentAbort = () => ac.abort();
141
+ ctx.deps.signal.addEventListener("abort", onParentAbort, { once: true });
142
+ }
143
+ }
144
+ try {
145
+ const invocation = ctx.deps.runTask(ctx.deps.cwd, ctx.deps.agents, agentName, task, {
146
+ model: phase.model,
147
+ thinking: phase.thinking,
148
+ tools: phase.tools,
149
+ cwd: ctx.deps.cwd,
150
+ signal: callSignal,
151
+ }, ctx.deps.globalThinking);
152
+ if (phaseTimeoutMs) {
153
+ const timeoutFallback = new Promise((resolve) => {
154
+ timer = setTimeout(() => {
155
+ timedOut = true;
156
+ timeoutController?.abort();
157
+ forceReturnTimer = setTimeout(() => resolve({
158
+ agent: agentName,
159
+ task,
160
+ exitCode: 1,
161
+ output: "",
162
+ stderr: "",
163
+ usage: emptyUsage(),
164
+ stopReason: "error",
165
+ errorMessage: `Phase runner did not stop within ${PHASE_TIMEOUT_ABORT_GRACE_MS}ms after abort`,
166
+ phaseTimeout: true,
167
+ }), PHASE_TIMEOUT_ABORT_GRACE_MS);
168
+ }, phaseTimeoutMs);
169
+ });
170
+ r = await Promise.race([invocation, timeoutFallback]);
171
+ }
172
+ else {
173
+ r = await invocation;
174
+ }
175
+ }
176
+ finally {
177
+ if (timer)
178
+ clearTimeout(timer);
179
+ if (forceReturnTimer)
180
+ clearTimeout(forceReturnTimer);
181
+ if (onParentAbort)
182
+ ctx.deps.signal?.removeEventListener("abort", onParentAbort);
183
+ }
184
+ if (timedOut) {
185
+ r = {
186
+ ...r,
187
+ exitCode: r.exitCode === 0 ? 1 : r.exitCode,
188
+ stopReason: "error",
189
+ errorMessage: `Phase timed out after ${phaseTimeoutMs}ms (subagent aborted)`,
190
+ phaseTimeout: true,
191
+ };
192
+ }
193
+ attempts.push(r.usage ? { ...emptyUsage(), ...r.usage } : emptyUsage());
194
+ if (!isFailedResult(r))
195
+ break;
196
+ // The current phase has not been committed to state yet. Include prior
197
+ // completed run usage plus every attempt made here before admitting a
198
+ // transient retry, matching the imperative runner's live usage guard.
199
+ if (kernelAttemptsOverBudget(ctx.state, phase.id, attempts))
200
+ break;
201
+ if (r.phaseTimeout || phase.idempotent === false || !isTransientError(r) || attempt >= 3)
202
+ break;
203
+ const wait = Math.min(60_000, (phase.retry?.backoffMs ?? 2_000) * 2 ** attempt);
204
+ await abortableDelay(wait, ctx.deps.signal);
205
+ }
206
+ if (!r) {
207
+ r = {
208
+ agent: agentName,
209
+ task,
210
+ exitCode: 1,
211
+ output: "",
212
+ stderr: "Aborted before execution",
213
+ usage: emptyUsage(),
214
+ stopReason: "aborted",
215
+ errorMessage: "Aborted before execution",
216
+ };
217
+ }
218
+ const usage = aggregateUsage(attempts);
219
+ r = { ...r, usage, attempts: attempts.length };
220
+ const event = baseEvent(ctx, phase.id, "subagent-call", {
221
+ input: {
222
+ agent: agentName,
223
+ model: phase.model,
224
+ task,
225
+ nodePath,
226
+ mapIndex,
227
+ },
228
+ output: {
229
+ text: r.output ?? "",
230
+ model: r.model,
231
+ usage,
232
+ stopReason: r.stopReason,
233
+ },
234
+ });
235
+ return { result: r, event };
236
+ }
237
+ async function executeAgentBody(phase, ctx) {
238
+ const interpCtx = {
239
+ args: ctx.args,
240
+ steps: ctx.steps,
241
+ };
242
+ const task = interpolate(phase.task ?? "", interpCtx).text;
243
+ const agentName = phase.agent ?? "executor";
244
+ try {
245
+ const { result: r, event } = await runOneAgent(ctx, phase, agentName, task, phase.id);
246
+ const failed = isFailedResult(r);
247
+ const status = r.phaseTimeout ? "timedOut" : failed ? "failed" : "done";
248
+ const usage = r.usage ? { ...emptyUsage(), ...r.usage } : emptyUsage();
249
+ return {
250
+ midEvents: [event],
251
+ output: r.output,
252
+ status,
253
+ error: failed ? r.errorMessage ?? r.stderr : undefined,
254
+ usage,
255
+ attempts: r.attempts,
256
+ };
257
+ }
258
+ catch (e) {
259
+ const err = e instanceof Error ? e.message : String(e);
260
+ return { midEvents: [], status: "failed", error: err, usage: emptyUsage() };
261
+ }
262
+ }
263
+ /** Resolve map-item template; supports default `{item}` and custom `as` aliases via locals. */
264
+ function resolveMapTask(template, phase, ctx, item) {
265
+ const loopVar = phase.as ?? "item";
266
+ return interpolate(template, {
267
+ args: ctx.args,
268
+ steps: ctx.steps,
269
+ locals: { [loopVar]: item },
270
+ }).text;
271
+ }
272
+ async function executeMapBody(phase, ctx) {
273
+ const interpCtx = { args: ctx.args, steps: ctx.steps };
274
+ const overResolved = interpolate(phase.over ?? "", interpCtx).text;
275
+ const arr = coerceArray(safeParse(overResolved)) ?? coerceArray(overResolved);
276
+ if (!arr) {
277
+ const err = `map phase '${phase.id}': 'over' (${phase.over}) did not resolve to an array`;
278
+ return { midEvents: [], status: "failed", error: err, usage: emptyUsage() };
279
+ }
280
+ const concurrency = typeof phase.concurrency === "number" && phase.concurrency > 0 ? phase.concurrency : 8;
281
+ const agentName = phase.agent ?? "executor";
282
+ const dynamic = (ctx.deps.stack ?? []).some((frame) => frame.startsWith("def:"));
283
+ const truncated = dynamic && arr.length > MAX_DYNAMIC_MAP_ITEMS;
284
+ const admitted = truncated ? arr.slice(0, MAX_DYNAMIC_MAP_ITEMS) : arr;
285
+ const tasks = admitted.map((item) => ({
286
+ agent: agentName,
287
+ task: resolveMapTask(phase.task ?? "", phase, ctx, item),
288
+ }));
289
+ try {
290
+ const midEvents = [];
291
+ const results = await mapWithConcurrencyLimit(tasks, concurrency, async (it, idx) => {
292
+ const { result, event } = await runOneAgent(ctx, phase, it.agent, it.task, `${phase.id}#item-${idx}`, idx);
293
+ midEvents.push(event);
294
+ return result;
295
+ });
296
+ // Order events by mapIndex for stable fold/trace
297
+ midEvents.sort((a, b) => (a.input?.mapIndex ?? 0) - (b.input?.mapIndex ?? 0));
298
+ const anyFailed = results.some(isFailedResult);
299
+ const anyTimedOut = results.some((r) => r.phaseTimeout);
300
+ const usage = aggregateUsage(results.map((r) => r.usage ?? emptyUsage()));
301
+ const errors = results.filter(isFailedResult).map((r) => `${r.agent}: ${r.errorMessage ?? r.stderr}`);
302
+ return {
303
+ midEvents,
304
+ output: combineFanoutText(results),
305
+ status: anyTimedOut ? "timedOut" : anyFailed ? "failed" : "done",
306
+ error: errors.length ? errors.join("; ") : undefined,
307
+ usage,
308
+ warnings: truncated
309
+ ? [`map fan-out truncated to MAX_DYNAMIC_MAP_ITEMS (${MAX_DYNAMIC_MAP_ITEMS}) inside a dynamic sub-flow`]
310
+ : undefined,
311
+ };
312
+ }
313
+ catch (e) {
314
+ const err = e instanceof Error ? e.message : String(e);
315
+ return { midEvents: [], status: "failed", error: err, usage: emptyUsage() };
316
+ }
317
+ }
318
+ async function executeParallelBody(phase, ctx) {
319
+ const branches = phase.branches ?? [];
320
+ if (branches.length === 0) {
321
+ return {
322
+ midEvents: [],
323
+ status: "failed",
324
+ error: `parallel phase '${phase.id}': empty branches`,
325
+ usage: emptyUsage(),
326
+ };
327
+ }
328
+ const concurrency = typeof phase.concurrency === "number" && phase.concurrency > 0 ? phase.concurrency : 8;
329
+ const interpCtx = { args: ctx.args, steps: ctx.steps };
330
+ const tasks = branches.map((b) => ({
331
+ agent: b.agent ?? phase.agent ?? "executor",
332
+ task: interpolate(b.task, interpCtx).text,
333
+ }));
334
+ try {
335
+ const midEvents = [];
336
+ const results = await mapWithConcurrencyLimit(tasks, concurrency, async (it, idx) => {
337
+ const { result, event } = await runOneAgent(ctx, phase, it.agent, it.task, `${phase.id}#branch-${idx}`, idx);
338
+ midEvents.push(event);
339
+ return result;
340
+ });
341
+ midEvents.sort((a, b) => (a.input?.mapIndex ?? 0) - (b.input?.mapIndex ?? 0));
342
+ const anyFailed = results.some(isFailedResult);
343
+ const anyTimedOut = results.some((r) => r.phaseTimeout);
344
+ const usage = aggregateUsage(results.map((r) => r.usage ?? emptyUsage()));
345
+ const errors = results.filter(isFailedResult).map((r) => `${r.agent}: ${r.errorMessage ?? r.stderr}`);
346
+ return {
347
+ midEvents,
348
+ output: combineFanoutText(results),
349
+ status: anyTimedOut ? "timedOut" : anyFailed ? "failed" : "done",
350
+ error: errors.length ? errors.join("; ") : undefined,
351
+ usage,
352
+ };
353
+ }
354
+ catch (e) {
355
+ const err = e instanceof Error ? e.message : String(e);
356
+ return { midEvents: [], status: "failed", error: err, usage: emptyUsage() };
357
+ }
358
+ }
359
+ /**
360
+ * Dispatch one phase kind. Returns null if kind is not handled by this slice.
361
+ * Emits phase-start → optional when-guard decision → work → phase-end.
362
+ */
363
+ export async function stepPhase(phase, ctx) {
364
+ const type = (phase.type ?? "agent");
365
+ if (!EVENT_KERNEL_PHASE_TYPES.includes(type))
366
+ return null;
367
+ const events = [
368
+ baseEvent(ctx, phase.id, "phase-start", {
369
+ dependencies: dependenciesOf(phase),
370
+ optional: phase.optional === true,
371
+ }),
372
+ ];
373
+ if (type === "flow") {
374
+ events.push(baseEvent(ctx, phase.id, "decision", {
375
+ decision: { type: "unreplayable", reason: "inner-flow" },
376
+ }));
377
+ }
378
+ // when-guard (fail-open evaluateCondition matches imperative runtime)
379
+ if (phase.when !== undefined) {
380
+ const interpCtx = { args: ctx.args, steps: ctx.steps };
381
+ const whenResult = evaluateCondition(phase.when, interpCtx);
382
+ events.push(baseEvent(ctx, phase.id, "decision", {
383
+ decision: {
384
+ type: "when-guard",
385
+ expression: phase.when,
386
+ result: whenResult,
387
+ },
388
+ }));
389
+ if (!whenResult) {
390
+ const err = `Condition not met: ${phase.when}`;
391
+ events.push(baseEvent(ctx, phase.id, "phase-end", { status: "skipped", error: err }));
392
+ return { events, status: "skipped", error: err, usage: emptyUsage() };
393
+ }
394
+ }
395
+ let body;
396
+ if (type === "script")
397
+ body = await executeScriptBody(phase, ctx);
398
+ else if (type === "map")
399
+ body = await executeMapBody(phase, ctx);
400
+ else if (type === "parallel")
401
+ body = await executeParallelBody(phase, ctx);
402
+ else if (type === "reduce")
403
+ body = await executeReduceBody(phase, ctx);
404
+ else if (type === "gate")
405
+ body = await executeGateBody(phase, ctx);
406
+ else if (type === "approval")
407
+ body = await executeApprovalBody(phase, ctx);
408
+ else if (type === "loop")
409
+ body = await executeLoopBody(phase, ctx);
410
+ else if (type === "tournament")
411
+ body = await executeTournamentBody(phase, ctx);
412
+ else if (type === "flow")
413
+ body = await executeFlowBody(phase, ctx);
414
+ else
415
+ body = await executeAgentBody(phase, ctx);
416
+ events.push(...body.midEvents);
417
+ const endStatus = body.gate?.verdict === "block" && body.status === "done"
418
+ ? "done" // phase completes; run-level blocked handled by driver
419
+ : body.status;
420
+ events.push(baseEvent(ctx, phase.id, "phase-end", {
421
+ status: endStatus === "timedOut" ? "timedOut" : endStatus,
422
+ error: body.error,
423
+ }));
424
+ return {
425
+ events,
426
+ output: body.output,
427
+ status: body.status,
428
+ error: body.error,
429
+ usage: body.usage,
430
+ attempts: body.attempts,
431
+ gate: body.gate,
432
+ approval: body.approval,
433
+ warnings: body.warnings,
434
+ };
435
+ }
436
+ //# sourceMappingURL=step.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"step.js","sourceRoot":"","sources":["../../src/exec/step.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAAE,cAAc,EAAE,qBAAqB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAKlF,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,UAAU,EAAmB,MAAM,aAAa,CAAC;AAC1E,OAAO,EACN,WAAW,EACX,iBAAiB,EACjB,WAAW,EACX,SAAS,GAET,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,cAAc,EAAE,QAAQ,IAAI,cAAc,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAC;AACxJ,OAAO,EACN,gBAAgB,EAChB,wBAAwB,EACxB,4BAA4B,GAC5B,MA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IAAI,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC;IAC/B,MAAM,SAAS,GACd,IAAI,CAAC,IAAI,EAAE,OAAO,KAAK,OAAO,IAAI,IAAI,CAAC,MAAM,KAAK,MAAM;QACvD,CAAC,CAAC,MAAM,CAAC,uDAAuD;QAChE,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC;IAChB,MAAM,CAAC,IAAI,CACV,SAAS,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,WAAW,EAAE;QACrC,MAAM,EAAE,SAAS,KAAK,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS;QACzD,KAAK,EAAE,IAAI,CAAC,KAAK;KACjB,CAAC,CACF,CAAC;IACF,OAAO;QACN,MAAM;QACN,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,QAAQ,EAAE,IAAI,CAAC,QAAQ;KACvB,CAAC;AACH,CAAC"}
@@ -0,0 +1,101 @@
1
+ /**
2
+ * # Genuine content-addressed hash over canonical FlowIR
3
+ *
4
+ * This is pi-taskflow's **own** content-addressed hash (Q5=own) over the
5
+ * canonical {@link FlowIR} type contract defined in `./schema.ts`. Unlike
6
+ * `./hash.ts`'s `flowDefHash` — which fingerprints the *DSL Taskflow
7
+ * definition* (vendored from overstory, async Web Crypto, truncated to 16
8
+ * bytes / 32 hex) — this module hashes the *compiled IR* synchronously with
9
+ * `node:crypto` SHA-256 (full 64-hex-char digest). The two answer different
10
+ * questions:
11
+ *
12
+ * - `flowDefHash(def)` — "did the *flow definition* change?" (DSL-level)
13
+ * - `hashFlowIR(ir)` — "is this *compiled IR* the same IR?" (IR-level)
14
+ *
15
+ * Wired into `compileTaskflowToIR` via `hashFlowIR` (`ir:<64-hex>`).
16
+ * The IR-level hash is the content-addressed key the event-sourced kernel
17
+ * (batch 2, `flowir/compile.ts`) will use to deduplicate compiled graphs and
18
+ * to key per-phase fingerprints (`hashNode`) independent of surface formatting.
19
+ *
20
+ * ## Canonicalization guarantees
21
+ *
22
+ * {@link canonicalizeFlowIR} produces a DETERMINISTIC serialization that is
23
+ * invariant under the cosmetic differences two logically-equivalent IRs may
24
+ * differ by:
25
+ *
26
+ * - **Object key order** — all object keys are stable-sorted (UTF-16 code
27
+ * units), so reordering fields on a node or on the IR object does not
28
+ * change the canonical form.
29
+ * - **Node array order** — `nodes` is re-sorted by `id` (stable), so two IRs
30
+ * that list the same nodes in different order canonicalize identically.
31
+ * Other arrays (`inject`, `emits`, `deps`, `edges`) keep their order —
32
+ * their ordering is semantically meaningful (declared-read order, edge
33
+ * declaration order) and must be preserved.
34
+ * - **Condition spelling** — a node's `when` guard is canonicalized via
35
+ * {@link normalizeCond} (`./cond.ts`), which collapses whitespace, operator
36
+ * spacing, and redundant enclosing parens while preserving string-literal
37
+ * contents. Equivalent conditions canonicalize identically.
38
+ * - **Insignificant formatting** — `undefined` optional fields are dropped,
39
+ * so their presence/absence does not change the hash.
40
+ *
41
+ * Two logically-equivalent FlowIRs (key reorder, whitespace, equivalent
42
+ * condition spelling) MUST canonicalize to the same string.
43
+ *
44
+ * ## Domain-separated digests
45
+ *
46
+ * Return values are prefixed:
47
+ * - `hashFlowIR` → `ir:<64-hex>`
48
+ * - `hashNode` → `node:<64-hex>`
49
+ *
50
+ * so IR-level and node-level digests never collide in a shared cache key
51
+ * namespace.
52
+ *
53
+ * ## Purity
54
+ *
55
+ * Zero runtime deps besides `node:crypto`. No IO, no `Date`, no randomness,
56
+ * never throws. The hash is synchronous (unlike `flowDefHash`).
57
+ *
58
+ * Exported from the FlowIR barrel (`./index.ts`) for consumers; **not yet
59
+ * wired** into runtime/cache — `usedFallbackHash` is untouched. Wiring
60
+ * happens in batch 2.
61
+ *
62
+ * @see ./schema.ts for the canonical FlowIR type contract.
63
+ * @see ./cond.ts for condition normalization (`normalizeCond`).
64
+ * @see ./hash.ts for the DSL-level `flowDefHash` (vendored from overstory).
65
+ */
66
+ import type { FlowIR, FlowIRNode } from "./schema.ts";
67
+ /**
68
+ * Deterministic, order- and whitespace-independent canonical serialization of
69
+ * a {@link FlowIR}.
70
+ *
71
+ * - `nodes` is re-sorted by `id` (stable) so node-list order does not affect
72
+ * the result.
73
+ * - Each node's `when` guard is canonicalized via {@link normalizeCond}.
74
+ * - All object keys are stable-sorted; `undefined` optionals are dropped.
75
+ * - `inject`/`emits`/`deps`/`edges` arrays keep their order (semantic).
76
+ *
77
+ * Two logically-equivalent FlowIRs MUST canonicalize to the same string.
78
+ * Never throws.
79
+ */
80
+ export declare function canonicalizeFlowIR(ir: FlowIR): string;
81
+ /**
82
+ * Deterministic canonical serialization of a single {@link FlowIRNode}, for
83
+ * per-node content addressing. Same canonicalization rules as
84
+ * {@link canonicalizeFlowIR} applied to one node (`when` normalized, keys
85
+ * sorted, `undefined` optionals dropped, `inject`/`emits`/`deps` order
86
+ * preserved). Never throws.
87
+ */
88
+ export declare function canonicalizeNode(node: FlowIRNode): string;
89
+ /**
90
+ * Domain-separated content hash of a compiled FlowIR.
91
+ * Returns `ir:<64 lowercase hex SHA-256 chars>` over {@link canonicalizeFlowIR}.
92
+ * Synchronous. Never throws.
93
+ */
94
+ export declare function hashFlowIR(ir: FlowIR): string;
95
+ /**
96
+ * Domain-separated per-node content hash.
97
+ * Returns `node:<64 lowercase hex SHA-256 chars>` over {@link canonicalizeNode}.
98
+ * Synchronous. Never throws.
99
+ */
100
+ export declare function hashNode(node: FlowIRNode): string;
101
+ //# sourceMappingURL=canonical-hash.d.ts.map