@tagma/sdk 0.1.3 → 0.1.4

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,138 +1,138 @@
1
- import type { HooksConfig, HookCommand } from './types';
2
- import { shellArgs } from './utils';
3
-
4
- type HookEvent =
5
- | 'pipeline_start' | 'task_start' | 'task_success'
6
- | 'task_failure' | 'pipeline_complete' | 'pipeline_error';
7
-
8
- const GATE_HOOKS: ReadonlySet<HookEvent> = new Set(['pipeline_start', 'task_start']);
9
-
10
- export interface HookResult {
11
- readonly allowed: boolean; // for gate hooks: true = proceed, false = block
12
- readonly exitCode: number;
13
- }
14
-
15
- function normalizeCommands(cmd: HookCommand | undefined): readonly string[] {
16
- if (!cmd) return [];
17
- if (typeof cmd === 'string') return [cmd];
18
- return cmd;
19
- }
20
-
21
- async function runSingleHook(command: string, context: unknown, cwd?: string): Promise<number> {
22
- const jsonInput = JSON.stringify(context, null, 2);
23
-
24
- const proc = Bun.spawn(shellArgs(command) as string[], {
25
- stdin: 'pipe',
26
- stdout: 'pipe',
27
- stderr: 'pipe',
28
- ...(cwd ? { cwd } : {}),
29
- });
30
-
31
- if (proc.stdin) {
32
- try {
33
- proc.stdin.write(jsonInput);
34
- proc.stdin.end();
35
- } catch {
36
- // Process may exit before reading stdin (e.g. `exit 1`), ignore EPIPE
37
- }
38
- }
39
-
40
- const exitCode = await proc.exited;
41
- const stderr = await new Response(proc.stderr).text();
42
-
43
- if (stderr.trim()) {
44
- console.error(`[hook: ${command}] stderr: ${stderr.trim()}`);
45
- }
46
-
47
- return exitCode;
48
- }
49
-
50
- export async function executeHook(
51
- hooks: HooksConfig | undefined,
52
- event: HookEvent,
53
- context: unknown,
54
- workDir?: string,
55
- ): Promise<HookResult> {
56
- if (!hooks) return { allowed: true, exitCode: 0 };
57
-
58
- const commands = normalizeCommands(hooks[event]);
59
- if (commands.length === 0) return { allowed: true, exitCode: 0 };
60
-
61
- const isGate = GATE_HOOKS.has(event);
62
-
63
- for (const cmd of commands) {
64
- const exitCode = await runSingleHook(cmd, context, workDir);
65
-
66
- if (isGate && exitCode === 1) {
67
- // Only exit code 1 has gate semantics (block execution)
68
- return { allowed: false, exitCode };
69
- }
70
-
71
- if (exitCode !== 0) {
72
- // Non-zero but not 1: hook itself had an error, log but don't block
73
- console.warn(`[hook: ${event}] "${cmd}" exited with code ${exitCode}`);
74
- }
75
- }
76
-
77
- return { allowed: true, exitCode: 0 };
78
- }
79
-
80
- // ═══ Context Builders ═══
81
-
82
- export interface PipelineInfo {
83
- readonly name: string;
84
- readonly run_id: string;
85
- readonly started_at: string;
86
- readonly finished_at?: string;
87
- readonly duration_ms?: number;
88
- }
89
-
90
- export interface TrackInfo {
91
- readonly id: string;
92
- readonly name: string;
93
- }
94
-
95
- export interface TaskInfo {
96
- readonly id: string;
97
- readonly name: string;
98
- readonly type: 'ai' | 'command';
99
- readonly status: string;
100
- readonly exit_code: number | null;
101
- readonly duration_ms: number | null;
102
- readonly output_path: string | null;
103
- readonly stderr_path: string | null;
104
- readonly session_id: string | null;
105
- readonly started_at: string | null;
106
- readonly finished_at: string | null;
107
- }
108
-
109
- export function buildPipelineStartContext(pipeline: PipelineInfo) {
110
- return { event: 'pipeline_start', pipeline };
111
- }
112
-
113
- export function buildTaskContext(
114
- event: 'task_start' | 'task_success' | 'task_failure',
115
- pipeline: PipelineInfo,
116
- track: TrackInfo,
117
- task: TaskInfo,
118
- ) {
119
- return { event, pipeline, track, task };
120
- }
121
-
122
- export function buildPipelineCompleteContext(
123
- pipeline: PipelineInfo & { finished_at: string; duration_ms: number },
124
- summary: {
125
- total: number; success: number; failed: number;
126
- skipped: number; timeout: number; blocked: number;
127
- },
128
- ) {
129
- return { event: 'pipeline_complete', pipeline, summary };
130
- }
131
-
132
- export function buildPipelineErrorContext(
133
- pipeline: PipelineInfo,
134
- error: string,
135
- eventType?: string,
136
- ) {
137
- return { event: eventType ?? 'pipeline_error', pipeline, error };
138
- }
1
+ import type { HooksConfig, HookCommand } from './types';
2
+ import { shellArgs } from './utils';
3
+
4
+ type HookEvent =
5
+ | 'pipeline_start' | 'task_start' | 'task_success'
6
+ | 'task_failure' | 'pipeline_complete' | 'pipeline_error';
7
+
8
+ const GATE_HOOKS: ReadonlySet<HookEvent> = new Set(['pipeline_start', 'task_start']);
9
+
10
+ export interface HookResult {
11
+ readonly allowed: boolean; // for gate hooks: true = proceed, false = block
12
+ readonly exitCode: number;
13
+ }
14
+
15
+ function normalizeCommands(cmd: HookCommand | undefined): readonly string[] {
16
+ if (!cmd) return [];
17
+ if (typeof cmd === 'string') return [cmd];
18
+ return cmd;
19
+ }
20
+
21
+ async function runSingleHook(command: string, context: unknown, cwd?: string): Promise<number> {
22
+ const jsonInput = JSON.stringify(context, null, 2);
23
+
24
+ const proc = Bun.spawn(shellArgs(command) as string[], {
25
+ stdin: 'pipe',
26
+ stdout: 'pipe',
27
+ stderr: 'pipe',
28
+ ...(cwd ? { cwd } : {}),
29
+ });
30
+
31
+ if (proc.stdin) {
32
+ try {
33
+ proc.stdin.write(jsonInput);
34
+ proc.stdin.end();
35
+ } catch {
36
+ // Process may exit before reading stdin (e.g. `exit 1`), ignore EPIPE
37
+ }
38
+ }
39
+
40
+ const exitCode = await proc.exited;
41
+ const stderr = await new Response(proc.stderr).text();
42
+
43
+ if (stderr.trim()) {
44
+ console.error(`[hook: ${command}] stderr: ${stderr.trim()}`);
45
+ }
46
+
47
+ return exitCode;
48
+ }
49
+
50
+ export async function executeHook(
51
+ hooks: HooksConfig | undefined,
52
+ event: HookEvent,
53
+ context: unknown,
54
+ workDir?: string,
55
+ ): Promise<HookResult> {
56
+ if (!hooks) return { allowed: true, exitCode: 0 };
57
+
58
+ const commands = normalizeCommands(hooks[event]);
59
+ if (commands.length === 0) return { allowed: true, exitCode: 0 };
60
+
61
+ const isGate = GATE_HOOKS.has(event);
62
+
63
+ for (const cmd of commands) {
64
+ const exitCode = await runSingleHook(cmd, context, workDir);
65
+
66
+ if (isGate && exitCode === 1) {
67
+ // Only exit code 1 has gate semantics (block execution)
68
+ return { allowed: false, exitCode };
69
+ }
70
+
71
+ if (exitCode !== 0) {
72
+ // Non-zero but not 1: hook itself had an error, log but don't block
73
+ console.warn(`[hook: ${event}] "${cmd}" exited with code ${exitCode}`);
74
+ }
75
+ }
76
+
77
+ return { allowed: true, exitCode: 0 };
78
+ }
79
+
80
+ // ═══ Context Builders ═══
81
+
82
+ export interface PipelineInfo {
83
+ readonly name: string;
84
+ readonly run_id: string;
85
+ readonly started_at: string;
86
+ readonly finished_at?: string;
87
+ readonly duration_ms?: number;
88
+ }
89
+
90
+ export interface TrackInfo {
91
+ readonly id: string;
92
+ readonly name: string;
93
+ }
94
+
95
+ export interface TaskInfo {
96
+ readonly id: string;
97
+ readonly name: string;
98
+ readonly type: 'ai' | 'command';
99
+ readonly status: string;
100
+ readonly exit_code: number | null;
101
+ readonly duration_ms: number | null;
102
+ readonly output_path: string | null;
103
+ readonly stderr_path: string | null;
104
+ readonly session_id: string | null;
105
+ readonly started_at: string | null;
106
+ readonly finished_at: string | null;
107
+ }
108
+
109
+ export function buildPipelineStartContext(pipeline: PipelineInfo) {
110
+ return { event: 'pipeline_start', pipeline };
111
+ }
112
+
113
+ export function buildTaskContext(
114
+ event: 'task_start' | 'task_success' | 'task_failure',
115
+ pipeline: PipelineInfo,
116
+ track: TrackInfo,
117
+ task: TaskInfo,
118
+ ) {
119
+ return { event, pipeline, track, task };
120
+ }
121
+
122
+ export function buildPipelineCompleteContext(
123
+ pipeline: PipelineInfo & { finished_at: string; duration_ms: number },
124
+ summary: {
125
+ total: number; success: number; failed: number;
126
+ skipped: number; timeout: number; blocked: number;
127
+ },
128
+ ) {
129
+ return { event: 'pipeline_complete', pipeline, summary };
130
+ }
131
+
132
+ export function buildPipelineErrorContext(
133
+ pipeline: PipelineInfo,
134
+ error: string,
135
+ eventType?: string,
136
+ ) {
137
+ return { event: eventType ?? 'pipeline_error', pipeline, error };
138
+ }
package/src/logger.ts CHANGED
@@ -1,100 +1,107 @@
1
- import { resolve, dirname } from 'node:path';
2
- import { mkdirSync, appendFileSync, writeFileSync } from 'node:fs';
3
-
4
- /**
5
- * Dual-channel logger.
6
- *
7
- * - `info/warn/error` → console AND file (brief, user-visible events)
8
- * - `debug` → file ONLY (verbose diagnostics)
9
- * - `section` → file ONLY (visual separators)
10
- * - `quiet` → file ONLY (bulk payload like full stdout dumps)
11
- *
12
- * Log file path: <workDir>/tmp/pipeline.log (one file per pipeline run,
13
- * truncated on construction).
14
- */
15
- export class Logger {
16
- private readonly filePath: string;
17
-
18
- constructor(workDir: string, runId: string) {
19
- this.filePath = resolve(workDir, 'tmp', 'pipeline.log');
20
- mkdirSync(dirname(this.filePath), { recursive: true });
21
- writeFileSync(
22
- this.filePath,
23
- `# Pipeline run ${runId} @ ${new Date().toISOString()}\n` +
24
- `# Host: ${process.platform} ${process.arch} Bun: ${process.versions.bun ?? 'n/a'}\n` +
25
- `# Work dir: ${workDir}\n\n`,
26
- );
27
- }
28
-
29
- info(prefix: string, message: string): void {
30
- const line = `${timestamp()} ${prefix} ${message}`;
31
- console.log(line);
32
- this.append(line);
33
- }
34
-
35
- warn(prefix: string, message: string): void {
36
- const line = `${timestamp()} ${prefix} WARN: ${message}`;
37
- console.warn(line);
38
- this.append(line);
39
- }
40
-
41
- error(prefix: string, message: string): void {
42
- const line = `${timestamp()} ${prefix} ERROR: ${message}`;
43
- console.error(line);
44
- this.append(line);
45
- }
46
-
47
- /** File-only diagnostic log line. */
48
- debug(prefix: string, message: string): void {
49
- this.append(`${timestamp()} ${prefix} DEBUG: ${message}`);
50
- }
51
-
52
- /** File-only visual separator with title. */
53
- section(title: string): void {
54
- this.append(`\n━━━ ${title} ━━━`);
55
- }
56
-
57
- /** File-only bulk payload (e.g. full stdout / stderr dumps). */
58
- quiet(message: string): void {
59
- this.append(message);
60
- }
61
-
62
- private append(line: string): void {
63
- try {
64
- appendFileSync(this.filePath, line.endsWith('\n') ? line : line + '\n');
65
- } catch {
66
- // Swallow log write failures; engine correctness shouldn't depend on logging.
67
- }
68
- }
69
-
70
- get path(): string {
71
- return this.filePath;
72
- }
73
- }
74
-
75
- function timestamp(): string {
76
- const d = new Date();
77
- const hh = String(d.getHours()).padStart(2, '0');
78
- const mm = String(d.getMinutes()).padStart(2, '0');
79
- const ss = String(d.getSeconds()).padStart(2, '0');
80
- const ms = String(d.getMilliseconds()).padStart(3, '0');
81
- return `${hh}:${mm}:${ss}.${ms}`;
82
- }
83
-
84
- /** Return the last `n` non-empty lines of `text`, joined with newlines. */
85
- export function tailLines(text: string, n: number): string {
86
- if (!text) return '';
87
- const lines = text.split(/\r?\n/).filter(l => l.length > 0);
88
- return lines.slice(-n).join('\n');
89
- }
90
-
91
- /**
92
- * Truncate a blob to at most `maxBytes` UTF-8 bytes for log embedding,
93
- * appending a marker when truncation occurred.
94
- */
95
- export function clip(text: string, maxBytes = 16 * 1024): string {
96
- if (!text) return '';
97
- if (text.length <= maxBytes) return text;
98
- const omitted = text.length - maxBytes;
99
- return text.slice(0, maxBytes) + `\n…[truncated ${omitted} chars]`;
100
- }
1
+ import { resolve, dirname } from 'node:path';
2
+ import { mkdirSync, appendFileSync, writeFileSync } from 'node:fs';
3
+
4
+ /**
5
+ * Dual-channel logger.
6
+ *
7
+ * - `info/warn/error` → console AND file (brief, user-visible events)
8
+ * - `debug` → file ONLY (verbose diagnostics)
9
+ * - `section` → file ONLY (visual separators)
10
+ * - `quiet` → file ONLY (bulk payload like full stdout dumps)
11
+ *
12
+ * Log file path: <workDir>/tmp/pipeline.log (one file per pipeline run,
13
+ * truncated on construction).
14
+ */
15
+ export class Logger {
16
+ private readonly filePath: string;
17
+ private readonly runDir: string;
18
+
19
+ constructor(workDir: string, runId: string) {
20
+ this.runDir = resolve(workDir, 'logs', runId);
21
+ this.filePath = resolve(this.runDir, 'pipeline.log');
22
+ mkdirSync(dirname(this.filePath), { recursive: true });
23
+ writeFileSync(
24
+ this.filePath,
25
+ `# Pipeline run ${runId} @ ${new Date().toISOString()}\n` +
26
+ `# Host: ${process.platform} ${process.arch} Bun: ${process.versions.bun ?? 'n/a'}\n` +
27
+ `# Work dir: ${workDir}\n\n`,
28
+ );
29
+ }
30
+
31
+ info(prefix: string, message: string): void {
32
+ const line = `${timestamp()} ${prefix} ${message}`;
33
+ console.log(line);
34
+ this.append(line);
35
+ }
36
+
37
+ warn(prefix: string, message: string): void {
38
+ const line = `${timestamp()} ${prefix} WARN: ${message}`;
39
+ console.warn(line);
40
+ this.append(line);
41
+ }
42
+
43
+ error(prefix: string, message: string): void {
44
+ const line = `${timestamp()} ${prefix} ERROR: ${message}`;
45
+ console.error(line);
46
+ this.append(line);
47
+ }
48
+
49
+ /** File-only diagnostic log line. */
50
+ debug(prefix: string, message: string): void {
51
+ this.append(`${timestamp()} ${prefix} DEBUG: ${message}`);
52
+ }
53
+
54
+ /** File-only visual separator with title. */
55
+ section(title: string): void {
56
+ this.append(`\n━━━ ${title} ━━━`);
57
+ }
58
+
59
+ /** File-only bulk payload (e.g. full stdout / stderr dumps). */
60
+ quiet(message: string): void {
61
+ this.append(message);
62
+ }
63
+
64
+ private append(line: string): void {
65
+ try {
66
+ appendFileSync(this.filePath, line.endsWith('\n') ? line : line + '\n');
67
+ } catch {
68
+ // Swallow log write failures; engine correctness shouldn't depend on logging.
69
+ }
70
+ }
71
+
72
+ get path(): string {
73
+ return this.filePath;
74
+ }
75
+
76
+ /** Directory that holds all artifacts for this run (pipeline.log, *.stderr, etc.). */
77
+ get dir(): string {
78
+ return this.runDir;
79
+ }
80
+ }
81
+
82
+ function timestamp(): string {
83
+ const d = new Date();
84
+ const hh = String(d.getHours()).padStart(2, '0');
85
+ const mm = String(d.getMinutes()).padStart(2, '0');
86
+ const ss = String(d.getSeconds()).padStart(2, '0');
87
+ const ms = String(d.getMilliseconds()).padStart(3, '0');
88
+ return `${hh}:${mm}:${ss}.${ms}`;
89
+ }
90
+
91
+ /** Return the last `n` non-empty lines of `text`, joined with newlines. */
92
+ export function tailLines(text: string, n: number): string {
93
+ if (!text) return '';
94
+ const lines = text.split(/\r?\n/).filter(l => l.length > 0);
95
+ return lines.slice(-n).join('\n');
96
+ }
97
+
98
+ /**
99
+ * Truncate a blob to at most `maxBytes` UTF-8 bytes for log embedding,
100
+ * appending a marker when truncation occurred.
101
+ */
102
+ export function clip(text: string, maxBytes = 16 * 1024): string {
103
+ if (!text) return '';
104
+ if (text.length <= maxBytes) return text;
105
+ const omitted = text.length - maxBytes;
106
+ return text.slice(0, maxBytes) + `\n…[truncated ${omitted} chars]`;
107
+ }
@@ -1,29 +1,29 @@
1
- import { basename } from 'path';
2
- import type { MiddlewarePlugin, MiddlewareContext } from '../types';
3
- import { validatePath } from '../utils';
4
-
5
- export const StaticContextMiddleware: MiddlewarePlugin = {
6
- name: 'static_context',
7
-
8
- async enhance(
9
- prompt: string,
10
- config: Record<string, unknown>,
11
- ctx: MiddlewareContext,
12
- ): Promise<string> {
13
- const filePath = config.file as string;
14
- if (!filePath) throw new Error('static_context middleware: "file" is required');
15
-
16
- const safePath = validatePath(filePath, ctx.workDir);
17
- const file = Bun.file(safePath);
18
-
19
- if (!(await file.exists())) {
20
- console.warn(`static_context: file ${filePath} not found, skipping`);
21
- return prompt;
22
- }
23
-
24
- const content = await file.text();
25
- const label = (config.label as string) ?? `Reference: ${basename(filePath)}`;
26
-
27
- return `[${label}]\n${content}\n\n[Task]\n${prompt}`;
28
- },
29
- };
1
+ import { basename } from 'path';
2
+ import type { MiddlewarePlugin, MiddlewareContext } from '../types';
3
+ import { validatePath } from '../utils';
4
+
5
+ export const StaticContextMiddleware: MiddlewarePlugin = {
6
+ name: 'static_context',
7
+
8
+ async enhance(
9
+ prompt: string,
10
+ config: Record<string, unknown>,
11
+ ctx: MiddlewareContext,
12
+ ): Promise<string> {
13
+ const filePath = config.file as string;
14
+ if (!filePath) throw new Error('static_context middleware: "file" is required');
15
+
16
+ const safePath = validatePath(filePath, ctx.workDir);
17
+ const file = Bun.file(safePath);
18
+
19
+ if (!(await file.exists())) {
20
+ console.warn(`static_context: file ${filePath} not found, skipping`);
21
+ return prompt;
22
+ }
23
+
24
+ const content = await file.text();
25
+ const label = (config.label as string) ?? `Reference: ${basename(filePath)}`;
26
+
27
+ return `[${label}]\n${content}\n\n[Task]\n${prompt}`;
28
+ },
29
+ };