@tagma/sdk 0.6.0 → 0.6.1

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.
package/src/hooks.ts CHANGED
@@ -1,193 +1,193 @@
1
- import type { HooksConfig, HookCommand, AbortReason } from './types';
2
- import { shellArgs } from './utils';
3
-
4
- type HookEvent =
5
- | 'pipeline_start'
6
- | 'task_start'
7
- | 'task_success'
8
- | 'task_failure'
9
- | 'pipeline_complete'
10
- | 'pipeline_error';
11
-
12
- const GATE_HOOKS: ReadonlySet<HookEvent> = new Set(['pipeline_start', 'task_start']);
13
-
14
- export interface HookResult {
15
- readonly allowed: boolean; // for gate hooks: true = proceed, false = block
16
- readonly exitCode: number;
17
- }
18
-
19
- function normalizeCommands(cmd: HookCommand | undefined): readonly string[] {
20
- if (!cmd) return [];
21
- if (typeof cmd === 'string') return [cmd];
22
- return cmd;
23
- }
24
-
25
- const DEFAULT_HOOK_TIMEOUT_MS = 30_000;
26
-
27
- async function runSingleHook(
28
- command: string,
29
- context: unknown,
30
- cwd?: string,
31
- signal?: AbortSignal,
32
- timeoutMs: number = DEFAULT_HOOK_TIMEOUT_MS,
33
- ): Promise<number> {
34
- const jsonInput = JSON.stringify(context, null, 2);
35
-
36
- const controller = new AbortController();
37
- const timer = timeoutMs > 0 ? setTimeout(() => controller.abort(), timeoutMs) : null;
38
-
39
- // Wire pipeline abort signal into hook process
40
- const onAbort = () => controller.abort();
41
- if (signal) {
42
- if (signal.aborted) {
43
- controller.abort();
44
- } else {
45
- signal.addEventListener('abort', onAbort, { once: true });
46
- }
47
- }
48
-
49
- try {
50
- const proc = Bun.spawn(shellArgs(command) as string[], {
51
- stdin: 'pipe',
52
- stdout: 'pipe',
53
- stderr: 'pipe',
54
- signal: controller.signal,
55
- ...(cwd ? { cwd } : {}),
56
- });
57
-
58
- if (proc.stdin) {
59
- try {
60
- proc.stdin.write(jsonInput);
61
- proc.stdin.end();
62
- } catch {
63
- // Process may exit before reading stdin (e.g. `exit 1`), ignore EPIPE
64
- }
65
- }
66
-
67
- // Consume stdout and stderr concurrently with waiting for exit.
68
- // Sequential reads after proc.exited risk a pipe-buffer deadlock when
69
- // hook output exceeds the ~64 KB kernel buffer.
70
- const [exitCode, stdout, stderr] = await Promise.all([
71
- proc.exited,
72
- new Response(proc.stdout).text(),
73
- new Response(proc.stderr).text(),
74
- ]);
75
-
76
- if (stdout.trim()) {
77
- console.warn(`[hook: ${command}] stdout: ${stdout.trim()}`);
78
- }
79
- if (stderr.trim()) {
80
- console.error(`[hook: ${command}] stderr: ${stderr.trim()}`);
81
- }
82
-
83
- return exitCode;
84
- } catch (err) {
85
- console.error(
86
- `[hook: ${command}] spawn error: ${err instanceof Error ? err.message : String(err)}`,
87
- );
88
- return -1;
89
- } finally {
90
- if (timer) clearTimeout(timer);
91
- if (signal) signal.removeEventListener('abort', onAbort);
92
- }
93
- }
94
-
95
- export async function executeHook(
96
- hooks: HooksConfig | undefined,
97
- event: HookEvent,
98
- context: unknown,
99
- workDir?: string,
100
- signal?: AbortSignal,
101
- ): Promise<HookResult> {
102
- if (!hooks) return { allowed: true, exitCode: 0 };
103
-
104
- const commands = normalizeCommands(hooks[event]);
105
- if (commands.length === 0) return { allowed: true, exitCode: 0 };
106
-
107
- const isGate = GATE_HOOKS.has(event);
108
-
109
- for (const cmd of commands) {
110
- const exitCode = await runSingleHook(cmd, context, workDir, signal);
111
-
112
- if (isGate && exitCode === 1) {
113
- // Only exit code 1 has gate semantics (block execution)
114
- return { allowed: false, exitCode };
115
- }
116
-
117
- if (exitCode !== 0) {
118
- // Non-zero but not 1: hook itself had an error, log but don't block
119
- console.warn(`[hook: ${event}] "${cmd}" exited with code ${exitCode}`);
120
- }
121
- }
122
-
123
- return { allowed: true, exitCode: 0 };
124
- }
125
-
126
- // ═══ Context Builders ═══
127
-
128
- export interface PipelineInfo {
129
- readonly name: string;
130
- readonly run_id: string;
131
- readonly started_at: string;
132
- readonly finished_at?: string;
133
- readonly duration_ms?: number;
134
- }
135
-
136
- export interface TrackInfo {
137
- readonly id: string;
138
- readonly name: string;
139
- }
140
-
141
- export interface TaskInfo {
142
- readonly id: string;
143
- readonly name: string;
144
- readonly type: 'ai' | 'command';
145
- readonly status: string;
146
- readonly exit_code: number | null;
147
- readonly duration_ms: number | null;
148
- readonly stderr_path: string | null;
149
- readonly session_id: string | null;
150
- readonly started_at: string | null;
151
- readonly finished_at: string | null;
152
- }
153
-
154
- export function buildPipelineStartContext(pipeline: PipelineInfo) {
155
- return { event: 'pipeline_start', pipeline };
156
- }
157
-
158
- export function buildTaskContext(
159
- event: 'task_start' | 'task_success' | 'task_failure',
160
- pipeline: PipelineInfo,
161
- track: TrackInfo,
162
- task: TaskInfo,
163
- ) {
164
- return { event, pipeline, track, task };
165
- }
166
-
167
- export function buildPipelineCompleteContext(
168
- pipeline: PipelineInfo & { finished_at: string; duration_ms: number },
169
- summary: {
170
- total: number;
171
- success: number;
172
- failed: number;
173
- skipped: number;
174
- timeout: number;
175
- blocked: number;
176
- },
177
- ) {
178
- return { event: 'pipeline_complete', pipeline, summary };
179
- }
180
-
181
- export function buildPipelineErrorContext(
182
- pipeline: PipelineInfo,
183
- error: string,
184
- eventType?: string,
185
- abortReason?: AbortReason,
186
- ) {
187
- return {
188
- event: eventType ?? 'pipeline_error',
189
- pipeline,
190
- error,
191
- ...(abortReason !== undefined ? { abort_reason: abortReason } : {}),
192
- };
193
- }
1
+ import type { HooksConfig, HookCommand, AbortReason } from './types';
2
+ import { shellArgs } from './utils';
3
+
4
+ type HookEvent =
5
+ | 'pipeline_start'
6
+ | 'task_start'
7
+ | 'task_success'
8
+ | 'task_failure'
9
+ | 'pipeline_complete'
10
+ | 'pipeline_error';
11
+
12
+ const GATE_HOOKS: ReadonlySet<HookEvent> = new Set(['pipeline_start', 'task_start']);
13
+
14
+ export interface HookResult {
15
+ readonly allowed: boolean; // for gate hooks: true = proceed, false = block
16
+ readonly exitCode: number;
17
+ }
18
+
19
+ function normalizeCommands(cmd: HookCommand | undefined): readonly string[] {
20
+ if (!cmd) return [];
21
+ if (typeof cmd === 'string') return [cmd];
22
+ return cmd;
23
+ }
24
+
25
+ const DEFAULT_HOOK_TIMEOUT_MS = 30_000;
26
+
27
+ async function runSingleHook(
28
+ command: string,
29
+ context: unknown,
30
+ cwd?: string,
31
+ signal?: AbortSignal,
32
+ timeoutMs: number = DEFAULT_HOOK_TIMEOUT_MS,
33
+ ): Promise<number> {
34
+ const jsonInput = JSON.stringify(context, null, 2);
35
+
36
+ const controller = new AbortController();
37
+ const timer = timeoutMs > 0 ? setTimeout(() => controller.abort(), timeoutMs) : null;
38
+
39
+ // Wire pipeline abort signal into hook process
40
+ const onAbort = () => controller.abort();
41
+ if (signal) {
42
+ if (signal.aborted) {
43
+ controller.abort();
44
+ } else {
45
+ signal.addEventListener('abort', onAbort, { once: true });
46
+ }
47
+ }
48
+
49
+ try {
50
+ const proc = Bun.spawn(shellArgs(command) as string[], {
51
+ stdin: 'pipe',
52
+ stdout: 'pipe',
53
+ stderr: 'pipe',
54
+ signal: controller.signal,
55
+ ...(cwd ? { cwd } : {}),
56
+ });
57
+
58
+ if (proc.stdin) {
59
+ try {
60
+ proc.stdin.write(jsonInput);
61
+ proc.stdin.end();
62
+ } catch {
63
+ // Process may exit before reading stdin (e.g. `exit 1`), ignore EPIPE
64
+ }
65
+ }
66
+
67
+ // Consume stdout and stderr concurrently with waiting for exit.
68
+ // Sequential reads after proc.exited risk a pipe-buffer deadlock when
69
+ // hook output exceeds the ~64 KB kernel buffer.
70
+ const [exitCode, stdout, stderr] = await Promise.all([
71
+ proc.exited,
72
+ new Response(proc.stdout).text(),
73
+ new Response(proc.stderr).text(),
74
+ ]);
75
+
76
+ if (stdout.trim()) {
77
+ console.warn(`[hook: ${command}] stdout: ${stdout.trim()}`);
78
+ }
79
+ if (stderr.trim()) {
80
+ console.error(`[hook: ${command}] stderr: ${stderr.trim()}`);
81
+ }
82
+
83
+ return exitCode;
84
+ } catch (err) {
85
+ console.error(
86
+ `[hook: ${command}] spawn error: ${err instanceof Error ? err.message : String(err)}`,
87
+ );
88
+ return -1;
89
+ } finally {
90
+ if (timer) clearTimeout(timer);
91
+ if (signal) signal.removeEventListener('abort', onAbort);
92
+ }
93
+ }
94
+
95
+ export async function executeHook(
96
+ hooks: HooksConfig | undefined,
97
+ event: HookEvent,
98
+ context: unknown,
99
+ workDir?: string,
100
+ signal?: AbortSignal,
101
+ ): Promise<HookResult> {
102
+ if (!hooks) return { allowed: true, exitCode: 0 };
103
+
104
+ const commands = normalizeCommands(hooks[event]);
105
+ if (commands.length === 0) return { allowed: true, exitCode: 0 };
106
+
107
+ const isGate = GATE_HOOKS.has(event);
108
+
109
+ for (const cmd of commands) {
110
+ const exitCode = await runSingleHook(cmd, context, workDir, signal);
111
+
112
+ if (isGate && exitCode === 1) {
113
+ // Only exit code 1 has gate semantics (block execution)
114
+ return { allowed: false, exitCode };
115
+ }
116
+
117
+ if (exitCode !== 0) {
118
+ // Non-zero but not 1: hook itself had an error, log but don't block
119
+ console.warn(`[hook: ${event}] "${cmd}" exited with code ${exitCode}`);
120
+ }
121
+ }
122
+
123
+ return { allowed: true, exitCode: 0 };
124
+ }
125
+
126
+ // ═══ Context Builders ═══
127
+
128
+ export interface PipelineInfo {
129
+ readonly name: string;
130
+ readonly run_id: string;
131
+ readonly started_at: string;
132
+ readonly finished_at?: string;
133
+ readonly duration_ms?: number;
134
+ }
135
+
136
+ export interface TrackInfo {
137
+ readonly id: string;
138
+ readonly name: string;
139
+ }
140
+
141
+ export interface TaskInfo {
142
+ readonly id: string;
143
+ readonly name: string;
144
+ readonly type: 'ai' | 'command';
145
+ readonly status: string;
146
+ readonly exit_code: number | null;
147
+ readonly duration_ms: number | null;
148
+ readonly stderr_path: string | null;
149
+ readonly session_id: string | null;
150
+ readonly started_at: string | null;
151
+ readonly finished_at: string | null;
152
+ }
153
+
154
+ export function buildPipelineStartContext(pipeline: PipelineInfo) {
155
+ return { event: 'pipeline_start', pipeline };
156
+ }
157
+
158
+ export function buildTaskContext(
159
+ event: 'task_start' | 'task_success' | 'task_failure',
160
+ pipeline: PipelineInfo,
161
+ track: TrackInfo,
162
+ task: TaskInfo,
163
+ ) {
164
+ return { event, pipeline, track, task };
165
+ }
166
+
167
+ export function buildPipelineCompleteContext(
168
+ pipeline: PipelineInfo & { finished_at: string; duration_ms: number },
169
+ summary: {
170
+ total: number;
171
+ success: number;
172
+ failed: number;
173
+ skipped: number;
174
+ timeout: number;
175
+ blocked: number;
176
+ },
177
+ ) {
178
+ return { event: 'pipeline_complete', pipeline, summary };
179
+ }
180
+
181
+ export function buildPipelineErrorContext(
182
+ pipeline: PipelineInfo,
183
+ error: string,
184
+ eventType?: string,
185
+ abortReason?: AbortReason,
186
+ ) {
187
+ return {
188
+ event: eventType ?? 'pipeline_error',
189
+ pipeline,
190
+ error,
191
+ ...(abortReason !== undefined ? { abort_reason: abortReason } : {}),
192
+ };
193
+ }
@@ -1,49 +1,49 @@
1
- import { basename } from 'path';
2
- import type { MiddlewarePlugin, MiddlewareContext, PromptDocument } from '../types';
3
- import { validatePath } from '../utils';
4
- import { appendContext } from '../prompt-doc';
5
-
6
- export const StaticContextMiddleware: MiddlewarePlugin = {
7
- name: 'static_context',
8
- schema: {
9
- description: 'Prepend a reference file to the prompt as static context.',
10
- fields: {
11
- file: {
12
- type: 'path',
13
- required: true,
14
- description: 'Path to the reference file (relative to workDir or absolute).',
15
- placeholder: 'docs/spec.md',
16
- },
17
- label: {
18
- type: 'string',
19
- description: 'Header shown before the content. Defaults to "Reference: <basename>".',
20
- placeholder: 'Reference: spec.md',
21
- },
22
- },
23
- },
24
-
25
- async enhanceDoc(
26
- doc: PromptDocument,
27
- config: Record<string, unknown>,
28
- ctx: MiddlewareContext,
29
- ): Promise<PromptDocument> {
30
- const filePath = config.file as string;
31
- if (!filePath) throw new Error('static_context middleware: "file" is required');
32
-
33
- const safePath = validatePath(filePath, ctx.workDir);
34
- const file = Bun.file(safePath);
35
-
36
- if (!(await file.exists())) {
37
- console.warn(`static_context: file ${filePath} not found, skipping`);
38
- return doc;
39
- }
40
-
41
- const content = await file.text();
42
- const label = (config.label as string) ?? `Reference: ${basename(filePath)}`;
43
-
44
- // Append a labeled context block; the engine's serializer joins blocks
45
- // with blank lines and places the task last. No [Task] header here —
46
- // that framing is the driver's concern (e.g. opencode's agent_profile).
47
- return appendContext(doc, { label, content });
48
- },
49
- };
1
+ import { basename } from 'path';
2
+ import type { MiddlewarePlugin, MiddlewareContext, PromptDocument } from '../types';
3
+ import { validatePath } from '../utils';
4
+ import { appendContext } from '../prompt-doc';
5
+
6
+ export const StaticContextMiddleware: MiddlewarePlugin = {
7
+ name: 'static_context',
8
+ schema: {
9
+ description: 'Prepend a reference file to the prompt as static context.',
10
+ fields: {
11
+ file: {
12
+ type: 'path',
13
+ required: true,
14
+ description: 'Path to the reference file (relative to workDir or absolute).',
15
+ placeholder: 'docs/spec.md',
16
+ },
17
+ label: {
18
+ type: 'string',
19
+ description: 'Header shown before the content. Defaults to "Reference: <basename>".',
20
+ placeholder: 'Reference: spec.md',
21
+ },
22
+ },
23
+ },
24
+
25
+ async enhanceDoc(
26
+ doc: PromptDocument,
27
+ config: Record<string, unknown>,
28
+ ctx: MiddlewareContext,
29
+ ): Promise<PromptDocument> {
30
+ const filePath = config.file as string;
31
+ if (!filePath) throw new Error('static_context middleware: "file" is required');
32
+
33
+ const safePath = validatePath(filePath, ctx.workDir);
34
+ const file = Bun.file(safePath);
35
+
36
+ if (!(await file.exists())) {
37
+ console.warn(`static_context: file ${filePath} not found, skipping`);
38
+ return doc;
39
+ }
40
+
41
+ const content = await file.text();
42
+ const label = (config.label as string) ?? `Reference: ${basename(filePath)}`;
43
+
44
+ // Append a labeled context block; the engine's serializer joins blocks
45
+ // with blank lines and places the task last. No [Task] header here —
46
+ // that framing is the driver's concern (e.g. opencode's agent_profile).
47
+ return appendContext(doc, { label, content });
48
+ },
49
+ };