@agentsmarket/pipeline-runtime 0.1.0
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 +94 -0
- package/bin/webhook.mjs +11 -0
- package/dist/adapters/minimax.d.ts +31 -0
- package/dist/adapters/minimax.js +69 -0
- package/dist/adapters/openrouter.d.ts +29 -0
- package/dist/adapters/openrouter.js +71 -0
- package/dist/checkpoints.d.ts +142 -0
- package/dist/checkpoints.js +192 -0
- package/dist/composition.d.ts +90 -0
- package/dist/composition.js +108 -0
- package/dist/content-hash.d.ts +7 -0
- package/dist/content-hash.js +17 -0
- package/dist/fallback.d.ts +31 -0
- package/dist/fallback.js +76 -0
- package/dist/index.d.ts +64 -0
- package/dist/index.js +61 -0
- package/dist/model-resolver.d.ts +136 -0
- package/dist/model-resolver.js +36 -0
- package/dist/parallel.d.ts +26 -0
- package/dist/parallel.js +83 -0
- package/dist/pricing.d.ts +57 -0
- package/dist/pricing.js +135 -0
- package/dist/provider-registry.d.ts +190 -0
- package/dist/provider-registry.js +333 -0
- package/dist/resolve-vars.d.ts +91 -0
- package/dist/resolve-vars.js +203 -0
- package/dist/retry.d.ts +40 -0
- package/dist/retry.js +61 -0
- package/dist/runtime-constraints.d.ts +39 -0
- package/dist/runtime-constraints.js +60 -0
- package/dist/stage-output-refs.d.ts +79 -0
- package/dist/stage-output-refs.js +107 -0
- package/dist/stages.d.ts +247 -0
- package/dist/stages.js +633 -0
- package/dist/streaming-events.d.ts +118 -0
- package/dist/streaming-events.js +132 -0
- package/dist/types.d.ts +138 -0
- package/dist/types.js +54 -0
- package/dist/webhook.d.ts +30 -0
- package/dist/webhook.js +160 -0
- package/dist/when.d.ts +55 -0
- package/dist/when.js +165 -0
- package/package.json +42 -0
package/README.md
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# @agentsmarket/pipeline-runtime
|
|
2
|
+
|
|
3
|
+
Executes PIPELINE.md files — multi-stage AI workflows.
|
|
4
|
+
|
|
5
|
+
> **Note (Phase 2):** The production executor lives in `@agentsmarket/server` (Cloudflare Worker),
|
|
6
|
+
> which runs pipelines server-side at `POST /v1/pipelines/:id/invoke` with provenance signing.
|
|
7
|
+
> The `bin/webhook.mjs` HTTP server in this package is a **local dev tool + self-hosting reference**.
|
|
8
|
+
> Use it when you want to run pipelines outside the marketplace (e.g. for testing, custom deployments,
|
|
9
|
+
> or before publishing your pipeline to `agentsmarket.world`).
|
|
10
|
+
|
|
11
|
+
## Quick start
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import { MiniMaxProvider, runPipeline, runPipelineV2 } from '@agentsmarket/pipeline-runtime';
|
|
15
|
+
|
|
16
|
+
const provider = new MiniMaxProvider(); // reads MINIMAX_API_KEY env
|
|
17
|
+
|
|
18
|
+
const pipeline = {
|
|
19
|
+
name: 'code-refactor',
|
|
20
|
+
version: '1.0.0',
|
|
21
|
+
stages: [
|
|
22
|
+
{
|
|
23
|
+
id: 'analyze',
|
|
24
|
+
provider: 'minimax', // R6: explicit provider declaration
|
|
25
|
+
model: 'MiniMax-M3',
|
|
26
|
+
system: 'You are a code analyzer.',
|
|
27
|
+
prompt: 'Analyze this code: {{code}}. List 3 improvement opportunities.',
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
id: 'refactor',
|
|
31
|
+
provider: 'minimax',
|
|
32
|
+
model: 'MiniMax-M3',
|
|
33
|
+
depends_on: ['analyze'],
|
|
34
|
+
system: 'You are a senior engineer.',
|
|
35
|
+
prompt: 'Refactor the code based on: {{analyze}}. Original: {{code}}. Return only the refactored code.',
|
|
36
|
+
},
|
|
37
|
+
],
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const result = await runPipeline(pipeline, { code: '...' }, { provider });
|
|
41
|
+
console.log(result.refactor);
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Provider ≠ Model (R6, v0.3)
|
|
45
|
+
|
|
46
|
+
As of R6 every LLM stage must declare **both** `provider:` and `model:`.
|
|
47
|
+
Auto-dispatch by model name was removed. See
|
|
48
|
+
[`docs/R6-PROVIDER-MODEL.md`](../../docs/R6-PROVIDER-MODEL.md) for the
|
|
49
|
+
full design; quick reference:
|
|
50
|
+
|
|
51
|
+
```yaml
|
|
52
|
+
stages:
|
|
53
|
+
- id: analyze
|
|
54
|
+
provider: minimax # required — one of openai|anthropic|minimax|openrouter|replicate
|
|
55
|
+
model: MiniMax-M3 # required — must be in PROVIDER_REGISTRY[provider].supportedModels
|
|
56
|
+
prompt: ...
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Use `validateR6Spec(spec)` (CLI / server) to fail-fast on invalid pairs:
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
import { validateR6Spec } from '@agentsmarket/pipeline-runtime';
|
|
63
|
+
|
|
64
|
+
const { errors } = validateR6Spec({
|
|
65
|
+
stages: [{ id: 's0', provider: 'replicate', model: 'gpt-4o', prompt: 'x' }],
|
|
66
|
+
});
|
|
67
|
+
// errors[0]: "Stage 's0': Provider 'replicate' does not support model 'gpt-4o'.
|
|
68
|
+
// Supported models for replicate: [...]"
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
For automated migration of legacy v0.2 pipelines:
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import { migrateProviderField } from '@agentsmarket/pipeline-runtime';
|
|
75
|
+
|
|
76
|
+
const migrated = migrateProviderField(legacySpec); // adds provider: minimax to LLM stages
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Provider abstraction
|
|
80
|
+
|
|
81
|
+
Pipelines reference models by name. The runtime picks a provider that knows that model:
|
|
82
|
+
|
|
83
|
+
- `minimax` — MiniMax (default). Models: `MiniMax-M3`, `MiniMax-M2.7`, `MiniMax-M1`. Env: `MINIMAX_API_KEY`.
|
|
84
|
+
- `openai` — OpenAI. Models: `gpt-4o`, `gpt-4o-mini`, `o1-preview`, `o1-mini`, `gpt-3.5-turbo`. Env: `OPENAI_API_KEY`.
|
|
85
|
+
- `anthropic` — Anthropic. Models: `claude-3-5-sonnet-20241022`, `claude-3-5-haiku-20241022`, `claude-3-opus-20240229`. Env: `ANTHROPIC_API_KEY`.
|
|
86
|
+
- `openrouter` — Multi-model gateway (`supportedModels: ['*']`). Env: `OPENROUTER_API_KEY`.
|
|
87
|
+
- `replicate` — Replicate (image gen). Models: `black-forest-labs/flux-pro`, `black-forest-labs/flux-schnell`, `stability-ai/sdxl`. Env: `REPLICATE_API_TOKEN`.
|
|
88
|
+
|
|
89
|
+
Single source of truth: `PROVIDER_REGISTRY` in
|
|
90
|
+
[`src/provider-registry.ts`](src/provider-registry.ts).
|
|
91
|
+
|
|
92
|
+
## Status
|
|
93
|
+
|
|
94
|
+
v0.3 — R6 (Provider ≠ Model) shipped. Linear + DAG stage execution. Retry, parallel branches, checkpoint.
|
package/bin/webhook.mjs
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Bob's Pipeline Webhook — bootable HTTP server.
|
|
4
|
+
* Run: node bin/webhook.mjs
|
|
5
|
+
*/
|
|
6
|
+
import { serve } from '@hono/node-server';
|
|
7
|
+
import app from '../dist/webhook.js';
|
|
8
|
+
|
|
9
|
+
serve({ fetch: app.fetch, port: app.port }, (info) => {
|
|
10
|
+
console.log(`[ready] http://localhost:${info.port}`);
|
|
11
|
+
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MiniMax provider — wraps MiniMax API which exposes an Anthropic-compatible endpoint.
|
|
3
|
+
*
|
|
4
|
+
* Endpoint: https://api.minimax.io/anthropic/v1/messages
|
|
5
|
+
* Auth: MINIMAX_API_KEY env var (or apiKey in opts)
|
|
6
|
+
*
|
|
7
|
+
* IMPORTANT: Anthropic SDK appends '/v1/messages' to baseURL.
|
|
8
|
+
* So baseURL must NOT include '/v1' (else we get '/v1/v1/messages' → 404).
|
|
9
|
+
*
|
|
10
|
+
* Models:
|
|
11
|
+
* - MiniMax-M2.7 (fast, simple tasks)
|
|
12
|
+
* - MiniMax-M2.7-highspeed (fastest, simplest)
|
|
13
|
+
* - MiniMax-M3 (slower, more capable, complex tasks)
|
|
14
|
+
*/
|
|
15
|
+
import type { LLMProvider, GenerateOptions, GenerateResult } from '../types.js';
|
|
16
|
+
import { z } from 'zod';
|
|
17
|
+
export interface MiniMaxProviderOptions {
|
|
18
|
+
apiKey?: string;
|
|
19
|
+
baseURL?: string;
|
|
20
|
+
}
|
|
21
|
+
export declare class MiniMaxProvider implements LLMProvider {
|
|
22
|
+
readonly name = "minimax";
|
|
23
|
+
readonly models: readonly ["MiniMax-M2.7", "MiniMax-M2.7-highspeed", "MiniMax-M3"];
|
|
24
|
+
readonly simpleModel = "MiniMax-M2.7";
|
|
25
|
+
readonly complexModel = "MiniMax-M3";
|
|
26
|
+
private client;
|
|
27
|
+
supports(model: string): boolean;
|
|
28
|
+
constructor(opts?: MiniMaxProviderOptions);
|
|
29
|
+
generateText(prompt: string, opts?: GenerateOptions): Promise<GenerateResult>;
|
|
30
|
+
generateJson<T>(prompt: string, schema: z.ZodSchema<T>, opts?: GenerateOptions): Promise<T>;
|
|
31
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MiniMax provider — wraps MiniMax API which exposes an Anthropic-compatible endpoint.
|
|
3
|
+
*
|
|
4
|
+
* Endpoint: https://api.minimax.io/anthropic/v1/messages
|
|
5
|
+
* Auth: MINIMAX_API_KEY env var (or apiKey in opts)
|
|
6
|
+
*
|
|
7
|
+
* IMPORTANT: Anthropic SDK appends '/v1/messages' to baseURL.
|
|
8
|
+
* So baseURL must NOT include '/v1' (else we get '/v1/v1/messages' → 404).
|
|
9
|
+
*
|
|
10
|
+
* Models:
|
|
11
|
+
* - MiniMax-M2.7 (fast, simple tasks)
|
|
12
|
+
* - MiniMax-M2.7-highspeed (fastest, simplest)
|
|
13
|
+
* - MiniMax-M3 (slower, more capable, complex tasks)
|
|
14
|
+
*/
|
|
15
|
+
import Anthropic from '@anthropic-ai/sdk';
|
|
16
|
+
// SDK appends '/v1/messages' → baseURL must NOT end with /v1
|
|
17
|
+
const DEFAULT_BASE_URL = 'https://api.minimax.io/anthropic';
|
|
18
|
+
export class MiniMaxProvider {
|
|
19
|
+
name = 'minimax';
|
|
20
|
+
models = ['MiniMax-M2.7', 'MiniMax-M2.7-highspeed', 'MiniMax-M3'];
|
|
21
|
+
simpleModel = 'MiniMax-M2.7';
|
|
22
|
+
complexModel = 'MiniMax-M3';
|
|
23
|
+
client;
|
|
24
|
+
supports(model) {
|
|
25
|
+
return this.models.includes(model);
|
|
26
|
+
}
|
|
27
|
+
constructor(opts = {}) {
|
|
28
|
+
// Workers runtime doesn't have `process` — guard access
|
|
29
|
+
const procEnv = typeof process !== 'undefined' ? process.env : undefined;
|
|
30
|
+
const apiKey = opts.apiKey || procEnv?.MINIMAX_API_KEY;
|
|
31
|
+
if (!apiKey) {
|
|
32
|
+
throw new Error('MiniMaxProvider: apiKey missing. Pass via opts.apiKey or set MINIMAX_API_KEY env var.');
|
|
33
|
+
}
|
|
34
|
+
this.client = new Anthropic({
|
|
35
|
+
apiKey,
|
|
36
|
+
baseURL: opts.baseURL || procEnv?.MINIMAX_BASE_URL || DEFAULT_BASE_URL,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
async generateText(prompt, opts = {}) {
|
|
40
|
+
const model = opts.complexity === 'complex' ? this.complexModel : this.simpleModel;
|
|
41
|
+
const response = await this.client.messages.create({
|
|
42
|
+
model,
|
|
43
|
+
max_tokens: opts.maxTokens ?? 2048,
|
|
44
|
+
temperature: opts.temperature ?? 0.7,
|
|
45
|
+
system: opts.system,
|
|
46
|
+
stop_sequences: opts.stopSequences,
|
|
47
|
+
messages: [{ role: 'user', content: prompt }],
|
|
48
|
+
});
|
|
49
|
+
const text = response.content
|
|
50
|
+
.filter((block) => block.type === 'text')
|
|
51
|
+
.map((block) => block.text)
|
|
52
|
+
.join('');
|
|
53
|
+
const usage = {
|
|
54
|
+
inputTokens: response.usage.input_tokens,
|
|
55
|
+
outputTokens: response.usage.output_tokens,
|
|
56
|
+
};
|
|
57
|
+
return { text, usage };
|
|
58
|
+
}
|
|
59
|
+
async generateJson(prompt, schema, opts = {}) {
|
|
60
|
+
const jsonPrompt = `${prompt}\\n\\nRespond ONLY with valid JSON. No markdown, no prose, no code fences.`;
|
|
61
|
+
const { text } = await this.generateText(jsonPrompt, {
|
|
62
|
+
...opts,
|
|
63
|
+
system: opts.system ?? 'You are a JSON generator. Output only valid JSON, nothing else.',
|
|
64
|
+
});
|
|
65
|
+
const cleaned = text.replace(/^```json\s*/i, '').replace(/```\s*$/, '').trim();
|
|
66
|
+
const parsed = JSON.parse(cleaned);
|
|
67
|
+
return schema.parse(parsed);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenRouter provider — multi-model gateway (Claude, GPT-4, MiniMax, etc.).
|
|
3
|
+
*
|
|
4
|
+
* Endpoint: https://openrouter.ai/api/v1/chat/completions
|
|
5
|
+
* Auth: OPENROUTER_API_KEY env var (or apiKey in opts)
|
|
6
|
+
*
|
|
7
|
+
* OpenRouter uses OpenAI-compatible format. We POST messages and parse
|
|
8
|
+
* choices[0].message.content.
|
|
9
|
+
*
|
|
10
|
+
* Model routing — pass model name in pipeline stage (e.g. "anthropic/claude-3.5-sonnet").
|
|
11
|
+
* Marketplace executes each stage with the named model; OpenRouter routes to provider.
|
|
12
|
+
*/
|
|
13
|
+
import type { LLMProvider, GenerateOptions, GenerateResult } from '../types.js';
|
|
14
|
+
import { z } from 'zod';
|
|
15
|
+
export interface OpenRouterProviderOptions {
|
|
16
|
+
apiKey?: string;
|
|
17
|
+
baseURL?: string;
|
|
18
|
+
}
|
|
19
|
+
export declare class OpenRouterProvider implements LLMProvider {
|
|
20
|
+
readonly name = "openrouter";
|
|
21
|
+
readonly models: readonly ["anthropic/claude-3.5-sonnet", "anthropic/claude-3-opus", "openai/gpt-4o", "openai/gpt-4-turbo", "MiniMax/MiniMax-M2.7", "MiniMax/MiniMax-M3"];
|
|
22
|
+
readonly simpleModel = "MiniMax/MiniMax-M2.7";
|
|
23
|
+
readonly complexModel = "anthropic/claude-3.5-sonnet";
|
|
24
|
+
private client;
|
|
25
|
+
supports(model: string): boolean;
|
|
26
|
+
constructor(opts?: OpenRouterProviderOptions);
|
|
27
|
+
generateText(prompt: string, opts?: GenerateOptions): Promise<GenerateResult>;
|
|
28
|
+
generateJson<T>(prompt: string, schema: z.ZodSchema<T>, opts?: GenerateOptions): Promise<T>;
|
|
29
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenRouter provider — multi-model gateway (Claude, GPT-4, MiniMax, etc.).
|
|
3
|
+
*
|
|
4
|
+
* Endpoint: https://openrouter.ai/api/v1/chat/completions
|
|
5
|
+
* Auth: OPENROUTER_API_KEY env var (or apiKey in opts)
|
|
6
|
+
*
|
|
7
|
+
* OpenRouter uses OpenAI-compatible format. We POST messages and parse
|
|
8
|
+
* choices[0].message.content.
|
|
9
|
+
*
|
|
10
|
+
* Model routing — pass model name in pipeline stage (e.g. "anthropic/claude-3.5-sonnet").
|
|
11
|
+
* Marketplace executes each stage with the named model; OpenRouter routes to provider.
|
|
12
|
+
*/
|
|
13
|
+
import OpenAI from 'openai';
|
|
14
|
+
const DEFAULT_BASE_URL = 'https://openrouter.ai/api/v1';
|
|
15
|
+
export class OpenRouterProvider {
|
|
16
|
+
name = 'openrouter';
|
|
17
|
+
models = [
|
|
18
|
+
'anthropic/claude-3.5-sonnet',
|
|
19
|
+
'anthropic/claude-3-opus',
|
|
20
|
+
'openai/gpt-4o',
|
|
21
|
+
'openai/gpt-4-turbo',
|
|
22
|
+
'MiniMax/MiniMax-M2.7',
|
|
23
|
+
'MiniMax/MiniMax-M3',
|
|
24
|
+
];
|
|
25
|
+
simpleModel = 'MiniMax/MiniMax-M2.7';
|
|
26
|
+
complexModel = 'anthropic/claude-3.5-sonnet';
|
|
27
|
+
client;
|
|
28
|
+
supports(model) {
|
|
29
|
+
return this.models.includes(model);
|
|
30
|
+
}
|
|
31
|
+
constructor(opts = {}) {
|
|
32
|
+
const procEnv = typeof process !== 'undefined' ? process.env : undefined;
|
|
33
|
+
const apiKey = opts.apiKey || procEnv?.OPENROUTER_API_KEY;
|
|
34
|
+
if (!apiKey) {
|
|
35
|
+
throw new Error('OpenRouterProvider: apiKey missing. Pass via opts.apiKey or set OPENROUTER_API_KEY env var.');
|
|
36
|
+
}
|
|
37
|
+
this.client = new OpenAI({
|
|
38
|
+
apiKey,
|
|
39
|
+
baseURL: opts.baseURL || procEnv?.OPENROUTER_BASE_URL || DEFAULT_BASE_URL,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
async generateText(prompt, opts = {}) {
|
|
43
|
+
const model = opts.model || (opts.complexity === 'complex' ? this.complexModel : this.simpleModel);
|
|
44
|
+
const response = await this.client.chat.completions.create({
|
|
45
|
+
model,
|
|
46
|
+
max_tokens: opts.maxTokens ?? 2048,
|
|
47
|
+
temperature: opts.temperature ?? 0.7,
|
|
48
|
+
messages: [
|
|
49
|
+
...(opts.system ? [{ role: 'system', content: opts.system }] : []),
|
|
50
|
+
{ role: 'user', content: prompt },
|
|
51
|
+
],
|
|
52
|
+
stop: opts.stopSequences,
|
|
53
|
+
});
|
|
54
|
+
const text = response.choices[0]?.message?.content ?? '';
|
|
55
|
+
const usage = {
|
|
56
|
+
inputTokens: response.usage?.prompt_tokens ?? 0,
|
|
57
|
+
outputTokens: response.usage?.completion_tokens ?? 0,
|
|
58
|
+
};
|
|
59
|
+
return { text, usage };
|
|
60
|
+
}
|
|
61
|
+
async generateJson(prompt, schema, opts = {}) {
|
|
62
|
+
const jsonPrompt = `${prompt}\n\nRespond ONLY with valid JSON. No markdown, no prose, no code fences.`;
|
|
63
|
+
const { text } = await this.generateText(jsonPrompt, {
|
|
64
|
+
...opts,
|
|
65
|
+
system: opts.system ?? 'You are a JSON generator. Output only valid JSON, nothing else.',
|
|
66
|
+
});
|
|
67
|
+
const cleaned = text.replace(/^```json\s*/i, '').replace(/```\s*$/, '').trim();
|
|
68
|
+
const parsed = JSON.parse(cleaned);
|
|
69
|
+
return schema.parse(parsed);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pipeline checkpoint storage — ADR Q6.
|
|
3
|
+
*
|
|
4
|
+
* Long pipelines (e.g., R10.5 multi-stage agent workflows) need to survive
|
|
5
|
+
* wall-clock limits (Cloudflare Workers: 30s on paid plan; 10ms-30s on free)
|
|
6
|
+
* and runner crashes. Checkpoints persist {completed outputs + pending stages +
|
|
7
|
+
* metadata} to durable storage so an interrupted run can resume without
|
|
8
|
+
* re-executing completed stages.
|
|
9
|
+
*
|
|
10
|
+
* Storage is pluggable — server wires the production R2 binding (created via
|
|
11
|
+
* `wrangler r2 bucket create agentsmarket-checkpoints` + wrangler.toml
|
|
12
|
+
* `[[env.<env>.r2_buckets]]` binding=CHECKPOINTS), tests use InMemoryCheckpointStorage.
|
|
13
|
+
*
|
|
14
|
+
* Schema version is bumped on any breaking change to `PipelineCheckpoint` shape
|
|
15
|
+
* so a stale snapshot fails fast on restore instead of silently misinterpreting.
|
|
16
|
+
*/
|
|
17
|
+
export declare const CHECKPOINT_SCHEMA_VERSION = 1;
|
|
18
|
+
export interface CompletedStageRecord {
|
|
19
|
+
id: string;
|
|
20
|
+
output: string;
|
|
21
|
+
ms: number;
|
|
22
|
+
costMicroUsdc: number;
|
|
23
|
+
model: string;
|
|
24
|
+
}
|
|
25
|
+
export interface PipelineCheckpoint {
|
|
26
|
+
schema_version: typeof CHECKPOINT_SCHEMA_VERSION;
|
|
27
|
+
run_id: string;
|
|
28
|
+
pipeline_name: string;
|
|
29
|
+
pipeline_version: string | undefined;
|
|
30
|
+
started_at: string;
|
|
31
|
+
last_snapshot_at: string;
|
|
32
|
+
inputs: Record<string, unknown>;
|
|
33
|
+
completed: CompletedStageRecord[];
|
|
34
|
+
pending: ReadonlyArray<{
|
|
35
|
+
id: string;
|
|
36
|
+
[k: string]: unknown;
|
|
37
|
+
}>;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Pluggable storage interface. Production = R2CheckpointStorage (not in this
|
|
41
|
+
* package — server wraps `c.env.CHECKPOINTS` R2 bucket binding). Tests =
|
|
42
|
+
* InMemoryCheckpointStorage. Pass null (default) to disable checkpointing
|
|
43
|
+
* entirely.
|
|
44
|
+
*/
|
|
45
|
+
export interface CheckpointStorage {
|
|
46
|
+
/** Persist `checkpoint`, return the same run_id echoed back. */
|
|
47
|
+
save(checkpoint: PipelineCheckpoint): Promise<string>;
|
|
48
|
+
/** Load a previously-saved checkpoint by run_id, or null if not found. */
|
|
49
|
+
load(run_id: string): Promise<PipelineCheckpoint | null>;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Minimal R2 bucket interface — matches both Cloudflare Workers R2Bucket and
|
|
53
|
+
* any compatible mock. We don't import @cloudflare/workers-types here so this
|
|
54
|
+
* package stays runtime-only (no worker-only deps); server-side wiring uses
|
|
55
|
+
* the real R2Bucket type via structural assignment.
|
|
56
|
+
*/
|
|
57
|
+
export interface R2BucketLike {
|
|
58
|
+
put(key: string, value: string, opts?: {
|
|
59
|
+
httpMetadata?: {
|
|
60
|
+
contentType?: string;
|
|
61
|
+
};
|
|
62
|
+
}): Promise<unknown>;
|
|
63
|
+
get(key: string): Promise<{
|
|
64
|
+
text(): Promise<string>;
|
|
65
|
+
} | null>;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Errors thrown when checkpoint operations fail. Distinct error classes so
|
|
69
|
+
* server can map to 5xx vs retryable 503.
|
|
70
|
+
*/
|
|
71
|
+
export declare class CheckpointLoadError extends Error {
|
|
72
|
+
readonly runId: string;
|
|
73
|
+
constructor(runId: string, cause: string);
|
|
74
|
+
}
|
|
75
|
+
export declare class CheckpointSaveError extends Error {
|
|
76
|
+
readonly runId: string;
|
|
77
|
+
constructor(runId: string, cause: string);
|
|
78
|
+
}
|
|
79
|
+
export declare class CheckpointSchemaMismatchError extends Error {
|
|
80
|
+
readonly runId: string;
|
|
81
|
+
readonly foundVersion: number;
|
|
82
|
+
readonly expectedVersion: number;
|
|
83
|
+
constructor(runId: string, foundVersion: number, expectedVersion: number);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* R2-backed checkpoint storage. One JSON object per run_id at
|
|
87
|
+
* `{prefix}/{run_id}.json`. Configure by passing the worker R2 binding:
|
|
88
|
+
* const storage = new R2CheckpointStorage(c.env.CHECKPOINTS);
|
|
89
|
+
*/
|
|
90
|
+
export declare class R2CheckpointStorage implements CheckpointStorage {
|
|
91
|
+
private readonly bucket;
|
|
92
|
+
private readonly prefix;
|
|
93
|
+
constructor(bucket: R2BucketLike, prefix?: string);
|
|
94
|
+
private keyFor;
|
|
95
|
+
save(checkpoint: PipelineCheckpoint): Promise<string>;
|
|
96
|
+
load(run_id: string): Promise<PipelineCheckpoint | null>;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* In-memory checkpoint storage. Used in tests and in dev when R2 isn't
|
|
100
|
+
* configured. Map keyed by run_id. NOT durable across process restarts.
|
|
101
|
+
*/
|
|
102
|
+
export declare class InMemoryCheckpointStorage implements CheckpointStorage {
|
|
103
|
+
private readonly store;
|
|
104
|
+
save(checkpoint: PipelineCheckpoint): Promise<string>;
|
|
105
|
+
load(run_id: string): Promise<PipelineCheckpoint | null>;
|
|
106
|
+
/** Test helper. */
|
|
107
|
+
has(runId: string): boolean;
|
|
108
|
+
/** Test helper. */
|
|
109
|
+
count(): number;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Build a PipelineCheckpoint from the current pipeline run state.
|
|
113
|
+
* Helper used by runPipelineV2 when snapshotting — keeps the checkpoint
|
|
114
|
+
* shape construction in one place (and unit-testable independently of
|
|
115
|
+
* the executor).
|
|
116
|
+
*/
|
|
117
|
+
export declare function buildCheckpoint(args: {
|
|
118
|
+
run_id: string;
|
|
119
|
+
pipeline_name: string;
|
|
120
|
+
pipeline_version: string | undefined;
|
|
121
|
+
started_at: string;
|
|
122
|
+
now_iso: string;
|
|
123
|
+
inputs: Record<string, unknown>;
|
|
124
|
+
completed: CompletedStageRecord[];
|
|
125
|
+
pending: PipelineCheckpoint['pending'];
|
|
126
|
+
}): PipelineCheckpoint;
|
|
127
|
+
/**
|
|
128
|
+
* Restore state from a loaded checkpoint. Returns:
|
|
129
|
+
* - `outputs`: map of completed-stage id → output (already populated, no re-exec)
|
|
130
|
+
* - `remainingStages`: stages that haven't been executed yet (must re-execute in order)
|
|
131
|
+
* - `restore`: throwaway helper decision: skip logic in runPipelineV2 will check
|
|
132
|
+
* outputs.has(id) → use that value instead of re-running.
|
|
133
|
+
*
|
|
134
|
+
* Throws if the checkpoint has zero pending AND zero completed (impossible
|
|
135
|
+
* resume state — would loop forever).
|
|
136
|
+
*/
|
|
137
|
+
export interface RestoreResult {
|
|
138
|
+
restored_outputs: Record<string, string>;
|
|
139
|
+
restored_cost: number;
|
|
140
|
+
remaining_stage_ids: string[];
|
|
141
|
+
}
|
|
142
|
+
export declare function restoreFromCheckpoint(checkpoint: PipelineCheckpoint): RestoreResult;
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pipeline checkpoint storage — ADR Q6.
|
|
3
|
+
*
|
|
4
|
+
* Long pipelines (e.g., R10.5 multi-stage agent workflows) need to survive
|
|
5
|
+
* wall-clock limits (Cloudflare Workers: 30s on paid plan; 10ms-30s on free)
|
|
6
|
+
* and runner crashes. Checkpoints persist {completed outputs + pending stages +
|
|
7
|
+
* metadata} to durable storage so an interrupted run can resume without
|
|
8
|
+
* re-executing completed stages.
|
|
9
|
+
*
|
|
10
|
+
* Storage is pluggable — server wires the production R2 binding (created via
|
|
11
|
+
* `wrangler r2 bucket create agentsmarket-checkpoints` + wrangler.toml
|
|
12
|
+
* `[[env.<env>.r2_buckets]]` binding=CHECKPOINTS), tests use InMemoryCheckpointStorage.
|
|
13
|
+
*
|
|
14
|
+
* Schema version is bumped on any breaking change to `PipelineCheckpoint` shape
|
|
15
|
+
* so a stale snapshot fails fast on restore instead of silently misinterpreting.
|
|
16
|
+
*/
|
|
17
|
+
export const CHECKPOINT_SCHEMA_VERSION = 1;
|
|
18
|
+
/**
|
|
19
|
+
* Errors thrown when checkpoint operations fail. Distinct error classes so
|
|
20
|
+
* server can map to 5xx vs retryable 503.
|
|
21
|
+
*/
|
|
22
|
+
export class CheckpointLoadError extends Error {
|
|
23
|
+
runId;
|
|
24
|
+
constructor(runId, cause) {
|
|
25
|
+
super(`Failed to load checkpoint for run_id=${runId}: ${cause}`);
|
|
26
|
+
this.runId = runId;
|
|
27
|
+
this.name = 'CHECKPOINT_LOAD_FAILED';
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export class CheckpointSaveError extends Error {
|
|
31
|
+
runId;
|
|
32
|
+
constructor(runId, cause) {
|
|
33
|
+
super(`Failed to save checkpoint for run_id=${runId}: ${cause}`);
|
|
34
|
+
this.runId = runId;
|
|
35
|
+
this.name = 'CHECKPOINT_SAVE_FAILED';
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export class CheckpointSchemaMismatchError extends Error {
|
|
39
|
+
runId;
|
|
40
|
+
foundVersion;
|
|
41
|
+
expectedVersion;
|
|
42
|
+
constructor(runId, foundVersion, expectedVersion) {
|
|
43
|
+
super(`Checkpoint for run_id=${runId} has schema_version=${foundVersion}, ` +
|
|
44
|
+
`runtime expects ${expectedVersion}. ` +
|
|
45
|
+
`(bump CHECKPOINT_SCHEMA_VERSION if the shape change was intentional)`);
|
|
46
|
+
this.runId = runId;
|
|
47
|
+
this.foundVersion = foundVersion;
|
|
48
|
+
this.expectedVersion = expectedVersion;
|
|
49
|
+
this.name = 'CHECKPOINT_SCHEMA_MISMATCH';
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* R2-backed checkpoint storage. One JSON object per run_id at
|
|
54
|
+
* `{prefix}/{run_id}.json`. Configure by passing the worker R2 binding:
|
|
55
|
+
* const storage = new R2CheckpointStorage(c.env.CHECKPOINTS);
|
|
56
|
+
*/
|
|
57
|
+
export class R2CheckpointStorage {
|
|
58
|
+
bucket;
|
|
59
|
+
prefix;
|
|
60
|
+
constructor(bucket, prefix = 'checkpoints') {
|
|
61
|
+
this.bucket = bucket;
|
|
62
|
+
this.prefix = prefix;
|
|
63
|
+
}
|
|
64
|
+
keyFor(runId) {
|
|
65
|
+
return `${this.prefix}/${runId}.json`;
|
|
66
|
+
}
|
|
67
|
+
async save(checkpoint) {
|
|
68
|
+
try {
|
|
69
|
+
const body = JSON.stringify(checkpoint);
|
|
70
|
+
await this.bucket.put(this.keyFor(checkpoint.run_id), body, {
|
|
71
|
+
httpMetadata: { contentType: 'application/json' },
|
|
72
|
+
});
|
|
73
|
+
return checkpoint.run_id;
|
|
74
|
+
}
|
|
75
|
+
catch (e) {
|
|
76
|
+
throw new CheckpointSaveError(checkpoint.run_id, e.message);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async load(run_id) {
|
|
80
|
+
let obj;
|
|
81
|
+
try {
|
|
82
|
+
obj = await this.bucket.get(this.keyFor(run_id));
|
|
83
|
+
}
|
|
84
|
+
catch (e) {
|
|
85
|
+
throw new CheckpointLoadError(run_id, e.message);
|
|
86
|
+
}
|
|
87
|
+
if (!obj)
|
|
88
|
+
return null;
|
|
89
|
+
let text;
|
|
90
|
+
try {
|
|
91
|
+
text = await obj.text();
|
|
92
|
+
}
|
|
93
|
+
catch (e) {
|
|
94
|
+
throw new CheckpointLoadError(run_id, `object read failed: ${e.message}`);
|
|
95
|
+
}
|
|
96
|
+
let parsed;
|
|
97
|
+
try {
|
|
98
|
+
parsed = JSON.parse(text);
|
|
99
|
+
}
|
|
100
|
+
catch (e) {
|
|
101
|
+
throw new CheckpointLoadError(run_id, `JSON parse failed: ${e.message}`);
|
|
102
|
+
}
|
|
103
|
+
if (typeof parsed !== 'object' || parsed === null) {
|
|
104
|
+
throw new CheckpointLoadError(run_id, 'decoded value is not an object');
|
|
105
|
+
}
|
|
106
|
+
const o = parsed;
|
|
107
|
+
const schemaVersion = o.schema_version;
|
|
108
|
+
if (typeof schemaVersion !== 'number') {
|
|
109
|
+
throw new CheckpointLoadError(run_id, 'missing or non-numeric schema_version');
|
|
110
|
+
}
|
|
111
|
+
if (schemaVersion !== CHECKPOINT_SCHEMA_VERSION) {
|
|
112
|
+
throw new CheckpointSchemaMismatchError(run_id, schemaVersion, CHECKPOINT_SCHEMA_VERSION);
|
|
113
|
+
}
|
|
114
|
+
if (!isPipelineCheckpoint(parsed)) {
|
|
115
|
+
throw new CheckpointLoadError(run_id, 'decoded object does not match PipelineCheckpoint shape');
|
|
116
|
+
}
|
|
117
|
+
return parsed;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* In-memory checkpoint storage. Used in tests and in dev when R2 isn't
|
|
122
|
+
* configured. Map keyed by run_id. NOT durable across process restarts.
|
|
123
|
+
*/
|
|
124
|
+
export class InMemoryCheckpointStorage {
|
|
125
|
+
store = new Map();
|
|
126
|
+
async save(checkpoint) {
|
|
127
|
+
this.store.set(checkpoint.run_id, checkpoint);
|
|
128
|
+
return checkpoint.run_id;
|
|
129
|
+
}
|
|
130
|
+
async load(run_id) {
|
|
131
|
+
return this.store.get(run_id) ?? null;
|
|
132
|
+
}
|
|
133
|
+
/** Test helper. */
|
|
134
|
+
has(runId) {
|
|
135
|
+
return this.store.has(runId);
|
|
136
|
+
}
|
|
137
|
+
/** Test helper. */
|
|
138
|
+
count() {
|
|
139
|
+
return this.store.size;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
function isPipelineCheckpoint(o) {
|
|
143
|
+
if (!o || typeof o !== 'object')
|
|
144
|
+
return false;
|
|
145
|
+
const r = o;
|
|
146
|
+
return (r.schema_version === CHECKPOINT_SCHEMA_VERSION &&
|
|
147
|
+
typeof r.run_id === 'string' &&
|
|
148
|
+
typeof r.pipeline_name === 'string' &&
|
|
149
|
+
typeof r.started_at === 'string' &&
|
|
150
|
+
typeof r.last_snapshot_at === 'string' &&
|
|
151
|
+
Array.isArray(r.completed) &&
|
|
152
|
+
Array.isArray(r.pending) &&
|
|
153
|
+
typeof r.inputs === 'object' &&
|
|
154
|
+
r.inputs !== null);
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Build a PipelineCheckpoint from the current pipeline run state.
|
|
158
|
+
* Helper used by runPipelineV2 when snapshotting — keeps the checkpoint
|
|
159
|
+
* shape construction in one place (and unit-testable independently of
|
|
160
|
+
* the executor).
|
|
161
|
+
*/
|
|
162
|
+
export function buildCheckpoint(args) {
|
|
163
|
+
return {
|
|
164
|
+
schema_version: CHECKPOINT_SCHEMA_VERSION,
|
|
165
|
+
run_id: args.run_id,
|
|
166
|
+
pipeline_name: args.pipeline_name,
|
|
167
|
+
pipeline_version: args.pipeline_version,
|
|
168
|
+
started_at: args.started_at,
|
|
169
|
+
last_snapshot_at: args.now_iso,
|
|
170
|
+
inputs: args.inputs,
|
|
171
|
+
completed: args.completed,
|
|
172
|
+
pending: args.pending,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
export function restoreFromCheckpoint(checkpoint) {
|
|
176
|
+
const outputs = {};
|
|
177
|
+
let cost = 0;
|
|
178
|
+
for (const c of checkpoint.completed) {
|
|
179
|
+
outputs[c.id] = c.output;
|
|
180
|
+
cost += c.costMicroUsdc;
|
|
181
|
+
}
|
|
182
|
+
const remaining = checkpoint.pending.map((s) => s.id);
|
|
183
|
+
if (Object.keys(outputs).length === 0 && remaining.length === 0) {
|
|
184
|
+
throw new Error(`Cannot restore from empty checkpoint (run_id=${checkpoint.run_id}); ` +
|
|
185
|
+
`refusing to loop forever`);
|
|
186
|
+
}
|
|
187
|
+
return {
|
|
188
|
+
restored_outputs: outputs,
|
|
189
|
+
restored_cost: cost,
|
|
190
|
+
remaining_stage_ids: remaining,
|
|
191
|
+
};
|
|
192
|
+
}
|