@tagma/sdk 0.1.2

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/README.md ADDED
@@ -0,0 +1 @@
1
+ # tagma-sdk
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@tagma/sdk",
3
+ "version": "0.1.2",
4
+ "type": "module",
5
+ "workspaces": [
6
+ "plugins/*"
7
+ ],
8
+ "main": "./src/sdk.ts",
9
+ "exports": {
10
+ ".": "./src/sdk.ts"
11
+ },
12
+ "files": [
13
+ "src"
14
+ ],
15
+ "scripts": {
16
+ "test": "bun test",
17
+ "release": "bun scripts/release.ts",
18
+ "release:publish": "bun scripts/release.ts --publish"
19
+ },
20
+ "dependencies": {
21
+ "js-yaml": "^4.1.0",
22
+ "chokidar": "^4.0.0",
23
+ "@tagma/types": "0.1.2"
24
+ },
25
+ "devDependencies": {
26
+ "@types/js-yaml": "^4.0.9",
27
+ "bun-types": "latest",
28
+ "typescript": "^6.0.2",
29
+ "@tagma/driver-codex": "0.1.2",
30
+ "@tagma/driver-opencode": "0.1.2"
31
+ }
32
+ }
@@ -0,0 +1,117 @@
1
+ import * as readline from 'readline';
2
+ import type { ApprovalGateway, ApprovalRequest } from '../approval';
3
+
4
+ // ═══ CLI Stdin Adapter ═══
5
+ //
6
+ // Subscribes to the gateway's 'requested' events, prompts the user on stdout,
7
+ // reads a line from stdin, and calls gateway.resolve(). Handles at most one
8
+ // prompt at a time — additional requests queue up.
9
+
10
+ export interface StdinApprovalAdapter {
11
+ readonly detach: () => void;
12
+ }
13
+
14
+ export function attachStdinApprovalAdapter(gateway: ApprovalGateway): StdinApprovalAdapter {
15
+ const queue: ApprovalRequest[] = [];
16
+ let processing = false;
17
+ let rl: readline.Interface | null = null;
18
+
19
+ function ensureReadline(): readline.Interface {
20
+ if (!rl) {
21
+ rl = readline.createInterface({ input: process.stdin, terminal: false });
22
+ }
23
+ return rl;
24
+ }
25
+
26
+ function readOneLine(): Promise<string> {
27
+ return new Promise((resolvePromise) => {
28
+ const reader = ensureReadline();
29
+ const handler = (line: string): void => {
30
+ reader.off('line', handler);
31
+ resolvePromise(line);
32
+ };
33
+ reader.on('line', handler);
34
+ });
35
+ }
36
+
37
+ async function processNext(): Promise<void> {
38
+ if (processing) return;
39
+ processing = true;
40
+ try {
41
+ while (queue.length > 0) {
42
+ const req = queue.shift()!;
43
+ // If the request was already resolved by another path while queued, skip it.
44
+ if (!gateway.pending().some((p) => p.id === req.id)) continue;
45
+
46
+ const optionsStr = req.options.join(' / ');
47
+ process.stdout.write(
48
+ `\n[APPROVAL REQUIRED] ${req.message}\n` +
49
+ ` id: ${req.id}\n` +
50
+ ` task: ${req.taskId}${req.trackId ? ` (track: ${req.trackId})` : ''}\n` +
51
+ ` options: ${optionsStr}\n` +
52
+ ` > `,
53
+ );
54
+
55
+ const input = (await readOneLine()).trim().toLowerCase();
56
+
57
+ const approveAliases = new Set(['approve', 'yes', 'y', 'ok', 'true', '1']);
58
+ const rejectAliases = new Set(['reject', 'no', 'n', 'deny', 'false', '0']);
59
+ const matchedOption = req.options.find((o) => o.toLowerCase() === input);
60
+
61
+ if (matchedOption) {
62
+ const isReject = rejectAliases.has(matchedOption.toLowerCase());
63
+ gateway.resolve(req.id, {
64
+ outcome: isReject ? 'rejected' : 'approved',
65
+ choice: matchedOption,
66
+ actor: 'cli',
67
+ });
68
+ } else if (approveAliases.has(input)) {
69
+ gateway.resolve(req.id, { outcome: 'approved', choice: input, actor: 'cli' });
70
+ } else if (rejectAliases.has(input)) {
71
+ gateway.resolve(req.id, {
72
+ outcome: 'rejected',
73
+ choice: input,
74
+ actor: 'cli',
75
+ reason: 'user rejected via CLI',
76
+ });
77
+ } else {
78
+ process.stdout.write(` unrecognized input "${input}" — treating as rejection\n`);
79
+ gateway.resolve(req.id, {
80
+ outcome: 'rejected',
81
+ actor: 'cli',
82
+ reason: `unrecognized CLI input: ${input}`,
83
+ });
84
+ }
85
+ }
86
+ } finally {
87
+ processing = false;
88
+ }
89
+ }
90
+
91
+ const unsubscribe = gateway.subscribe((event) => {
92
+ switch (event.type) {
93
+ case 'requested':
94
+ queue.push(event.request);
95
+ void processNext();
96
+ return;
97
+ case 'resolved':
98
+ case 'expired':
99
+ case 'aborted': {
100
+ // Drop from queue if it's still waiting its turn.
101
+ const idx = queue.findIndex((r) => r.id === event.request.id);
102
+ if (idx >= 0) queue.splice(idx, 1);
103
+ return;
104
+ }
105
+ }
106
+ });
107
+
108
+ return {
109
+ detach: () => {
110
+ unsubscribe();
111
+ if (rl) {
112
+ rl.close();
113
+ rl = null;
114
+ }
115
+ },
116
+ };
117
+ }
@@ -0,0 +1,144 @@
1
+ import type { ApprovalGateway, ApprovalEvent } from '../approval';
2
+
3
+ // ═══ WebSocket Approval Adapter ═══
4
+ //
5
+ // Bridges the ApprovalGateway to WebSocket clients (e.g. a frontend UI).
6
+ // Mirrors the stdin-approval adapter pattern: subscribe to gateway events,
7
+ // forward them as JSON to all connected clients, and call gateway.resolve()
8
+ // when a client sends a resolution message.
9
+ //
10
+ // Protocol — server → client:
11
+ // { type: 'pending', requests: ApprovalRequest[] } ← sent on connect
12
+ // { type: 'approval_requested', request: ApprovalRequest }
13
+ // { type: 'approval_resolved', request: ApprovalRequest, decision: ApprovalDecision }
14
+ // { type: 'approval_expired', request: ApprovalRequest }
15
+ // { type: 'approval_aborted', request: ApprovalRequest, reason: string }
16
+ //
17
+ // Protocol — client → server:
18
+ // { type: 'resolve', approvalId: string, outcome: 'approved'|'rejected',
19
+ // choice?: string, actor?: string, reason?: string }
20
+
21
+ export interface WebSocketApprovalAdapterOptions {
22
+ port?: number; // default: 3000
23
+ hostname?: string; // default: 'localhost'
24
+ }
25
+
26
+ export interface WebSocketApprovalAdapter {
27
+ readonly port: number;
28
+ readonly detach: () => void;
29
+ }
30
+
31
+ export function attachWebSocketApprovalAdapter(
32
+ gateway: ApprovalGateway,
33
+ options: WebSocketApprovalAdapterOptions = {},
34
+ ): WebSocketApprovalAdapter {
35
+ const port = options.port ?? 3000;
36
+ const hostname = options.hostname ?? 'localhost';
37
+
38
+ const clients = new Set<import('bun').ServerWebSocket<unknown>>();
39
+
40
+ function broadcast(msg: unknown): void {
41
+ const text = JSON.stringify(msg);
42
+ for (const ws of clients) {
43
+ ws.send(text);
44
+ }
45
+ }
46
+
47
+ const unsubscribe = gateway.subscribe((event: ApprovalEvent) => {
48
+ switch (event.type) {
49
+ case 'requested':
50
+ broadcast({ type: 'approval_requested', request: event.request });
51
+ break;
52
+ case 'resolved':
53
+ broadcast({ type: 'approval_resolved', request: event.request, decision: event.decision });
54
+ break;
55
+ case 'expired':
56
+ broadcast({ type: 'approval_expired', request: event.request });
57
+ break;
58
+ case 'aborted':
59
+ broadcast({ type: 'approval_aborted', request: event.request, reason: event.reason });
60
+ break;
61
+ }
62
+ });
63
+
64
+ const server = Bun.serve({
65
+ port,
66
+ hostname,
67
+
68
+ fetch(req, server) {
69
+ if (server.upgrade(req)) return undefined;
70
+ return new Response('tagma-sdk WebSocket approval endpoint', { status: 426 });
71
+ },
72
+
73
+ websocket: {
74
+ open(ws) {
75
+ clients.add(ws);
76
+ // Sync current pending approvals to newly connected client.
77
+ ws.send(JSON.stringify({ type: 'pending', requests: gateway.pending() }));
78
+ },
79
+
80
+ message(ws, raw) {
81
+ let msg: unknown;
82
+ try {
83
+ msg = JSON.parse(typeof raw === 'string' ? raw : raw.toString());
84
+ } catch {
85
+ ws.send(JSON.stringify({ type: 'error', message: 'invalid JSON' }));
86
+ return;
87
+ }
88
+
89
+ if (!isResolveMessage(msg)) {
90
+ ws.send(JSON.stringify({ type: 'error', message: 'unknown message type' }));
91
+ return;
92
+ }
93
+
94
+ const ok = gateway.resolve(msg.approvalId, {
95
+ outcome: msg.outcome,
96
+ choice: msg.choice,
97
+ actor: msg.actor ?? 'websocket',
98
+ reason: msg.reason,
99
+ });
100
+
101
+ if (!ok) {
102
+ ws.send(JSON.stringify({
103
+ type: 'error',
104
+ message: `approval ${msg.approvalId} not found or already resolved`,
105
+ }));
106
+ }
107
+ },
108
+
109
+ close(ws) {
110
+ clients.delete(ws);
111
+ },
112
+ },
113
+ });
114
+
115
+ return {
116
+ port: server.port,
117
+ detach() {
118
+ unsubscribe();
119
+ clients.clear();
120
+ server.stop(true);
121
+ },
122
+ };
123
+ }
124
+
125
+ // ── Type guard ──
126
+
127
+ interface ResolveMessage {
128
+ type: 'resolve';
129
+ approvalId: string;
130
+ outcome: 'approved' | 'rejected';
131
+ choice?: string;
132
+ actor?: string;
133
+ reason?: string;
134
+ }
135
+
136
+ function isResolveMessage(v: unknown): v is ResolveMessage {
137
+ if (typeof v !== 'object' || v === null) return false;
138
+ const m = v as Record<string, unknown>;
139
+ return (
140
+ m['type'] === 'resolve' &&
141
+ typeof m['approvalId'] === 'string' &&
142
+ (m['outcome'] === 'approved' || m['outcome'] === 'rejected')
143
+ );
144
+ }
@@ -0,0 +1,125 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { nowISO } from './utils';
3
+
4
+ // Approval types (ApprovalRequest, ApprovalDecision, ApprovalOutcome,
5
+ // ApprovalEvent, ApprovalListener, ApprovalGateway) live in the shared
6
+ // @tagma/types package so trigger plugins can import them without
7
+ // depending on the engine's runtime implementation. This module keeps
8
+ // only the in-memory implementation.
9
+ import type {
10
+ ApprovalRequest, ApprovalDecision, ApprovalEvent, ApprovalListener, ApprovalGateway,
11
+ } from '@tagma/types';
12
+
13
+ // Re-export for existing engine-side consumers that import from this file.
14
+ export type {
15
+ ApprovalRequest, ApprovalDecision, ApprovalOutcome, ApprovalEvent,
16
+ ApprovalListener, ApprovalGateway,
17
+ } from '@tagma/types';
18
+
19
+ // ═══ Default In-Memory Implementation ═══
20
+
21
+ interface PendingEntry {
22
+ readonly request: ApprovalRequest;
23
+ readonly settle: (decision: ApprovalDecision) => void;
24
+ readonly timer: ReturnType<typeof setTimeout> | null;
25
+ }
26
+
27
+ export class InMemoryApprovalGateway implements ApprovalGateway {
28
+ private readonly pendingMap = new Map<string, PendingEntry>();
29
+ private readonly listeners = new Set<ApprovalListener>();
30
+
31
+ request(
32
+ req: Omit<ApprovalRequest, 'id' | 'createdAt' | 'options'> & { options?: readonly string[] },
33
+ ): Promise<ApprovalDecision> {
34
+ const full: ApprovalRequest = {
35
+ id: randomUUID(),
36
+ createdAt: nowISO(),
37
+ taskId: req.taskId,
38
+ trackId: req.trackId,
39
+ message: req.message,
40
+ options: req.options && req.options.length > 0 ? req.options : ['approve', 'reject'],
41
+ timeoutMs: req.timeoutMs,
42
+ metadata: req.metadata,
43
+ };
44
+
45
+ return new Promise<ApprovalDecision>((resolvePromise) => {
46
+ let timer: ReturnType<typeof setTimeout> | null = null;
47
+ if (full.timeoutMs > 0) {
48
+ timer = setTimeout(() => {
49
+ const entry = this.pendingMap.get(full.id);
50
+ if (!entry) return;
51
+ this.pendingMap.delete(full.id);
52
+ const decision: ApprovalDecision = {
53
+ approvalId: full.id,
54
+ outcome: 'timeout',
55
+ reason: `Approval timed out after ${full.timeoutMs}ms`,
56
+ decidedAt: nowISO(),
57
+ };
58
+ this.emit({ type: 'expired', request: full });
59
+ resolvePromise(decision);
60
+ }, full.timeoutMs);
61
+ }
62
+
63
+ this.pendingMap.set(full.id, { request: full, settle: resolvePromise, timer });
64
+ this.emit({ type: 'requested', request: full });
65
+ });
66
+ }
67
+
68
+ resolve(
69
+ approvalId: string,
70
+ decision: Omit<ApprovalDecision, 'approvalId' | 'decidedAt'>,
71
+ ): boolean {
72
+ const entry = this.pendingMap.get(approvalId);
73
+ if (!entry) return false;
74
+ this.pendingMap.delete(approvalId);
75
+ if (entry.timer) clearTimeout(entry.timer);
76
+
77
+ const full: ApprovalDecision = {
78
+ approvalId,
79
+ outcome: decision.outcome,
80
+ choice: decision.choice,
81
+ actor: decision.actor,
82
+ reason: decision.reason,
83
+ decidedAt: nowISO(),
84
+ };
85
+ this.emit({ type: 'resolved', request: entry.request, decision: full });
86
+ entry.settle(full);
87
+ return true;
88
+ }
89
+
90
+ pending(): readonly ApprovalRequest[] {
91
+ return Array.from(this.pendingMap.values()).map((e) => e.request);
92
+ }
93
+
94
+ subscribe(listener: ApprovalListener): () => void {
95
+ this.listeners.add(listener);
96
+ return () => {
97
+ this.listeners.delete(listener);
98
+ };
99
+ }
100
+
101
+ abortAll(reason: string): void {
102
+ const entries = Array.from(this.pendingMap.entries());
103
+ this.pendingMap.clear();
104
+ for (const [id, entry] of entries) {
105
+ if (entry.timer) clearTimeout(entry.timer);
106
+ this.emit({ type: 'aborted', request: entry.request, reason });
107
+ entry.settle({
108
+ approvalId: id,
109
+ outcome: 'aborted',
110
+ reason,
111
+ decidedAt: nowISO(),
112
+ });
113
+ }
114
+ }
115
+
116
+ private emit(event: ApprovalEvent): void {
117
+ for (const listener of this.listeners) {
118
+ try {
119
+ listener(event);
120
+ } catch (err) {
121
+ console.error('[approval gateway] listener error:', err);
122
+ }
123
+ }
124
+ }
125
+ }
@@ -0,0 +1,37 @@
1
+ import { registerPlugin } from './registry';
2
+
3
+ // Built-in Drivers
4
+ // Only claude-code is built in. Other drivers (codex, opencode) ship as
5
+ // workspace plugins under plugins/ and must be declared in pipeline.yaml
6
+ // via the `plugins` field, e.g.:
7
+ // plugins: ["@tagma/driver-codex", "@tagma/driver-opencode"]
8
+ import { ClaudeCodeDriver } from './drivers/claude-code';
9
+
10
+ // Built-in Triggers
11
+ import { FileTrigger } from './triggers/file';
12
+ import { ManualTrigger } from './triggers/manual';
13
+
14
+ // Built-in Completions
15
+ import { ExitCodeCompletion } from './completions/exit-code';
16
+ import { FileExistsCompletion } from './completions/file-exists';
17
+ import { OutputCheckCompletion } from './completions/output-check';
18
+
19
+ // Built-in Middleware
20
+ import { StaticContextMiddleware } from './middlewares/static-context';
21
+
22
+ export function bootstrapBuiltins(): void {
23
+ // Drivers
24
+ registerPlugin('drivers', 'claude-code', ClaudeCodeDriver);
25
+
26
+ // Triggers
27
+ registerPlugin('triggers', 'file', FileTrigger);
28
+ registerPlugin('triggers', 'manual', ManualTrigger);
29
+
30
+ // Completions
31
+ registerPlugin('completions', 'exit_code', ExitCodeCompletion);
32
+ registerPlugin('completions', 'file_exists', FileExistsCompletion);
33
+ registerPlugin('completions', 'output_check', OutputCheckCompletion);
34
+
35
+ // Middlewares
36
+ registerPlugin('middlewares', 'static_context', StaticContextMiddleware);
37
+ }
@@ -0,0 +1,19 @@
1
+ import type { CompletionPlugin, CompletionContext, TaskResult } from '../types';
2
+
3
+ export const ExitCodeCompletion: CompletionPlugin = {
4
+ name: 'exit_code',
5
+
6
+ async check(config: Record<string, unknown>, result: TaskResult, _ctx: CompletionContext): Promise<boolean> {
7
+ const expected = config.expect ?? 0;
8
+
9
+ if (typeof expected === 'number') {
10
+ return result.exitCode === expected;
11
+ }
12
+ if (Array.isArray(expected) && expected.every((v) => typeof v === 'number')) {
13
+ return expected.includes(result.exitCode);
14
+ }
15
+ throw new Error(
16
+ `exit_code completion: "expect" must be a number or number[], got ${typeof expected}`
17
+ );
18
+ },
19
+ };
@@ -0,0 +1,39 @@
1
+ import { stat } from 'node:fs/promises';
2
+ import type { CompletionPlugin, CompletionContext, TaskResult } from '../types';
3
+ import { validatePath } from '../utils';
4
+
5
+ type Kind = 'file' | 'dir' | 'any';
6
+
7
+ export const FileExistsCompletion: CompletionPlugin = {
8
+ name: 'file_exists',
9
+
10
+ async check(config: Record<string, unknown>, _result: TaskResult, ctx: CompletionContext): Promise<boolean> {
11
+ const filePath = config.path as string;
12
+ if (!filePath) throw new Error('file_exists completion: "path" is required');
13
+
14
+ const safePath = validatePath(filePath, ctx.workDir);
15
+
16
+ const kind = (config.kind as Kind | undefined) ?? 'any';
17
+ if (kind !== 'file' && kind !== 'dir' && kind !== 'any') {
18
+ throw new Error(`file_exists completion: "kind" must be "file" | "dir" | "any", got "${kind}"`);
19
+ }
20
+
21
+ const minSize = config.min_size;
22
+ if (minSize != null && (typeof minSize !== 'number' || minSize < 0)) {
23
+ throw new Error(`file_exists completion: "min_size" must be a non-negative number`);
24
+ }
25
+
26
+ try {
27
+ const st = await stat(safePath);
28
+ if (kind === 'file' && !st.isFile()) return false;
29
+ if (kind === 'dir' && !st.isDirectory()) return false;
30
+ if (typeof minSize === 'number' && st.isFile() && st.size < minSize) return false;
31
+ return true;
32
+ } catch (err: unknown) {
33
+ const code = (err as NodeJS.ErrnoException).code;
34
+ if (code === 'ENOENT' || code === 'ENOTDIR') return false;
35
+ // Permission / IO errors should surface, not silently mean "missing"
36
+ throw err;
37
+ }
38
+ },
39
+ };
@@ -0,0 +1,57 @@
1
+ import type { CompletionPlugin, CompletionContext, TaskResult } from '../types';
2
+ import { shellArgs, parseDuration } from '../utils';
3
+
4
+ const DEFAULT_TIMEOUT_MS = 30_000;
5
+
6
+ export const OutputCheckCompletion: CompletionPlugin = {
7
+ name: 'output_check',
8
+
9
+ async check(config: Record<string, unknown>, result: TaskResult, ctx: CompletionContext): Promise<boolean> {
10
+ const checkCmd = config.check as string;
11
+ if (!checkCmd) throw new Error('output_check completion: "check" is required');
12
+
13
+ const timeoutMs = config.timeout != null
14
+ ? parseDuration(String(config.timeout))
15
+ : DEFAULT_TIMEOUT_MS;
16
+
17
+ const controller = new AbortController();
18
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
19
+
20
+ const proc = Bun.spawn(shellArgs(checkCmd) as string[], {
21
+ cwd: ctx.workDir,
22
+ stdin: 'pipe',
23
+ stdout: 'pipe',
24
+ stderr: 'pipe',
25
+ signal: controller.signal,
26
+ });
27
+
28
+ try {
29
+ if (proc.stdin) {
30
+ try {
31
+ proc.stdin.write(result.stdout);
32
+ await proc.stdin.end();
33
+ } catch (err: unknown) {
34
+ // EPIPE is expected when the check process exits before reading all of stdin
35
+ // (e.g. `grep -q` exits on first match). Anything else is a real failure.
36
+ const code = (err as NodeJS.ErrnoException)?.code;
37
+ if (code !== 'EPIPE') throw err;
38
+ }
39
+ }
40
+
41
+ const exitCode = await proc.exited;
42
+
43
+ if (exitCode !== 0) {
44
+ try {
45
+ const stderr = await new Response(proc.stderr).text();
46
+ if (stderr.trim()) {
47
+ console.warn(`[output_check] "${checkCmd}" exit=${exitCode}: ${stderr.trim()}`);
48
+ }
49
+ } catch { /* ignore stderr read failures */ }
50
+ }
51
+
52
+ return exitCode === 0;
53
+ } finally {
54
+ clearTimeout(timer);
55
+ }
56
+ },
57
+ };