@tagma/sdk 0.7.4 → 0.7.6

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