@agentsmarket/pipeline-runtime 0.4.0 → 0.5.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/README.md +86 -1
- package/dist/adapters/minimax.d.ts +16 -8
- package/dist/adapters/minimax.js +105 -26
- package/dist/adapters/multimodal-convert.d.ts +54 -0
- package/dist/adapters/multimodal-convert.js +105 -0
- package/dist/adapters/openrouter.d.ts +5 -0
- package/dist/adapters/openrouter.js +53 -6
- package/dist/index.d.ts +21 -4
- package/dist/index.js +16 -3
- package/dist/loop.d.ts +90 -0
- package/dist/loop.js +200 -0
- package/dist/memory.d.ts +73 -0
- package/dist/memory.js +119 -0
- package/dist/model-resolver.d.ts +66 -1
- package/dist/multimodal.d.ts +43 -0
- package/dist/multimodal.js +23 -0
- package/dist/output-errors.d.ts +93 -0
- package/dist/output-errors.js +128 -0
- package/dist/output-schema-validate.d.ts +10 -0
- package/dist/output-schema-validate.js +149 -0
- package/dist/output-schema.d.ts +66 -0
- package/dist/output-schema.js +141 -0
- package/dist/pipeline-refs.d.ts +15 -0
- package/dist/pipeline-refs.js +155 -0
- package/dist/provider-registry.d.ts +22 -1
- package/dist/provider-registry.js +62 -2
- package/dist/providers/anthropic.d.ts +28 -0
- package/dist/providers/anthropic.js +118 -0
- package/dist/providers/openai-chat.d.ts +28 -0
- package/dist/providers/openai-chat.js +106 -0
- package/dist/providers/openai-dalle.d.ts +19 -0
- package/dist/providers/openai-dalle.js +41 -0
- package/dist/providers/openai-tts.d.ts +19 -0
- package/dist/providers/openai-tts.js +46 -0
- package/dist/providers/openai-vision.d.ts +15 -0
- package/dist/providers/openai-vision.js +43 -0
- package/dist/providers/openai-whisper.d.ts +16 -0
- package/dist/providers/openai-whisper.js +43 -0
- package/dist/providers/replicate.d.ts +19 -0
- package/dist/providers/replicate.js +61 -0
- package/dist/providers/types.d.ts +23 -0
- package/dist/providers/types.js +31 -0
- package/dist/runtime-constraints.d.ts +2 -1
- package/dist/shell-stage.d.ts +82 -0
- package/dist/shell-stage.js +169 -0
- package/dist/stages.d.ts +23 -2
- package/dist/stages.js +349 -29
- package/dist/streaming-events.d.ts +17 -2
- package/dist/streaming-events.js +12 -0
- package/dist/testing/assertions.d.ts +17 -0
- package/dist/testing/assertions.js +149 -0
- package/dist/testing/conformance.d.ts +3 -0
- package/dist/testing/conformance.js +28 -0
- package/dist/testing/coverage.d.ts +11 -0
- package/dist/testing/coverage.js +35 -0
- package/dist/testing/index.d.ts +9 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/reporters/json.d.ts +5 -0
- package/dist/testing/reporters/json.js +23 -0
- package/dist/testing/reporters/junit.d.ts +5 -0
- package/dist/testing/reporters/junit.js +31 -0
- package/dist/testing/reporters/text.d.ts +5 -0
- package/dist/testing/reporters/text.js +36 -0
- package/dist/testing/runner.d.ts +25 -0
- package/dist/testing/runner.js +222 -0
- package/dist/testing/spec-parser.d.ts +366 -0
- package/dist/testing/spec-parser.js +60 -0
- package/dist/testing/stage-extractor.d.ts +16 -0
- package/dist/testing/stage-extractor.js +25 -0
- package/dist/tools/audio-transcribe.d.ts +11 -0
- package/dist/tools/audio-transcribe.js +45 -0
- package/dist/tools/image-describe.d.ts +12 -0
- package/dist/tools/image-describe.js +47 -0
- package/dist/tools/image-generate.d.ts +12 -0
- package/dist/tools/image-generate.js +47 -0
- package/dist/tools/memory-recall.d.ts +13 -0
- package/dist/tools/memory-recall.js +63 -0
- package/dist/tools/memory-shared.d.ts +8 -0
- package/dist/tools/memory-shared.js +8 -0
- package/dist/tools/memory-store.d.ts +14 -0
- package/dist/tools/memory-store.js +68 -0
- package/dist/tools/tool-skills.js +14 -0
- package/dist/tools/tts-synthesize.d.ts +12 -0
- package/dist/tools/tts-synthesize.js +50 -0
- package/dist/tools/video-generate.d.ts +12 -0
- package/dist/tools/video-generate.js +47 -0
- package/dist/types.d.ts +8 -0
- package/dist/validate-inputs.d.ts +115 -0
- package/dist/validate-inputs.js +273 -0
- package/dist/webhook.js +0 -0
- package/package.json +3 -3
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI TTS provider — text-to-speech.
|
|
3
|
+
* Used by tts_synthesize tool skill.
|
|
4
|
+
*
|
|
5
|
+
* Env: OPENAI_API_KEY
|
|
6
|
+
* Cost: $15 / 1M characters ($0.000015/char)
|
|
7
|
+
* Limit: 4096 chars per request (we use 5000 for safety)
|
|
8
|
+
*/
|
|
9
|
+
import { ToolSkillResult } from './types.js';
|
|
10
|
+
export declare const MAX_CHARS = 5000;
|
|
11
|
+
export type TtsVoice = 'alloy' | 'echo' | 'fable' | 'onyx' | 'nova' | 'shimmer';
|
|
12
|
+
export type TtsFormat = 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm';
|
|
13
|
+
export interface OpenAITtsInput {
|
|
14
|
+
text: string;
|
|
15
|
+
voice?: TtsVoice;
|
|
16
|
+
format?: TtsFormat;
|
|
17
|
+
speed?: number;
|
|
18
|
+
}
|
|
19
|
+
export declare function openaiTtsSynthesize(input: OpenAITtsInput): Promise<ToolSkillResult>;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI TTS provider — text-to-speech.
|
|
3
|
+
* Used by tts_synthesize tool skill.
|
|
4
|
+
*
|
|
5
|
+
* Env: OPENAI_API_KEY
|
|
6
|
+
* Cost: $15 / 1M characters ($0.000015/char)
|
|
7
|
+
* Limit: 4096 chars per request (we use 5000 for safety)
|
|
8
|
+
*/
|
|
9
|
+
import { ProviderError, requireEnv } from './types.js';
|
|
10
|
+
export const MAX_CHARS = 5000;
|
|
11
|
+
export async function openaiTtsSynthesize(input) {
|
|
12
|
+
const apiKey = requireEnv('OPENAI_API_KEY');
|
|
13
|
+
if (input.text.length > MAX_CHARS) {
|
|
14
|
+
throw new ProviderError(`text too long: ${input.text.length} chars (max ${MAX_CHARS})`, 'openai-tts', 413);
|
|
15
|
+
}
|
|
16
|
+
const res = await fetch('https://api.openai.com/v1/audio/speech', {
|
|
17
|
+
method: 'POST',
|
|
18
|
+
headers: {
|
|
19
|
+
Authorization: `Bearer ${apiKey}`,
|
|
20
|
+
'Content-Type': 'application/json',
|
|
21
|
+
},
|
|
22
|
+
body: JSON.stringify({
|
|
23
|
+
model: 'tts-1',
|
|
24
|
+
input: input.text,
|
|
25
|
+
voice: input.voice ?? 'alloy',
|
|
26
|
+
response_format: input.format ?? 'mp3',
|
|
27
|
+
speed: input.speed ?? 1.0,
|
|
28
|
+
}),
|
|
29
|
+
});
|
|
30
|
+
if (!res.ok) {
|
|
31
|
+
const errText = await res.text();
|
|
32
|
+
throw new ProviderError(`openai-tts error ${res.status}: ${errText.slice(0, 500)}`, 'openai-tts', res.status);
|
|
33
|
+
}
|
|
34
|
+
const arrayBuffer = await res.arrayBuffer();
|
|
35
|
+
const bytes = arrayBuffer.byteLength;
|
|
36
|
+
return {
|
|
37
|
+
text: JSON.stringify({ audio_size_bytes: bytes, format: input.format ?? 'mp3', ok: true }),
|
|
38
|
+
usage: { inputTokens: input.text.length, outputTokens: 0 },
|
|
39
|
+
meta: {
|
|
40
|
+
provider: 'openai',
|
|
41
|
+
model: 'tts-1',
|
|
42
|
+
voice: input.voice ?? 'alloy',
|
|
43
|
+
audio_size_bytes: bytes,
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI Vision provider — gpt-4o-mini multimodal.
|
|
3
|
+
* Used by image_describe tool skill.
|
|
4
|
+
*
|
|
5
|
+
* Env: OPENAI_API_KEY
|
|
6
|
+
* Cost: ~$0.00015/image + $0.0006/1k output tokens
|
|
7
|
+
*/
|
|
8
|
+
import { ToolSkillResult } from './types.js';
|
|
9
|
+
export interface OpenAIVisionInput {
|
|
10
|
+
image_url: string;
|
|
11
|
+
prompt: string;
|
|
12
|
+
detail?: 'low' | 'high' | 'auto';
|
|
13
|
+
max_tokens?: number;
|
|
14
|
+
}
|
|
15
|
+
export declare function openaiVisionDescribe(input: OpenAIVisionInput): Promise<ToolSkillResult>;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI Vision provider — gpt-4o-mini multimodal.
|
|
3
|
+
* Used by image_describe tool skill.
|
|
4
|
+
*
|
|
5
|
+
* Env: OPENAI_API_KEY
|
|
6
|
+
* Cost: ~$0.00015/image + $0.0006/1k output tokens
|
|
7
|
+
*/
|
|
8
|
+
import { ProviderError, requireEnv, safeJsonParse } from './types.js';
|
|
9
|
+
export async function openaiVisionDescribe(input) {
|
|
10
|
+
const apiKey = requireEnv('OPENAI_API_KEY');
|
|
11
|
+
const res = await fetch('https://api.openai.com/v1/chat/completions', {
|
|
12
|
+
method: 'POST',
|
|
13
|
+
headers: {
|
|
14
|
+
Authorization: `Bearer ${apiKey}`,
|
|
15
|
+
'Content-Type': 'application/json',
|
|
16
|
+
},
|
|
17
|
+
body: JSON.stringify({
|
|
18
|
+
model: 'gpt-4o-mini',
|
|
19
|
+
messages: [
|
|
20
|
+
{
|
|
21
|
+
role: 'user',
|
|
22
|
+
content: [
|
|
23
|
+
{ type: 'text', text: input.prompt || 'Describe this image in detail.' },
|
|
24
|
+
{
|
|
25
|
+
type: 'image_url',
|
|
26
|
+
image_url: { url: input.image_url, detail: input.detail ?? 'auto' },
|
|
27
|
+
},
|
|
28
|
+
],
|
|
29
|
+
},
|
|
30
|
+
],
|
|
31
|
+
max_tokens: input.max_tokens ?? 500,
|
|
32
|
+
}),
|
|
33
|
+
});
|
|
34
|
+
const data = await safeJsonParse(res, 'openai-vision');
|
|
35
|
+
const content = data.choices[0]?.message.content ?? '';
|
|
36
|
+
if (!content)
|
|
37
|
+
throw new ProviderError('openai-vision returned empty content', 'openai-vision', 200);
|
|
38
|
+
return {
|
|
39
|
+
text: JSON.stringify({ description: content, ok: true }),
|
|
40
|
+
usage: { inputTokens: data.usage.prompt_tokens, outputTokens: data.usage.completion_tokens },
|
|
41
|
+
meta: { provider: 'openai', model: 'gpt-4o-mini' },
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI Whisper provider — speech-to-text.
|
|
3
|
+
* Used by audio_transcribe tool skill.
|
|
4
|
+
*
|
|
5
|
+
* Env: OPENAI_API_KEY
|
|
6
|
+
* Cost: $0.006 / minute of audio
|
|
7
|
+
* Limit: 25 MB max upload
|
|
8
|
+
*/
|
|
9
|
+
import { ToolSkillResult } from './types.js';
|
|
10
|
+
export interface OpenAIWhisperInput {
|
|
11
|
+
audio_url: string;
|
|
12
|
+
language?: string;
|
|
13
|
+
response_format?: 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt';
|
|
14
|
+
}
|
|
15
|
+
export declare const MAX_AUDIO_BYTES: number;
|
|
16
|
+
export declare function openaiWhisperTranscribe(input: OpenAIWhisperInput): Promise<ToolSkillResult>;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI Whisper provider — speech-to-text.
|
|
3
|
+
* Used by audio_transcribe tool skill.
|
|
4
|
+
*
|
|
5
|
+
* Env: OPENAI_API_KEY
|
|
6
|
+
* Cost: $0.006 / minute of audio
|
|
7
|
+
* Limit: 25 MB max upload
|
|
8
|
+
*/
|
|
9
|
+
import { ProviderError, requireEnv } from './types.js';
|
|
10
|
+
export const MAX_AUDIO_BYTES = 25 * 1024 * 1024;
|
|
11
|
+
export async function openaiWhisperTranscribe(input) {
|
|
12
|
+
const apiKey = requireEnv('OPENAI_API_KEY');
|
|
13
|
+
const audioRes = await fetch(input.audio_url);
|
|
14
|
+
if (!audioRes.ok) {
|
|
15
|
+
throw new ProviderError(`failed to fetch audio: ${audioRes.status}`, 'openai-whisper', audioRes.status);
|
|
16
|
+
}
|
|
17
|
+
const blob = await audioRes.blob();
|
|
18
|
+
if (blob.size > MAX_AUDIO_BYTES) {
|
|
19
|
+
throw new ProviderError(`audio too large: ${blob.size} bytes (max ${MAX_AUDIO_BYTES})`, 'openai-whisper', 413);
|
|
20
|
+
}
|
|
21
|
+
const form = new FormData();
|
|
22
|
+
const ext = input.audio_url.split('.').pop()?.toLowerCase() ?? 'mp3';
|
|
23
|
+
form.append('file', blob, `audio.${ext}`);
|
|
24
|
+
form.append('model', 'whisper-1');
|
|
25
|
+
if (input.language)
|
|
26
|
+
form.append('language', input.language);
|
|
27
|
+
form.append('response_format', input.response_format ?? 'verbose_json');
|
|
28
|
+
const res = await fetch('https://api.openai.com/v1/audio/transcriptions', {
|
|
29
|
+
method: 'POST',
|
|
30
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
31
|
+
body: form,
|
|
32
|
+
});
|
|
33
|
+
if (!res.ok) {
|
|
34
|
+
const errText = await res.text();
|
|
35
|
+
throw new ProviderError(`openai-whisper error ${res.status}: ${errText.slice(0, 500)}`, 'openai-whisper', res.status);
|
|
36
|
+
}
|
|
37
|
+
const data = (await res.json());
|
|
38
|
+
return {
|
|
39
|
+
text: JSON.stringify({ transcript: data.text, language: data.language, duration: data.duration, ok: true }),
|
|
40
|
+
usage: { inputTokens: 0, outputTokens: 0 },
|
|
41
|
+
meta: { provider: 'openai', model: 'whisper-1', duration_seconds: data.duration },
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Replicate provider — generic async polling for video/image models.
|
|
3
|
+
* Used by video_generate tool skill (Runway Gen-3 / Pika / Stable Video).
|
|
4
|
+
*
|
|
5
|
+
* Env: REPLICATE_API_KEY
|
|
6
|
+
* Flow: POST /v1/predictions → poll until status=succeeded → return output URLs
|
|
7
|
+
* Cost varies by model (~$0.10/sec for Runway Gen-3)
|
|
8
|
+
*/
|
|
9
|
+
import { ToolSkillResult } from './types.js';
|
|
10
|
+
export type ReplicateModel = 'stability-ai/stable-video-diffusion' | 'minimax/video-01' | 'bytedance/seedance-1-pro';
|
|
11
|
+
export interface ReplicateVideoInput {
|
|
12
|
+
prompt: string;
|
|
13
|
+
duration_seconds?: number;
|
|
14
|
+
resolution?: '480p' | '720p' | '1080p';
|
|
15
|
+
model?: ReplicateModel;
|
|
16
|
+
max_wait_ms?: number;
|
|
17
|
+
}
|
|
18
|
+
export declare const MAX_DURATION_SECONDS = 30;
|
|
19
|
+
export declare function replicateGenerateVideo(input: ReplicateVideoInput): Promise<ToolSkillResult>;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Replicate provider — generic async polling for video/image models.
|
|
3
|
+
* Used by video_generate tool skill (Runway Gen-3 / Pika / Stable Video).
|
|
4
|
+
*
|
|
5
|
+
* Env: REPLICATE_API_KEY
|
|
6
|
+
* Flow: POST /v1/predictions → poll until status=succeeded → return output URLs
|
|
7
|
+
* Cost varies by model (~$0.10/sec for Runway Gen-3)
|
|
8
|
+
*/
|
|
9
|
+
import { ProviderError, requireEnv } from './types.js';
|
|
10
|
+
const REPLICATE_BASE = 'https://api.replicate.com/v1';
|
|
11
|
+
const POLL_INTERVAL_MS = 2000;
|
|
12
|
+
const DEFAULT_MAX_WAIT_MS = 5 * 60 * 1000;
|
|
13
|
+
export const MAX_DURATION_SECONDS = 30;
|
|
14
|
+
export async function replicateGenerateVideo(input) {
|
|
15
|
+
const apiKey = requireEnv('REPLICATE_API_KEY');
|
|
16
|
+
const duration = Math.min(input.duration_seconds ?? 10, MAX_DURATION_SECONDS);
|
|
17
|
+
const model = input.model ?? 'stability-ai/stable-video-diffusion';
|
|
18
|
+
const createRes = await fetch(`${REPLICATE_BASE}/predictions`, {
|
|
19
|
+
method: 'POST',
|
|
20
|
+
headers: {
|
|
21
|
+
Authorization: `Token ${apiKey}`,
|
|
22
|
+
'Content-Type': 'application/json',
|
|
23
|
+
},
|
|
24
|
+
body: JSON.stringify({
|
|
25
|
+
version: model,
|
|
26
|
+
input: {
|
|
27
|
+
prompt: input.prompt,
|
|
28
|
+
duration,
|
|
29
|
+
resolution: input.resolution ?? '720p',
|
|
30
|
+
},
|
|
31
|
+
}),
|
|
32
|
+
});
|
|
33
|
+
if (!createRes.ok) {
|
|
34
|
+
const errText = await createRes.text();
|
|
35
|
+
throw new ProviderError(`replicate error ${createRes.status}: ${errText.slice(0, 500)}`, 'replicate', createRes.status);
|
|
36
|
+
}
|
|
37
|
+
let prediction = (await createRes.json());
|
|
38
|
+
const deadline = Date.now() + (input.max_wait_ms ?? DEFAULT_MAX_WAIT_MS);
|
|
39
|
+
while (prediction.status !== 'succeeded' && prediction.status !== 'failed' && prediction.status !== 'canceled') {
|
|
40
|
+
if (Date.now() > deadline) {
|
|
41
|
+
throw new ProviderError(`replicate timed out after ${input.max_wait_ms}ms`, 'replicate', 504);
|
|
42
|
+
}
|
|
43
|
+
await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
|
|
44
|
+
const pollRes = await fetch(`${REPLICATE_BASE}/predictions/${prediction.id}`, {
|
|
45
|
+
headers: { Authorization: `Token ${apiKey}` },
|
|
46
|
+
});
|
|
47
|
+
if (!pollRes.ok) {
|
|
48
|
+
throw new ProviderError(`replicate poll error ${pollRes.status}`, 'replicate', pollRes.status);
|
|
49
|
+
}
|
|
50
|
+
prediction = (await pollRes.json());
|
|
51
|
+
}
|
|
52
|
+
if (prediction.status === 'failed' || prediction.status === 'canceled') {
|
|
53
|
+
throw new ProviderError(`replicate prediction ${prediction.status}: ${prediction.error ?? 'unknown'}`, 'replicate');
|
|
54
|
+
}
|
|
55
|
+
const output = Array.isArray(prediction.output) ? prediction.output : prediction.output ? [prediction.output] : [];
|
|
56
|
+
return {
|
|
57
|
+
text: JSON.stringify({ videos: output, duration_seconds: duration, ok: true }),
|
|
58
|
+
usage: { inputTokens: 0, outputTokens: 0 },
|
|
59
|
+
meta: { provider: 'replicate', model, status: prediction.status, video_count: output.length },
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared types for tool skill providers.
|
|
3
|
+
*
|
|
4
|
+
* Each provider module exports a `call<X>(input): Promise<ToolSkillResult>` function.
|
|
5
|
+
* Tool skill handlers call providers; providers handle API key + HTTP + response parsing.
|
|
6
|
+
*/
|
|
7
|
+
export interface ToolSkillUsage {
|
|
8
|
+
inputTokens: number;
|
|
9
|
+
outputTokens: number;
|
|
10
|
+
}
|
|
11
|
+
export interface ToolSkillResult {
|
|
12
|
+
text: string;
|
|
13
|
+
usage: ToolSkillUsage;
|
|
14
|
+
meta?: Record<string, unknown>;
|
|
15
|
+
}
|
|
16
|
+
export declare class ProviderError extends Error {
|
|
17
|
+
readonly provider: string;
|
|
18
|
+
readonly statusCode?: number | undefined;
|
|
19
|
+
readonly cause?: unknown | undefined;
|
|
20
|
+
constructor(message: string, provider: string, statusCode?: number | undefined, cause?: unknown | undefined);
|
|
21
|
+
}
|
|
22
|
+
export declare function requireEnv(name: string): string;
|
|
23
|
+
export declare function safeJsonParse<T>(res: Response, provider: string): Promise<T>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export class ProviderError extends Error {
|
|
2
|
+
provider;
|
|
3
|
+
statusCode;
|
|
4
|
+
cause;
|
|
5
|
+
constructor(message, provider, statusCode, cause) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.provider = provider;
|
|
8
|
+
this.statusCode = statusCode;
|
|
9
|
+
this.cause = cause;
|
|
10
|
+
this.name = 'ProviderError';
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export function requireEnv(name) {
|
|
14
|
+
const v = process.env[name];
|
|
15
|
+
if (!v) {
|
|
16
|
+
throw new ProviderError(`${name} not set`, 'env');
|
|
17
|
+
}
|
|
18
|
+
return v;
|
|
19
|
+
}
|
|
20
|
+
export async function safeJsonParse(res, provider) {
|
|
21
|
+
const text = await res.text();
|
|
22
|
+
if (!res.ok) {
|
|
23
|
+
throw new ProviderError(`${provider} error ${res.status}: ${text.slice(0, 500)}`, provider, res.status);
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(text);
|
|
27
|
+
}
|
|
28
|
+
catch (e) {
|
|
29
|
+
throw new ProviderError(`${provider} returned non-JSON: ${text.slice(0, 200)}`, provider, res.status, e);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -31,7 +31,8 @@ export interface StageLikeForConstraints {
|
|
|
31
31
|
readonly provider?: string;
|
|
32
32
|
readonly uses?: string | string[];
|
|
33
33
|
readonly system?: string;
|
|
34
|
-
readonly prompt?: string;
|
|
34
|
+
readonly prompt?: string | readonly import('./multimodal.js').MultimodalMessage[];
|
|
35
|
+
readonly messages?: readonly import('./multimodal.js').MultimodalMessage[];
|
|
35
36
|
}
|
|
36
37
|
export declare function defaultRuntimeConstraints(): RuntimeConstraints;
|
|
37
38
|
export declare function mergeRuntimeConstraints(a: RuntimeConstraints, b: RuntimeConstraints): RuntimeConstraints;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* P4 — Shell stages (CLI-only).
|
|
3
|
+
*
|
|
4
|
+
* A `shell` stage lets a pipeline run a local command as part of its DAG.
|
|
5
|
+
* Useful for: running tests, linting, formatting, refactoring tools that
|
|
6
|
+
* live on the local machine.
|
|
7
|
+
*
|
|
8
|
+
* **Server-side is REJECTED.** Cloudflare Workers cannot spawn child
|
|
9
|
+
* processes. A pipeline with shell stages works only via `pipeline call
|
|
10
|
+
* --local`. The server explicitly throws `ShellStageUnsupportedError` so
|
|
11
|
+
* the user gets a clear 400 instead of a confusing 500.
|
|
12
|
+
*
|
|
13
|
+
* **Execution model:**
|
|
14
|
+
* - `spawn(cmd, args, { shell: false })` — no shell interpretation, args
|
|
15
|
+
* are passed verbatim to the OS as argv. Prevents shell injection.
|
|
16
|
+
* - `timeout` option sends SIGTERM after `timeout_ms`; the executor
|
|
17
|
+
* maps that to `ShellStageTimeoutError`.
|
|
18
|
+
* - Non-zero exit code → `ShellStageExecError` with stderr in message.
|
|
19
|
+
*
|
|
20
|
+
* **Why dynamic import of `node:child_process`:** the runtime package is
|
|
21
|
+
* also loaded by Cloudflare Workers (which have no Node bindings). Importing
|
|
22
|
+
* `child_process` at module top-level would crash Workers startup. The
|
|
23
|
+
* `NodeShellExecutor` lazily imports it inside `.exec()` so Workers
|
|
24
|
+
* never touch the binding (the server uses a throwing stub).
|
|
25
|
+
*
|
|
26
|
+
* Stage schema (two forms):
|
|
27
|
+
* shell: "npm test" # shorthand: auto-split
|
|
28
|
+
* shell: # explicit form
|
|
29
|
+
* cmd: "npm"
|
|
30
|
+
* args: ["test"]
|
|
31
|
+
* cwd: "./my-project"
|
|
32
|
+
* timeout_ms: 60000
|
|
33
|
+
*/
|
|
34
|
+
export interface ShellStageSpec {
|
|
35
|
+
cmd: string;
|
|
36
|
+
args?: string[];
|
|
37
|
+
cwd?: string;
|
|
38
|
+
timeout_ms?: number;
|
|
39
|
+
}
|
|
40
|
+
export declare const SHELL_DEFAULT_TIMEOUT_MS = 30000;
|
|
41
|
+
export declare const SHELL_MAX_OUTPUT_BYTES: number;
|
|
42
|
+
export declare const SHELL_MAX_TIMEOUT_MS = 600000;
|
|
43
|
+
export declare function normalizeShellStage(raw: unknown): ShellStageSpec | null;
|
|
44
|
+
export interface ShellExecOptions {
|
|
45
|
+
cwd: string;
|
|
46
|
+
timeoutMs: number;
|
|
47
|
+
}
|
|
48
|
+
export interface ShellExecResult {
|
|
49
|
+
stdout: string;
|
|
50
|
+
stderr: string;
|
|
51
|
+
exitCode: number;
|
|
52
|
+
durationMs: number;
|
|
53
|
+
cmd: string;
|
|
54
|
+
args: string[];
|
|
55
|
+
}
|
|
56
|
+
export interface ShellExecutor {
|
|
57
|
+
exec(spec: ShellStageSpec, opts: ShellExecOptions): Promise<ShellExecResult>;
|
|
58
|
+
}
|
|
59
|
+
export declare class ShellStageUnsupportedError extends Error {
|
|
60
|
+
readonly stageId: string;
|
|
61
|
+
readonly reason: string;
|
|
62
|
+
constructor(stageId: string, reason: string);
|
|
63
|
+
}
|
|
64
|
+
export declare class ShellStageExecError extends Error {
|
|
65
|
+
readonly stageId: string;
|
|
66
|
+
readonly exitCode: number;
|
|
67
|
+
readonly stderrSnippet: string;
|
|
68
|
+
constructor(stageId: string, exitCode: number, stderrSnippet: string);
|
|
69
|
+
}
|
|
70
|
+
export declare class ShellStageTimeoutError extends Error {
|
|
71
|
+
readonly stageId: string;
|
|
72
|
+
readonly timeoutMs: number;
|
|
73
|
+
constructor(stageId: string, timeoutMs: number);
|
|
74
|
+
}
|
|
75
|
+
export declare class ThrowingShellExecutor implements ShellExecutor {
|
|
76
|
+
private readonly reason;
|
|
77
|
+
constructor(reason: string);
|
|
78
|
+
exec(): Promise<ShellExecResult>;
|
|
79
|
+
}
|
|
80
|
+
export declare class NodeShellExecutor implements ShellExecutor {
|
|
81
|
+
exec(spec: ShellStageSpec, opts: ShellExecOptions): Promise<ShellExecResult>;
|
|
82
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* P4 — Shell stages (CLI-only).
|
|
3
|
+
*
|
|
4
|
+
* A `shell` stage lets a pipeline run a local command as part of its DAG.
|
|
5
|
+
* Useful for: running tests, linting, formatting, refactoring tools that
|
|
6
|
+
* live on the local machine.
|
|
7
|
+
*
|
|
8
|
+
* **Server-side is REJECTED.** Cloudflare Workers cannot spawn child
|
|
9
|
+
* processes. A pipeline with shell stages works only via `pipeline call
|
|
10
|
+
* --local`. The server explicitly throws `ShellStageUnsupportedError` so
|
|
11
|
+
* the user gets a clear 400 instead of a confusing 500.
|
|
12
|
+
*
|
|
13
|
+
* **Execution model:**
|
|
14
|
+
* - `spawn(cmd, args, { shell: false })` — no shell interpretation, args
|
|
15
|
+
* are passed verbatim to the OS as argv. Prevents shell injection.
|
|
16
|
+
* - `timeout` option sends SIGTERM after `timeout_ms`; the executor
|
|
17
|
+
* maps that to `ShellStageTimeoutError`.
|
|
18
|
+
* - Non-zero exit code → `ShellStageExecError` with stderr in message.
|
|
19
|
+
*
|
|
20
|
+
* **Why dynamic import of `node:child_process`:** the runtime package is
|
|
21
|
+
* also loaded by Cloudflare Workers (which have no Node bindings). Importing
|
|
22
|
+
* `child_process` at module top-level would crash Workers startup. The
|
|
23
|
+
* `NodeShellExecutor` lazily imports it inside `.exec()` so Workers
|
|
24
|
+
* never touch the binding (the server uses a throwing stub).
|
|
25
|
+
*
|
|
26
|
+
* Stage schema (two forms):
|
|
27
|
+
* shell: "npm test" # shorthand: auto-split
|
|
28
|
+
* shell: # explicit form
|
|
29
|
+
* cmd: "npm"
|
|
30
|
+
* args: ["test"]
|
|
31
|
+
* cwd: "./my-project"
|
|
32
|
+
* timeout_ms: 60000
|
|
33
|
+
*/
|
|
34
|
+
export const SHELL_DEFAULT_TIMEOUT_MS = 30_000;
|
|
35
|
+
export const SHELL_MAX_OUTPUT_BYTES = 1024 * 1024;
|
|
36
|
+
export const SHELL_MAX_TIMEOUT_MS = 600_000;
|
|
37
|
+
export function normalizeShellStage(raw) {
|
|
38
|
+
if (typeof raw === 'string') {
|
|
39
|
+
const trimmed = raw.trim();
|
|
40
|
+
if (trimmed.length === 0)
|
|
41
|
+
return null;
|
|
42
|
+
const parts = trimmed.split(/\s+/);
|
|
43
|
+
return { cmd: parts[0], args: parts.slice(1) };
|
|
44
|
+
}
|
|
45
|
+
if (!raw || typeof raw !== 'object')
|
|
46
|
+
return null;
|
|
47
|
+
const obj = raw;
|
|
48
|
+
if (typeof obj.cmd !== 'string' || obj.cmd.trim().length === 0)
|
|
49
|
+
return null;
|
|
50
|
+
const spec = { cmd: obj.cmd.trim() };
|
|
51
|
+
if (Array.isArray(obj.args)) {
|
|
52
|
+
const args = obj.args.filter((a) => typeof a === 'string');
|
|
53
|
+
if (args.length > 0)
|
|
54
|
+
spec.args = args;
|
|
55
|
+
}
|
|
56
|
+
if (typeof obj.cwd === 'string' && obj.cwd.length > 0)
|
|
57
|
+
spec.cwd = obj.cwd;
|
|
58
|
+
if (typeof obj.timeout_ms === 'number' && Number.isFinite(obj.timeout_ms) && obj.timeout_ms > 0) {
|
|
59
|
+
spec.timeout_ms = Math.min(obj.timeout_ms, SHELL_MAX_TIMEOUT_MS);
|
|
60
|
+
}
|
|
61
|
+
return spec;
|
|
62
|
+
}
|
|
63
|
+
export class ShellStageUnsupportedError extends Error {
|
|
64
|
+
stageId;
|
|
65
|
+
reason;
|
|
66
|
+
constructor(stageId, reason) {
|
|
67
|
+
super(`Stage '${stageId}' uses a shell command but ${reason}`);
|
|
68
|
+
this.stageId = stageId;
|
|
69
|
+
this.reason = reason;
|
|
70
|
+
this.name = 'SHELL_STAGE_UNSUPPORTED';
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export class ShellStageExecError extends Error {
|
|
74
|
+
stageId;
|
|
75
|
+
exitCode;
|
|
76
|
+
stderrSnippet;
|
|
77
|
+
constructor(stageId, exitCode, stderrSnippet) {
|
|
78
|
+
super(`Shell stage '${stageId}' exited with code ${exitCode}: ${stderrSnippet.slice(0, 500)}`);
|
|
79
|
+
this.stageId = stageId;
|
|
80
|
+
this.exitCode = exitCode;
|
|
81
|
+
this.stderrSnippet = stderrSnippet;
|
|
82
|
+
this.name = 'SHELL_STAGE_EXEC_FAILED';
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
export class ShellStageTimeoutError extends Error {
|
|
86
|
+
stageId;
|
|
87
|
+
timeoutMs;
|
|
88
|
+
constructor(stageId, timeoutMs) {
|
|
89
|
+
super(`Shell stage '${stageId}' exceeded timeout of ${timeoutMs}ms`);
|
|
90
|
+
this.stageId = stageId;
|
|
91
|
+
this.timeoutMs = timeoutMs;
|
|
92
|
+
this.name = 'SHELL_STAGE_TIMEOUT';
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
export class ThrowingShellExecutor {
|
|
96
|
+
reason;
|
|
97
|
+
constructor(reason) {
|
|
98
|
+
this.reason = reason;
|
|
99
|
+
}
|
|
100
|
+
async exec() {
|
|
101
|
+
throw new ShellStageUnsupportedError('<unknown>', this.reason);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
export class NodeShellExecutor {
|
|
105
|
+
async exec(spec, opts) {
|
|
106
|
+
const { spawn } = await import('node:child_process');
|
|
107
|
+
const args = spec.args ?? [];
|
|
108
|
+
const t0 = Date.now();
|
|
109
|
+
return new Promise((resolve, reject) => {
|
|
110
|
+
const child = spawn(spec.cmd, args, {
|
|
111
|
+
cwd: opts.cwd,
|
|
112
|
+
timeout: opts.timeoutMs,
|
|
113
|
+
shell: false,
|
|
114
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
115
|
+
});
|
|
116
|
+
let stdout = '';
|
|
117
|
+
let stderr = '';
|
|
118
|
+
let stdoutTruncated = false;
|
|
119
|
+
let stderrTruncated = false;
|
|
120
|
+
const onChunk = (target) => (chunk) => {
|
|
121
|
+
const text = typeof chunk === 'string' ? chunk : chunk.toString('utf-8');
|
|
122
|
+
if (target === 'stdout') {
|
|
123
|
+
if (stdout.length + text.length > SHELL_MAX_OUTPUT_BYTES) {
|
|
124
|
+
if (!stdoutTruncated) {
|
|
125
|
+
stdout = stdout.slice(0, SHELL_MAX_OUTPUT_BYTES) + '\n[stdout truncated at 1MB]';
|
|
126
|
+
stdoutTruncated = true;
|
|
127
|
+
}
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
stdout += text;
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
if (stderr.length + text.length > SHELL_MAX_OUTPUT_BYTES) {
|
|
134
|
+
if (!stderrTruncated) {
|
|
135
|
+
stderr = stderr.slice(0, SHELL_MAX_OUTPUT_BYTES) + '\n[stderr truncated at 1MB]';
|
|
136
|
+
stderrTruncated = true;
|
|
137
|
+
}
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
stderr += text;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
child.stdout.on('data', onChunk('stdout'));
|
|
144
|
+
child.stderr.on('data', onChunk('stderr'));
|
|
145
|
+
let settled = false;
|
|
146
|
+
const settle = (fn) => {
|
|
147
|
+
if (settled)
|
|
148
|
+
return;
|
|
149
|
+
settled = true;
|
|
150
|
+
fn();
|
|
151
|
+
};
|
|
152
|
+
child.on('error', (e) => {
|
|
153
|
+
settle(() => reject(e));
|
|
154
|
+
});
|
|
155
|
+
child.on('close', (code, signal) => {
|
|
156
|
+
const durationMs = Date.now() - t0;
|
|
157
|
+
if (signal === 'SIGTERM' || signal === 'SIGKILL') {
|
|
158
|
+
settle(() => reject(new ShellStageTimeoutError('<shell>', opts.timeoutMs)));
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (code === 0) {
|
|
162
|
+
settle(() => resolve({ stdout, stderr, exitCode: 0, durationMs, cmd: spec.cmd, args }));
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
settle(() => reject(new ShellStageExecError('<shell>', code ?? -1, stderr || stdout)));
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
package/dist/stages.d.ts
CHANGED
|
@@ -18,6 +18,7 @@ import type { PricingResolver } from './pricing.js';
|
|
|
18
18
|
import { createModelResolver, type ModelResolver, type PipelineLike, type PipelineStageLike, type SkillLike } from './model-resolver.js';
|
|
19
19
|
import { type PipelineEventSink } from './streaming-events.js';
|
|
20
20
|
import { type RuntimeConstraints } from './runtime-constraints.js';
|
|
21
|
+
import { type ShellExecutor } from './shell-stage.js';
|
|
21
22
|
import { type PipelineFetcher, type CompositionConfig } from './composition.js';
|
|
22
23
|
export interface ResolvedUse {
|
|
23
24
|
id: string;
|
|
@@ -88,8 +89,13 @@ export interface StageExecutorDeps {
|
|
|
88
89
|
* text and surface it when validation fails (e.g. "Output format
|
|
89
90
|
* violations: takeaway_1: key missing" without `--debug` you never
|
|
90
91
|
* see what the model actually returned).
|
|
92
|
+
*
|
|
93
|
+
* Awaited by the executor. The server's implementation writes cost
|
|
94
|
+
* telemetry and may throw `BalanceExhaustedError` to halt the run, which only
|
|
95
|
+
* works if the runtime waits for it — a fire-and-forget call turns the
|
|
96
|
+
* rejection into an unhandled rejection that never reaches the caller.
|
|
91
97
|
*/
|
|
92
|
-
onLlmResponse?: (stageId: string, rawText: string, model: string) => void
|
|
98
|
+
onLlmResponse?: (stageId: string, rawText: string, model: string) => void | Promise<void>;
|
|
93
99
|
/**
|
|
94
100
|
* Optional pipeline fetcher for composition refs (R10.7.b, ADR Q10).
|
|
95
101
|
* When supplied, runPipelineV2 walks the spec once before the loop and
|
|
@@ -115,6 +121,14 @@ export interface StageExecutorDeps {
|
|
|
115
121
|
* from `RunPipelineOptions.eventSink` by `runPipelineV2`.
|
|
116
122
|
*/
|
|
117
123
|
eventSink?: PipelineEventSink;
|
|
124
|
+
/**
|
|
125
|
+
* P4 — shell stage executor. Server passes a `ThrowingShellExecutor`
|
|
126
|
+
* that rejects every call (server cannot spawn processes). CLI passes
|
|
127
|
+
* a `NodeShellExecutor` that uses `child_process.spawn`.
|
|
128
|
+
*
|
|
129
|
+
* When absent, stages declaring `shell:` throw `ShellStageUnsupportedError`.
|
|
130
|
+
*/
|
|
131
|
+
shellExecutor?: ShellExecutor;
|
|
118
132
|
}
|
|
119
133
|
export interface RetryContext {
|
|
120
134
|
stageId: string;
|
|
@@ -137,7 +151,14 @@ export declare class StageForbiddenError extends Error {
|
|
|
137
151
|
export declare class StageBadConfigError extends Error {
|
|
138
152
|
constructor(message: string);
|
|
139
153
|
}
|
|
140
|
-
export declare function executeStage(stage: PipelineStageLike, pipeline: PipelineLike | undefined, ctx: StageContext, deps: StageExecutorDeps
|
|
154
|
+
export declare function executeStage(stage: PipelineStageLike, pipeline: PipelineLike | undefined, ctx: StageContext, deps: StageExecutorDeps,
|
|
155
|
+
/**
|
|
156
|
+
* Appended to the prompt on a validation retry. `output_retry` used to
|
|
157
|
+
* re-run the stage with byte-identical input, which only pays off when the
|
|
158
|
+
* failure was a one-off transport glitch; a stage whose output shape is
|
|
159
|
+
* wrong re-rolls the same wrong shape. See runStageWithOutputValidation.
|
|
160
|
+
*/
|
|
161
|
+
correctionHint?: string): Promise<StageExecutionResult>;
|
|
141
162
|
export interface RunPipelineOptions {
|
|
142
163
|
spec: {
|
|
143
164
|
name?: string;
|