@tagma/sdk 0.7.4 → 0.7.5

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