@tagma/sdk 0.1.8 → 0.1.9
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 +3 -3
- package/package.json +1 -1
- package/src/adapters/stdin-approval.ts +117 -117
- package/src/adapters/websocket-approval.ts +175 -144
- package/src/approval.ts +4 -1
- package/src/completions/exit-code.ts +19 -19
- package/src/completions/file-exists.ts +39 -39
- package/src/completions/output-check.ts +57 -57
- package/src/config-ops.ts +239 -220
- package/src/dag.ts +222 -222
- package/src/drivers/claude-code.ts +207 -207
- package/src/engine.ts +743 -714
- package/src/hooks.ts +147 -138
- package/src/logger.ts +112 -107
- package/src/middlewares/static-context.ts +29 -29
- package/src/pipeline-runner.ts +126 -125
- package/src/runner.ts +213 -195
- package/src/schema.ts +386 -358
- package/src/triggers/file.ts +105 -94
- package/src/triggers/manual.ts +61 -61
- package/src/utils.ts +154 -147
- package/src/validate-raw.ts +223 -203
package/src/hooks.ts
CHANGED
|
@@ -1,138 +1,147 @@
|
|
|
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
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
readonly name: string;
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
readonly
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
readonly
|
|
101
|
-
readonly
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
readonly
|
|
106
|
-
readonly
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
) {
|
|
119
|
-
return { event, pipeline
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
export function
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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
|
+
// Consume stdout and stderr concurrently with waiting for exit.
|
|
41
|
+
// Sequential reads after proc.exited risk a pipe-buffer deadlock when
|
|
42
|
+
// hook output exceeds the ~64 KB kernel buffer.
|
|
43
|
+
const [exitCode, stdout, stderr] = await Promise.all([
|
|
44
|
+
proc.exited,
|
|
45
|
+
new Response(proc.stdout).text(),
|
|
46
|
+
new Response(proc.stderr).text(),
|
|
47
|
+
]);
|
|
48
|
+
|
|
49
|
+
if (stdout.trim()) {
|
|
50
|
+
console.log(`[hook: ${command}] stdout: ${stdout.trim()}`);
|
|
51
|
+
}
|
|
52
|
+
if (stderr.trim()) {
|
|
53
|
+
console.error(`[hook: ${command}] stderr: ${stderr.trim()}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return exitCode;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function executeHook(
|
|
60
|
+
hooks: HooksConfig | undefined,
|
|
61
|
+
event: HookEvent,
|
|
62
|
+
context: unknown,
|
|
63
|
+
workDir?: string,
|
|
64
|
+
): Promise<HookResult> {
|
|
65
|
+
if (!hooks) return { allowed: true, exitCode: 0 };
|
|
66
|
+
|
|
67
|
+
const commands = normalizeCommands(hooks[event]);
|
|
68
|
+
if (commands.length === 0) return { allowed: true, exitCode: 0 };
|
|
69
|
+
|
|
70
|
+
const isGate = GATE_HOOKS.has(event);
|
|
71
|
+
|
|
72
|
+
for (const cmd of commands) {
|
|
73
|
+
const exitCode = await runSingleHook(cmd, context, workDir);
|
|
74
|
+
|
|
75
|
+
if (isGate && exitCode === 1) {
|
|
76
|
+
// Only exit code 1 has gate semantics (block execution)
|
|
77
|
+
return { allowed: false, exitCode };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (exitCode !== 0) {
|
|
81
|
+
// Non-zero but not 1: hook itself had an error, log but don't block
|
|
82
|
+
console.warn(`[hook: ${event}] "${cmd}" exited with code ${exitCode}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return { allowed: true, exitCode: 0 };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ═══ Context Builders ═══
|
|
90
|
+
|
|
91
|
+
export interface PipelineInfo {
|
|
92
|
+
readonly name: string;
|
|
93
|
+
readonly run_id: string;
|
|
94
|
+
readonly started_at: string;
|
|
95
|
+
readonly finished_at?: string;
|
|
96
|
+
readonly duration_ms?: number;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface TrackInfo {
|
|
100
|
+
readonly id: string;
|
|
101
|
+
readonly name: string;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface TaskInfo {
|
|
105
|
+
readonly id: string;
|
|
106
|
+
readonly name: string;
|
|
107
|
+
readonly type: 'ai' | 'command';
|
|
108
|
+
readonly status: string;
|
|
109
|
+
readonly exit_code: number | null;
|
|
110
|
+
readonly duration_ms: number | null;
|
|
111
|
+
readonly output_path: string | null;
|
|
112
|
+
readonly stderr_path: string | null;
|
|
113
|
+
readonly session_id: string | null;
|
|
114
|
+
readonly started_at: string | null;
|
|
115
|
+
readonly finished_at: string | null;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function buildPipelineStartContext(pipeline: PipelineInfo) {
|
|
119
|
+
return { event: 'pipeline_start', pipeline };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function buildTaskContext(
|
|
123
|
+
event: 'task_start' | 'task_success' | 'task_failure',
|
|
124
|
+
pipeline: PipelineInfo,
|
|
125
|
+
track: TrackInfo,
|
|
126
|
+
task: TaskInfo,
|
|
127
|
+
) {
|
|
128
|
+
return { event, pipeline, track, task };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function buildPipelineCompleteContext(
|
|
132
|
+
pipeline: PipelineInfo & { finished_at: string; duration_ms: number },
|
|
133
|
+
summary: {
|
|
134
|
+
total: number; success: number; failed: number;
|
|
135
|
+
skipped: number; timeout: number; blocked: number;
|
|
136
|
+
},
|
|
137
|
+
) {
|
|
138
|
+
return { event: 'pipeline_complete', pipeline, summary };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function buildPipelineErrorContext(
|
|
142
|
+
pipeline: PipelineInfo,
|
|
143
|
+
error: string,
|
|
144
|
+
eventType?: string,
|
|
145
|
+
) {
|
|
146
|
+
return { event: eventType ?? 'pipeline_error', pipeline, error };
|
|
147
|
+
}
|
package/src/logger.ts
CHANGED
|
@@ -1,107 +1,112 @@
|
|
|
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>/
|
|
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
|
-
|
|
103
|
-
|
|
104
|
-
if (text
|
|
105
|
-
const
|
|
106
|
-
|
|
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>/.tagma/logs/<runId>/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, '.tagma', '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
|
+
* Uses TextEncoder so CJK and emoji (multi-byte) characters are counted correctly.
|
|
102
|
+
*/
|
|
103
|
+
export function clip(text: string, maxBytes = 16 * 1024): string {
|
|
104
|
+
if (!text) return '';
|
|
105
|
+
const encoder = new TextEncoder();
|
|
106
|
+
const bytes = encoder.encode(text);
|
|
107
|
+
if (bytes.length <= maxBytes) return text;
|
|
108
|
+
const omittedBytes = bytes.length - maxBytes;
|
|
109
|
+
// TextDecoder handles partial code-point boundaries safely (replacement char insertion)
|
|
110
|
+
const truncated = new TextDecoder().decode(bytes.slice(0, maxBytes));
|
|
111
|
+
return truncated + `\n…[truncated ${omittedBytes} bytes]`;
|
|
112
|
+
}
|
|
@@ -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
|
+
};
|