@tagma/sdk 0.6.12 → 0.7.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 (110) hide show
  1. package/README.md +56 -15
  2. package/dist/bootstrap.d.ts +6 -6
  3. package/dist/bootstrap.d.ts.map +1 -1
  4. package/dist/bootstrap.js +5 -6
  5. package/dist/bootstrap.js.map +1 -1
  6. package/dist/config.d.ts +8 -0
  7. package/dist/config.d.ts.map +1 -0
  8. package/dist/config.js +5 -0
  9. package/dist/config.js.map +1 -0
  10. package/dist/core/dataflow.d.ts +23 -0
  11. package/dist/core/dataflow.d.ts.map +1 -0
  12. package/dist/core/dataflow.js +63 -0
  13. package/dist/core/dataflow.js.map +1 -0
  14. package/dist/core/log-prune.d.ts +16 -0
  15. package/dist/core/log-prune.d.ts.map +1 -0
  16. package/dist/core/log-prune.js +34 -0
  17. package/dist/core/log-prune.js.map +1 -0
  18. package/dist/core/preflight.d.ts +13 -0
  19. package/dist/core/preflight.d.ts.map +1 -0
  20. package/dist/core/preflight.js +61 -0
  21. package/dist/core/preflight.js.map +1 -0
  22. package/dist/core/run-context.d.ts +52 -0
  23. package/dist/core/run-context.d.ts.map +1 -0
  24. package/dist/core/run-context.js +156 -0
  25. package/dist/core/run-context.js.map +1 -0
  26. package/dist/core/run-state.d.ts +25 -0
  27. package/dist/core/run-state.d.ts.map +1 -0
  28. package/dist/core/run-state.js +93 -0
  29. package/dist/core/run-state.js.map +1 -0
  30. package/dist/core/scheduler.d.ts +13 -0
  31. package/dist/core/scheduler.d.ts.map +1 -0
  32. package/dist/core/scheduler.js +35 -0
  33. package/dist/core/scheduler.js.map +1 -0
  34. package/dist/core/task-executor.d.ts +13 -0
  35. package/dist/core/task-executor.d.ts.map +1 -0
  36. package/dist/core/task-executor.js +639 -0
  37. package/dist/core/task-executor.js.map +1 -0
  38. package/dist/core/trigger-errors.d.ts +9 -0
  39. package/dist/core/trigger-errors.d.ts.map +1 -0
  40. package/dist/core/trigger-errors.js +15 -0
  41. package/dist/core/trigger-errors.js.map +1 -0
  42. package/dist/engine.d.ts +6 -14
  43. package/dist/engine.d.ts.map +1 -1
  44. package/dist/engine.js +68 -1035
  45. package/dist/engine.js.map +1 -1
  46. package/dist/index.d.ts +9 -0
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +6 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/pipeline-definition.d.ts +3 -0
  51. package/dist/pipeline-definition.d.ts.map +1 -0
  52. package/dist/pipeline-definition.js +4 -0
  53. package/dist/pipeline-definition.js.map +1 -0
  54. package/dist/pipeline-runner.d.ts +2 -1
  55. package/dist/pipeline-runner.d.ts.map +1 -1
  56. package/dist/pipeline-runner.js +2 -2
  57. package/dist/pipeline-runner.js.map +1 -1
  58. package/dist/plugins.d.ts +5 -0
  59. package/dist/plugins.d.ts.map +1 -0
  60. package/dist/plugins.js +3 -0
  61. package/dist/plugins.js.map +1 -0
  62. package/dist/registry.d.ts +3 -19
  63. package/dist/registry.d.ts.map +1 -1
  64. package/dist/registry.js +7 -35
  65. package/dist/registry.js.map +1 -1
  66. package/dist/tagma.d.ts +24 -0
  67. package/dist/tagma.d.ts.map +1 -0
  68. package/dist/tagma.js +23 -0
  69. package/dist/tagma.js.map +1 -0
  70. package/dist/utils-api.d.ts +2 -0
  71. package/dist/utils-api.d.ts.map +1 -0
  72. package/dist/utils-api.js +2 -0
  73. package/dist/utils-api.js.map +1 -0
  74. package/dist/yaml.d.ts +4 -0
  75. package/dist/yaml.d.ts.map +1 -0
  76. package/dist/yaml.js +3 -0
  77. package/dist/yaml.js.map +1 -0
  78. package/package.json +52 -7
  79. package/src/bootstrap.ts +6 -6
  80. package/src/config.ts +26 -0
  81. package/src/core/dataflow.test.ts +167 -0
  82. package/src/core/dataflow.ts +118 -0
  83. package/src/core/log-prune.test.ts +58 -0
  84. package/src/core/log-prune.ts +43 -0
  85. package/src/core/preflight.test.ts +49 -0
  86. package/src/core/preflight.ts +89 -0
  87. package/src/core/run-context.test.ts +244 -0
  88. package/src/core/run-context.ts +207 -0
  89. package/src/core/run-state.test.ts +98 -0
  90. package/src/core/run-state.ts +122 -0
  91. package/src/core/scheduler.test.ts +83 -0
  92. package/src/core/scheduler.ts +42 -0
  93. package/src/core/task-executor.ts +803 -0
  94. package/src/core/trigger-errors.ts +15 -0
  95. package/src/engine.ts +80 -1248
  96. package/src/index.ts +28 -0
  97. package/src/pipeline-definition.ts +5 -0
  98. package/src/pipeline-runner.ts +3 -2
  99. package/src/plugin-registry.test.ts +7 -10
  100. package/src/plugins.ts +18 -0
  101. package/src/registry.ts +7 -49
  102. package/src/tagma.test.ts +84 -0
  103. package/src/tagma.ts +47 -0
  104. package/src/utils-api.ts +8 -0
  105. package/src/yaml.ts +11 -0
  106. package/dist/sdk.d.ts +0 -32
  107. package/dist/sdk.d.ts.map +0 -1
  108. package/dist/sdk.js +0 -41
  109. package/dist/sdk.js.map +0 -1
  110. package/src/sdk.ts +0 -151
@@ -0,0 +1,639 @@
1
+ import { resolve } from 'path';
2
+ import { runCommand, runSpawn } from '../runner';
3
+ import { parseDuration, nowISO } from '../utils';
4
+ import { promptDocumentFromString, serializePromptDocument, prependContext, renderInputsBlock, renderOutputSchemaBlock, } from '../prompt-doc';
5
+ import { resolveTaskBindingInputs, resolveTaskInputs, substituteInputs, } from '../ports';
6
+ import { executeHook, buildTaskContext } from '../hooks';
7
+ import { clip, tailLines } from '../logger';
8
+ import { extractSuccessfulOutputs, inferEffectivePorts } from './dataflow';
9
+ import { TriggerBlockedError, TriggerTimeoutError } from './trigger-errors';
10
+ const MAX_NORMALIZED_BYTES = 1_000_000;
11
+ function isPromptTaskConfig(task) {
12
+ return task.prompt !== undefined && task.command === undefined;
13
+ }
14
+ function isCommandTaskConfig(task) {
15
+ return task.command !== undefined && task.prompt === undefined;
16
+ }
17
+ export async function executeTask(options) {
18
+ const { taskId, ctx, registry, log, approvalGateway } = options;
19
+ const dag = ctx.dag;
20
+ const config = ctx.config;
21
+ const workDir = ctx.workDir;
22
+ const pipelineInfo = ctx.pipelineInfo;
23
+ const state = ctx.states.get(taskId);
24
+ const node = dag.nodes.get(taskId);
25
+ const task = node.task;
26
+ const track = node.track;
27
+ log.section(`Task ${taskId}`, taskId);
28
+ log.debug(`[task:${taskId}]`, `type=${isPromptTaskConfig(task) ? 'ai' : 'cmd'} track=${track.id} deps=[${node.dependsOn.join(', ') || '(root)'}]`);
29
+ // 1. Check dependencies
30
+ for (const depId of node.dependsOn) {
31
+ const result = ctx.isDependencySatisfied(depId);
32
+ if (result === 'skip') {
33
+ const depStatus = ctx.states.get(depId)?.status ?? 'unknown';
34
+ log.debug(`[task:${taskId}]`, `skipped (upstream "${depId}" status=${depStatus})`);
35
+ state.finishedAt = nowISO();
36
+ ctx.setTaskStatus(taskId, 'skipped');
37
+ return;
38
+ }
39
+ if (result === 'unsatisfied')
40
+ return; // still waiting
41
+ }
42
+ // 2. Check trigger
43
+ if (task.trigger) {
44
+ log.debug(`[task:${taskId}]`, `trigger wait: type=${task.trigger.type} ${JSON.stringify(task.trigger)}`);
45
+ try {
46
+ const triggerPlugin = registry.getHandler('triggers', task.trigger.type);
47
+ // R6: race the plugin's watch() against the pipeline's abort signal
48
+ // AND the task-level timeout. Third-party triggers may forget to
49
+ // wire up ctx.signal — without the abort race, an aborted pipeline
50
+ // would hang forever waiting for the plugin's watch promise to
51
+ // resolve. And without the timeout race, a buggy watch() that never
52
+ // settles would ignore the user's `task.timeout` (which the spawn
53
+ // path at step 4 already honours) — a task could wedge the whole
54
+ // pipeline until pipeline-level timeout fires (or forever, if none
55
+ // is set). Honouring task.timeout here makes the two stages
56
+ // symmetric. The cleanup paths in finally never run on the orphaned
57
+ // plugin promise (it's allowed to leak a watcher; the pipeline is
58
+ // being torn down anyway).
59
+ const triggerTimeoutMs = task.timeout ? parseDuration(task.timeout) : 0;
60
+ await new Promise((resolve, reject) => {
61
+ let settled = false;
62
+ let timer = null;
63
+ const onAbort = () => {
64
+ if (settled)
65
+ return;
66
+ settled = true;
67
+ if (timer !== null)
68
+ clearTimeout(timer);
69
+ reject(new Error('Pipeline aborted'));
70
+ };
71
+ if (ctx.abortController.signal.aborted) {
72
+ onAbort();
73
+ return;
74
+ }
75
+ ctx.abortController.signal.addEventListener('abort', onAbort, { once: true });
76
+ if (triggerTimeoutMs > 0) {
77
+ timer = setTimeout(() => {
78
+ if (settled)
79
+ return;
80
+ settled = true;
81
+ ctx.abortController.signal.removeEventListener('abort', onAbort);
82
+ reject(new TriggerTimeoutError(`Trigger "${task.trigger.type}" did not settle within ${task.timeout} (task-level timeout)`));
83
+ }, triggerTimeoutMs);
84
+ }
85
+ triggerPlugin
86
+ .watch(task.trigger, {
87
+ taskId: node.taskId,
88
+ trackId: track.id,
89
+ workDir: task.cwd ?? workDir,
90
+ signal: ctx.abortController.signal,
91
+ approvalGateway,
92
+ })
93
+ .then((v) => {
94
+ if (settled)
95
+ return;
96
+ settled = true;
97
+ if (timer !== null)
98
+ clearTimeout(timer);
99
+ ctx.abortController.signal.removeEventListener('abort', onAbort);
100
+ resolve(v);
101
+ }, (e) => {
102
+ if (settled)
103
+ return;
104
+ settled = true;
105
+ if (timer !== null)
106
+ clearTimeout(timer);
107
+ ctx.abortController.signal.removeEventListener('abort', onAbort);
108
+ reject(e);
109
+ });
110
+ });
111
+ log.debug(`[task:${taskId}]`, `trigger fired`);
112
+ }
113
+ catch (err) {
114
+ // If pipeline was aborted while we were still waiting for the trigger,
115
+ // this task never entered running state → skipped, not timeout.
116
+ state.finishedAt = nowISO();
117
+ if (ctx.abortReason !== null) {
118
+ ctx.setTaskStatus(taskId, 'skipped');
119
+ }
120
+ else if (err instanceof TriggerBlockedError) {
121
+ ctx.setTaskStatus(taskId, 'blocked'); // user/policy rejection
122
+ }
123
+ else if (err instanceof TriggerTimeoutError) {
124
+ ctx.setTaskStatus(taskId, 'timeout'); // genuine trigger wait timeout
125
+ }
126
+ else {
127
+ // A7 fallback: also check message strings for backward-compat with
128
+ // third-party trigger plugins that don't throw typed errors yet.
129
+ const msg = err instanceof Error ? err.message : String(err);
130
+ if (msg.includes('rejected') || msg.includes('denied')) {
131
+ ctx.setTaskStatus(taskId, 'blocked');
132
+ }
133
+ else if (msg.includes('timeout')) {
134
+ ctx.setTaskStatus(taskId, 'timeout');
135
+ }
136
+ else {
137
+ ctx.setTaskStatus(taskId, 'failed'); // plugin error, watcher crash, etc.
138
+ }
139
+ }
140
+ try {
141
+ await ctx.fireHook(taskId, 'task_failure');
142
+ }
143
+ catch (hookErr) {
144
+ log.error(`[task:${taskId}]`, `hook execution failed: ${hookErr instanceof Error ? hookErr.message : String(hookErr)}`);
145
+ }
146
+ return;
147
+ }
148
+ }
149
+ // 3. task_start hook (gate)
150
+ const hookResult = await executeHook(config.hooks, 'task_start', buildTaskContext('task_start', pipelineInfo, ctx.trackInfoOf(taskId), ctx.buildTaskInfoObj(taskId)), workDir, ctx.abortController.signal);
151
+ if (hookResult.exitCode !== 0 || config.hooks?.task_start) {
152
+ log.debug(`[task:${taskId}]`, `task_start hook exit=${hookResult.exitCode} allowed=${hookResult.allowed}`);
153
+ }
154
+ if (!hookResult.allowed) {
155
+ state.finishedAt = nowISO();
156
+ ctx.setTaskStatus(taskId, 'blocked');
157
+ try {
158
+ await ctx.fireHook(taskId, 'task_failure');
159
+ }
160
+ catch (hookErr) {
161
+ log.error(`[task:${taskId}]`, `hook execution failed: ${hookErr instanceof Error ? hookErr.message : String(hookErr)}`);
162
+ }
163
+ return;
164
+ }
165
+ // 3.5. Resolve port inputs from upstream outputs. This is the last
166
+ // gate before execution: missing-required inputs block the task
167
+ // without ever spawning a process, so the caller sees a clear
168
+ // "blocked: missing input X" rather than a cryptic runtime error
169
+ // from a command that expanded a placeholder to the empty string.
170
+ // Resolution runs even for tasks that declare no ports — the call
171
+ // is cheap and returns `{kind: 'ready', inputs: {}}` in that case,
172
+ // which downstream code handles uniformly.
173
+ //
174
+ // Prompt Tasks have no declared ports — their I/O contract is
175
+ // inferred from direct-neighbor Command Tasks (see ports.ts:
176
+ // `inferPromptPorts`). We synthesize a `TaskPorts` object and
177
+ // feed it into the same resolve/substitute/render/extract
178
+ // pipeline the Command path uses. Collisions that a Prompt can't
179
+ // disambiguate (same input name on two upstreams, incompatible
180
+ // downstream output types) block the task with a clear message.
181
+ const effectivePortsResult = inferEffectivePorts(ctx, taskId);
182
+ if (effectivePortsResult.kind === 'blocked') {
183
+ log.error(`[task:${taskId}]`, `blocked — prompt port inference failed:\n${effectivePortsResult.reason}`);
184
+ state.result = {
185
+ exitCode: -1,
186
+ stdout: '',
187
+ stderr: `[engine] prompt port inference failed:\n${effectivePortsResult.reason}`,
188
+ stdoutPath: null,
189
+ stderrPath: null,
190
+ durationMs: 0,
191
+ sessionId: null,
192
+ normalizedOutput: null,
193
+ failureKind: 'spawn_error',
194
+ outputs: null,
195
+ };
196
+ state.finishedAt = nowISO();
197
+ ctx.setTaskStatus(taskId, 'blocked');
198
+ try {
199
+ await ctx.fireHook(taskId, 'task_failure');
200
+ }
201
+ catch (hookErr) {
202
+ log.error(`[task:${taskId}]`, `hook execution failed: ${hookErr instanceof Error ? hookErr.message : String(hookErr)}`);
203
+ }
204
+ if (ctx.getOnFailure(taskId) === 'stop_all')
205
+ ctx.applyStopAll();
206
+ return;
207
+ }
208
+ const isPromptTask = effectivePortsResult.isPromptTask;
209
+ const effectivePorts = effectivePortsResult.effectivePorts;
210
+ const bindingResolution = resolveTaskBindingInputs(task, ctx.bindingDataMap, node.dependsOn);
211
+ if (bindingResolution.kind === 'blocked') {
212
+ log.error(`[task:${taskId}]`, `blocked — cannot resolve task input bindings:\n${bindingResolution.reason}`);
213
+ state.result = {
214
+ exitCode: -1,
215
+ stdout: '',
216
+ stderr: `[engine] task input binding resolution failed:\n${bindingResolution.reason}`,
217
+ stdoutPath: null,
218
+ stderrPath: null,
219
+ durationMs: 0,
220
+ sessionId: null,
221
+ normalizedOutput: null,
222
+ failureKind: 'spawn_error',
223
+ outputs: null,
224
+ };
225
+ state.finishedAt = nowISO();
226
+ ctx.setTaskStatus(taskId, 'blocked');
227
+ try {
228
+ await ctx.fireHook(taskId, 'task_failure');
229
+ }
230
+ catch (hookErr) {
231
+ log.error(`[task:${taskId}]`, `hook execution failed: ${hookErr instanceof Error ? hookErr.message : String(hookErr)}`);
232
+ }
233
+ if (ctx.getOnFailure(taskId) === 'stop_all')
234
+ ctx.applyStopAll();
235
+ return;
236
+ }
237
+ if (bindingResolution.missingOptional.length > 0) {
238
+ log.debug(`[task:${taskId}]`, `optional input bindings unresolved (empty in placeholders): ${bindingResolution.missingOptional.join(', ')}`);
239
+ }
240
+ // Feed effective ports into `resolveTaskInputs` by shallow-cloning
241
+ // the task. Prompt tasks get the inferred ports; Command tasks are
242
+ // unchanged (effectivePorts === task.ports).
243
+ const taskForResolve = effectivePorts === task.ports ? task : { ...task, ports: effectivePorts };
244
+ const inputResolution = resolveTaskInputs(taskForResolve, ctx.outputValuesMap, node.dependsOn);
245
+ if (inputResolution.kind === 'blocked') {
246
+ log.error(`[task:${taskId}]`, `blocked — cannot resolve port inputs:\n${inputResolution.reason}`);
247
+ state.result = {
248
+ exitCode: -1,
249
+ stdout: '',
250
+ stderr: `[engine] port input resolution failed:\n${inputResolution.reason}`,
251
+ stdoutPath: null,
252
+ stderrPath: null,
253
+ durationMs: 0,
254
+ sessionId: null,
255
+ normalizedOutput: null,
256
+ failureKind: 'spawn_error',
257
+ outputs: null,
258
+ };
259
+ state.finishedAt = nowISO();
260
+ ctx.setTaskStatus(taskId, 'blocked');
261
+ try {
262
+ await ctx.fireHook(taskId, 'task_failure');
263
+ }
264
+ catch (hookErr) {
265
+ log.error(`[task:${taskId}]`, `hook execution failed: ${hookErr instanceof Error ? hookErr.message : String(hookErr)}`);
266
+ }
267
+ if (ctx.getOnFailure(taskId) === 'stop_all')
268
+ ctx.applyStopAll();
269
+ return;
270
+ }
271
+ const resolvedInputs = { ...bindingResolution.inputs, ...inputResolution.inputs };
272
+ ctx.resolvedInputsMap.set(taskId, resolvedInputs);
273
+ if (inputResolution.missingOptional.length > 0) {
274
+ log.debug(`[task:${taskId}]`, `optional inputs unresolved (empty in placeholders): ${inputResolution.missingOptional.join(', ')}`);
275
+ }
276
+ if (effectivePorts?.inputs && effectivePorts.inputs.length > 0) {
277
+ log.debug(`[task:${taskId}]`, `resolved inputs: ${JSON.stringify(resolvedInputs)}` +
278
+ (isPromptTask ? ' (inferred from upstream Commands)' : ''));
279
+ }
280
+ // 4. Mark running — set startedAt before emitting so subscribers see a
281
+ // complete task_update (startedAt non-null) on the status transition.
282
+ state.startedAt = nowISO();
283
+ ctx.setTaskStatus(taskId, 'running');
284
+ log.info(`[task:${taskId}]`, isCommandTaskConfig(task) ? `running: ${task.command}` : `running (driver task)`);
285
+ // File-only: resolved config for this task
286
+ const resolvedDriver = task.driver ?? track.driver ?? config.driver ?? 'opencode';
287
+ const resolvedModel = task.model ?? track.model ?? config.model ?? '(default)';
288
+ const resolvedPerms = task.permissions ?? track.permissions ?? '(default)';
289
+ const resolvedCwd = task.cwd ?? track.cwd ?? workDir;
290
+ log.debug(`[task:${taskId}]`, `resolved: driver=${resolvedDriver} model=${resolvedModel} cwd=${resolvedCwd}`);
291
+ log.debug(`[task:${taskId}]`, `permissions: ${JSON.stringify(resolvedPerms)}`);
292
+ if (task.continue_from) {
293
+ log.debug(`[task:${taskId}]`, `continue_from: "${task.continue_from}"`);
294
+ }
295
+ if (task.timeout) {
296
+ log.debug(`[task:${taskId}]`, `timeout: ${task.timeout}`);
297
+ }
298
+ try {
299
+ let result;
300
+ const timeoutMs = task.timeout ? parseDuration(task.timeout) : undefined;
301
+ // Stream child stdout/stderr directly to disk in the logger's run dir
302
+ // and keep only a bounded tail in the returned TaskResult. Filenames
303
+ // mirror the existing `.stderr` naming — dots in task ids are replaced
304
+ // so hierarchical ids (e.g. `track1.task2`) map cleanly to a flat dir.
305
+ const fsSafeTaskId = taskId.replace(/\./g, '_');
306
+ const stdoutPath = resolve(log.dir, `${fsSafeTaskId}.stdout`);
307
+ const stderrPath = resolve(log.dir, `${fsSafeTaskId}.stderr`);
308
+ const runOpts = {
309
+ timeoutMs,
310
+ signal: ctx.abortController.signal,
311
+ stdoutPath,
312
+ stderrPath,
313
+ };
314
+ if (isCommandTaskConfig(task)) {
315
+ // Substitute `{{inputs.X}}` placeholders into the command
316
+ // string. Tasks with no declared inputs always produce the same
317
+ // string back (no placeholders to match). Unresolved references
318
+ // render empty — validate-raw flags undeclared references as
319
+ // errors, so the only way to land here with an unresolved is an
320
+ // optional input that had no upstream producer and no default,
321
+ // which we surface in the log.
322
+ const { text: expandedCommand, unresolved } = substituteInputs(task.command, resolvedInputs);
323
+ if (unresolved.length > 0) {
324
+ log.debug(`[task:${taskId}]`, `command placeholders rendered empty: ${unresolved.join(', ')}`);
325
+ }
326
+ log.debug(`[task:${taskId}]`, `command: ${expandedCommand}`);
327
+ result = await runCommand(expandedCommand, task.cwd ?? workDir, runOpts);
328
+ }
329
+ else {
330
+ // AI task: apply middleware chain against a structured PromptDocument.
331
+ const driverName = task.driver ?? track.driver ?? config.driver ?? 'opencode';
332
+ const driver = registry.getHandler('drivers', driverName);
333
+ // Substitute placeholders in the user-authored prompt before
334
+ // wrapping into a PromptDocument so middlewares see the
335
+ // already-resolved task text.
336
+ const { text: expandedPrompt, unresolved } = substituteInputs(task.prompt, resolvedInputs);
337
+ if (unresolved.length > 0) {
338
+ log.debug(`[task:${taskId}]`, `prompt placeholders rendered empty: ${unresolved.join(', ')}`);
339
+ }
340
+ const originalLen = expandedPrompt.length;
341
+ let doc = promptDocumentFromString(expandedPrompt);
342
+ // Prepend port-related context blocks so the model sees them
343
+ // before any middleware-added retrieval / memory blocks. Order
344
+ // matters: [Output Format] first (sets the deliverable), then
345
+ // [Inputs] (the concrete data to operate on). Empty blocks are
346
+ // filtered out — tasks without ports get no extra blocks at all.
347
+ const outputFormatBlock = renderOutputSchemaBlock(effectivePorts?.outputs);
348
+ if (outputFormatBlock) {
349
+ doc = prependContext(doc, outputFormatBlock);
350
+ }
351
+ const inputsBlock = renderInputsBlock(effectivePorts?.inputs, resolvedInputs);
352
+ if (inputsBlock) {
353
+ doc = prependContext(doc, inputsBlock);
354
+ }
355
+ const mws = task.middlewares !== undefined ? task.middlewares : track.middlewares;
356
+ if (mws && mws.length > 0) {
357
+ log.debug(`[task:${taskId}]`, `middleware chain: ${mws.map((m) => m.type).join(' → ')}`);
358
+ const mwCtx = {
359
+ task,
360
+ track,
361
+ workDir: task.cwd ?? workDir,
362
+ };
363
+ for (const mwConfig of mws) {
364
+ const mwPlugin = registry.getHandler('middlewares', mwConfig.type);
365
+ const beforeBlocks = doc.contexts.length;
366
+ const beforeLen = serializePromptDocument(doc).length;
367
+ // Prefer the structured API. Fall back to the legacy
368
+ // `enhance(string) → string` path so v0.x plugins keep
369
+ // working — that fallback loses context structure (the
370
+ // middleware's output becomes the new task body) but never
371
+ // silently drops content.
372
+ if (typeof mwPlugin.enhanceDoc === 'function') {
373
+ const next = await mwPlugin.enhanceDoc(doc, mwConfig, mwCtx);
374
+ if (!next ||
375
+ typeof next !== 'object' ||
376
+ !Array.isArray(next.contexts) ||
377
+ typeof next.task !== 'string') {
378
+ throw new Error(`middleware "${mwConfig.type}".enhanceDoc() returned a malformed PromptDocument`);
379
+ }
380
+ doc = next;
381
+ }
382
+ else if (typeof mwPlugin.enhance === 'function') {
383
+ const asString = serializePromptDocument(doc);
384
+ const next = await mwPlugin.enhance(asString, mwConfig, mwCtx);
385
+ // R3: a middleware that returns undefined / null / a non-string
386
+ // would silently corrupt the prompt. Fail loud.
387
+ if (typeof next !== 'string') {
388
+ throw new Error(`middleware "${mwConfig.type}".enhance() returned ${next === null ? 'null' : typeof next}, expected string`);
389
+ }
390
+ // Legacy fallback: collapse the returned string into a
391
+ // fresh doc. Earlier structure is folded into the string
392
+ // (serializePromptDocument just ran), so bytes the driver
393
+ // sees match the old string pipeline.
394
+ doc = { contexts: [], task: next };
395
+ }
396
+ else {
397
+ throw new Error(`middleware "${mwConfig.type}" provides neither enhanceDoc nor enhance`);
398
+ }
399
+ const afterLen = serializePromptDocument(doc).length;
400
+ const addedBlocks = doc.contexts.length - beforeBlocks;
401
+ log.debug(`[task:${taskId}]`, ` ${mwConfig.type}: ${beforeLen} → ${afterLen} chars` +
402
+ (addedBlocks > 0
403
+ ? ` (+${addedBlocks} context block${addedBlocks > 1 ? 's' : ''})`
404
+ : ''));
405
+ }
406
+ }
407
+ const prompt = serializePromptDocument(doc);
408
+ log.debug(`[task:${taskId}]`, `prompt: ${originalLen} chars (final: ${prompt.length} chars, ${doc.contexts.length} block${doc.contexts.length === 1 ? '' : 's'})`);
409
+ log.quiet(`--- prompt (final) ---\n${clip(prompt)}\n--- end prompt ---`, taskId);
410
+ // H1: hand the driver a continue_from that has already been
411
+ // qualified by dag.ts. Without this, drivers like codex/opencode/
412
+ // claude-code look up maps directly with
413
+ // the user's raw (possibly bare) string, which races whenever two
414
+ // tracks share a task name. dag.ts has the only authoritative
415
+ // resolver, so we use its precomputed answer here.
416
+ // Drivers key sessionMap/normalizedMap by fully-qualified id. buildDag
417
+ // guarantees `resolvedContinueFrom` is set for every task that has a
418
+ // `continue_from`, so if we see the bare form here something upstream
419
+ // is broken — fail loud instead of silently miskeying the lookup.
420
+ if (task.continue_from && !node.resolvedContinueFrom) {
421
+ throw new Error(`Internal: task "${taskId}" has continue_from "${task.continue_from}" ` +
422
+ `but no resolvedContinueFrom. buildDag should have qualified it.`);
423
+ }
424
+ const enrichedTask = {
425
+ ...task,
426
+ prompt,
427
+ continue_from: node.resolvedContinueFrom,
428
+ // Hand the driver the EFFECTIVE port schema rather than the
429
+ // raw task.ports. For Prompt tasks this is the one inferred
430
+ // from neighbor Commands; Command tasks are unchanged.
431
+ // Drivers that introspect ports (e.g. to annotate a system
432
+ // prompt with the I/O contract) otherwise saw `undefined`
433
+ // for every prompt and had no way to know the contract.
434
+ ports: effectivePorts,
435
+ };
436
+ const driverCtx = {
437
+ sessionMap: ctx.sessionMap,
438
+ normalizedMap: ctx.normalizedMap,
439
+ workDir: task.cwd ?? workDir,
440
+ // Structured view for drivers that want fine-grained control
441
+ // over serialization (e.g. inserting [Previous Output] between
442
+ // contexts and task). Drivers that read task.prompt see the
443
+ // default serialization and need no changes.
444
+ promptDoc: doc,
445
+ // Ports feature: resolved input values keyed by port name,
446
+ // already coerced to the declared port type. Drivers that
447
+ // need to re-substitute placeholders inside a custom envelope
448
+ // can read this and call `substituteInputs`; most drivers can
449
+ // ignore it because the engine has already expanded
450
+ // `{{inputs.X}}` into `task.prompt` upstream.
451
+ inputs: resolvedInputs,
452
+ };
453
+ const spec = await driver.buildCommand(enrichedTask, track, driverCtx);
454
+ log.debug(`[task:${taskId}]`, `driver=${driverName}`);
455
+ log.debug(`[task:${taskId}]`, `spawn args: ${JSON.stringify(spec.args)}`);
456
+ if (spec.cwd)
457
+ log.debug(`[task:${taskId}]`, `spawn cwd: ${spec.cwd}`);
458
+ if (spec.env)
459
+ log.debug(`[task:${taskId}]`, `spawn env overrides: ${Object.keys(spec.env).join(', ')}`);
460
+ if (spec.stdin)
461
+ log.debug(`[task:${taskId}]`, `spawn stdin: ${spec.stdin.length} chars`);
462
+ result = await runSpawn(spec, driver, runOpts);
463
+ }
464
+ // 6. Determine terminal status (without emitting yet — result must be complete first)
465
+ // H2: branch on failureKind so spawn errors no longer masquerade as
466
+ // timeouts. Old runners that don't set failureKind still work — we
467
+ // fall back to the historical `exitCode === -1 → timeout` heuristic so
468
+ // pre-existing third-party drivers don't regress.
469
+ let terminalStatus;
470
+ const kind = result.failureKind;
471
+ if (kind === 'timeout') {
472
+ terminalStatus = 'timeout';
473
+ }
474
+ else if (kind === 'spawn_error') {
475
+ terminalStatus = 'failed';
476
+ }
477
+ else if (kind === undefined && result.exitCode === -1) {
478
+ // Legacy path: pre-H2 driver returned -1 with no kind. Treat as
479
+ // timeout for backward compatibility (the previous behaviour).
480
+ terminalStatus = 'timeout';
481
+ }
482
+ else if (result.exitCode !== 0) {
483
+ terminalStatus = 'failed';
484
+ }
485
+ else if (task.completion) {
486
+ const plugin = registry.getHandler('completions', task.completion.type);
487
+ const completionCtx = { workDir: task.cwd ?? workDir, signal: ctx.abortController.signal };
488
+ const passed = await plugin.check(task.completion, result, completionCtx);
489
+ // R4: strict boolean check. Truthy strings/numbers used to be coerced
490
+ // to success — a check returning "ok" would let a failing task pass.
491
+ if (typeof passed !== 'boolean') {
492
+ throw new Error(`completion "${task.completion.type}".check() returned ${passed === null ? 'null' : typeof passed}, expected boolean`);
493
+ }
494
+ terminalStatus = passed ? 'success' : 'failed';
495
+ }
496
+ else {
497
+ terminalStatus = 'success';
498
+ }
499
+ // Extract declared outputs from the task's output stream. Only
500
+ // meaningful on success — a failed task's output is whatever the
501
+ // child happened to emit before exiting, and downstream tasks
502
+ // shouldn't receive partial data.
503
+ let extractedOutputs = null;
504
+ if (terminalStatus === 'success') {
505
+ const outputExtraction = extractSuccessfulOutputs({
506
+ task,
507
+ effectivePorts,
508
+ result,
509
+ });
510
+ extractedOutputs = outputExtraction.outputs;
511
+ if (task.outputs && Object.keys(task.outputs).length > 0) {
512
+ log.debug(`[task:${taskId}]`, `extracted binding outputs: ${JSON.stringify(extractedOutputs ?? {})}`);
513
+ if (outputExtraction.bindingDiagnostic) {
514
+ log.debug(`[task:${taskId}]`, outputExtraction.bindingDiagnostic);
515
+ }
516
+ }
517
+ // Prompt tasks use inferred ports (from direct-downstream Command
518
+ // inputs); Command tasks use their declared ports. Either way,
519
+ // `extractTaskOutputs` is a no-op when there are no declared
520
+ // outputs to pull, so pre-ports tasks pay nothing for this call.
521
+ if (effectivePorts?.outputs && effectivePorts.outputs.length > 0) {
522
+ log.debug(`[task:${taskId}]`, `extracted outputs: ${JSON.stringify(extractedOutputs ?? {})}` +
523
+ (isPromptTask ? ' (inferred from downstream Commands)' : ''));
524
+ if (outputExtraction.portDiagnostic) {
525
+ log.error(`[task:${taskId}]`, outputExtraction.portDiagnostic);
526
+ const note = `\n[engine] ${outputExtraction.portDiagnostic}`;
527
+ result = { ...result, stderr: result.stderr + note };
528
+ }
529
+ }
530
+ }
531
+ // Attach outputs to the result (null when task has no declared
532
+ // outputs or extraction failed entirely). Consumers of TaskResult
533
+ // — hooks, wire events, test assertions — all go through this
534
+ // one field rather than re-running extraction.
535
+ result = { ...result, outputs: extractedOutputs };
536
+ if (extractedOutputs !== null) {
537
+ ctx.outputValuesMap.set(taskId, extractedOutputs);
538
+ }
539
+ ctx.bindingDataMap.set(taskId, {
540
+ outputs: extractedOutputs,
541
+ stdout: result.stdout,
542
+ stderr: result.stderr,
543
+ normalizedOutput: result.normalizedOutput,
544
+ exitCode: result.exitCode,
545
+ });
546
+ // Store normalized text separately (in-memory) for continue_from handoff.
547
+ // R15: clip oversized values so a runaway parseResult can't accumulate
548
+ // hundreds of MB across tasks.
549
+ if (result.normalizedOutput !== null) {
550
+ const clipped = result.normalizedOutput.length > MAX_NORMALIZED_BYTES
551
+ ? result.normalizedOutput.slice(0, MAX_NORMALIZED_BYTES) +
552
+ `\n[…clipped at ${MAX_NORMALIZED_BYTES} bytes]`
553
+ : result.normalizedOutput;
554
+ ctx.normalizedMap.set(taskId, clipped);
555
+ }
556
+ // Note: stderr is already persisted by runner.ts as it streams; the
557
+ // old "write full string after the fact" block is gone — that's what
558
+ // the streaming rewrite fixed (unbounded in-memory buffering).
559
+ if (result.sessionId) {
560
+ // H1: qualified-only key.
561
+ ctx.sessionMap.set(taskId, result.sessionId);
562
+ }
563
+ // Set result and finishedAt before emitting terminal status so listeners see complete state
564
+ state.result = result;
565
+ state.finishedAt = nowISO();
566
+ ctx.setTaskStatus(taskId, terminalStatus);
567
+ // Log task outcome with relevant details
568
+ const durSec = (result.durationMs / 1000).toFixed(1);
569
+ if (terminalStatus === 'success') {
570
+ log.info(`[task:${taskId}]`, `success (${durSec}s)`);
571
+ }
572
+ else {
573
+ log.error(`[task:${taskId}]`, `${terminalStatus} exit=${result.exitCode} duration=${durSec}s`);
574
+ if (result.stderr) {
575
+ const tail = tailLines(result.stderr, 10);
576
+ log.error(`[task:${taskId}]`, `stderr tail:\n${tail}`);
577
+ }
578
+ }
579
+ // File-only: byte counts (prefer full totals from the runner over the
580
+ // bounded tail length so oversized outputs show their real size) +
581
+ // paths to the on-disk full copies.
582
+ const stdoutSize = result.stdoutBytes ?? result.stdout.length;
583
+ const stderrSize = result.stderrBytes ?? result.stderr.length;
584
+ log.debug(`[task:${taskId}]`, `stdout: ${stdoutSize} bytes, stderr: ${stderrSize} bytes`);
585
+ if (result.sessionId) {
586
+ log.debug(`[task:${taskId}]`, `sessionId: ${result.sessionId}`);
587
+ }
588
+ if (result.stdoutPath) {
589
+ log.debug(`[task:${taskId}]`, `wrote stdout: ${result.stdoutPath}`);
590
+ }
591
+ if (result.stderrPath) {
592
+ log.debug(`[task:${taskId}]`, `wrote stderr: ${result.stderrPath}`);
593
+ }
594
+ if (result.stdout) {
595
+ log.quiet(`--- stdout (${taskId}) ---\n${clip(result.stdout)}\n--- end stdout ---`, taskId);
596
+ }
597
+ if (result.stderr) {
598
+ log.quiet(`--- stderr (${taskId}) ---\n${clip(result.stderr)}\n--- end stderr ---`, taskId);
599
+ }
600
+ if (task.completion) {
601
+ log.debug(`[task:${taskId}]`, `completion check: type=${task.completion.type} result=${terminalStatus}`);
602
+ }
603
+ }
604
+ catch (err) {
605
+ const errMsg = err instanceof Error ? (err.stack ?? err.message) : String(err);
606
+ log.error(`[task:${taskId}]`, `failed before execution: ${errMsg}`);
607
+ state.result = {
608
+ exitCode: -1,
609
+ stdout: '',
610
+ stderr: errMsg,
611
+ stdoutPath: null,
612
+ stderrPath: null,
613
+ stdoutBytes: 0,
614
+ stderrBytes: errMsg.length,
615
+ durationMs: 0,
616
+ sessionId: null,
617
+ normalizedOutput: null,
618
+ // H2: Engine-level pre-execution errors (driver throw, middleware
619
+ // throw, getHandler 404) classify as spawn_error — the process never
620
+ // ran, so calling them "timeout" was actively misleading.
621
+ failureKind: 'spawn_error',
622
+ };
623
+ state.finishedAt = nowISO();
624
+ ctx.setTaskStatus(taskId, 'failed');
625
+ }
626
+ // 7. Fire hooks
627
+ const finalStatus = state.status;
628
+ try {
629
+ await ctx.fireHook(taskId, finalStatus === 'success' ? 'task_success' : 'task_failure');
630
+ }
631
+ catch (hookErr) {
632
+ log.error(`[task:${taskId}]`, `hook execution failed: ${hookErr instanceof Error ? hookErr.message : String(hookErr)}`);
633
+ }
634
+ // 8. Handle stop_all for failure states
635
+ if (finalStatus !== 'success' && ctx.getOnFailure(taskId) === 'stop_all') {
636
+ ctx.applyStopAll();
637
+ }
638
+ }
639
+ //# sourceMappingURL=task-executor.js.map