@crewhaus/target-cf-worker-workflow 0.3.2 → 0.4.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/dist/index.d.ts +25 -19
- package/dist/index.js +252 -175
- package/package.json +9 -5
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CrewhausError } from "@crewhaus/errors";
|
|
2
|
-
import { type Bundle, type IrWorkflowV0 } from "@crewhaus/ir";
|
|
2
|
+
import { type Bundle, type IrWorkflowStep, type IrWorkflowV0 } from "@crewhaus/ir";
|
|
3
3
|
export type EmitOptions = {
|
|
4
4
|
/**
|
|
5
5
|
* Origins the generated Worker should accept on `/chat`. Defaults to the
|
|
@@ -13,28 +13,34 @@ export type EmitOptions = {
|
|
|
13
13
|
};
|
|
14
14
|
/**
|
|
15
15
|
* Emit a Cloudflare Worker bundle for a WORKFLOW-target IR. Workflow sibling
|
|
16
|
-
* of `@crewhaus/target-cf-worker-cli`'s `emitCfWorkerCli`: same
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
* call; the prior step's terminal assistant text is threaded into the next
|
|
20
|
-
* step's user message (mirrors `@crewhaus/target-workflow`'s local runtime).
|
|
16
|
+
* of `@crewhaus/target-cf-worker-cli`'s `emitCfWorkerCli`: same `/chat` SSE
|
|
17
|
+
* protocol, but instead of a single agent it runs the IR's steps sequentially
|
|
18
|
+
* server-side, threading each step's terminal assistant text into the next.
|
|
21
19
|
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
* - `wrangler.toml` — deploy descriptor for users who do prefer CLI
|
|
30
|
-
* - `package.json` — declares the runtime version stamp
|
|
31
|
-
*
|
|
32
|
-
* M2 emits a tools-free Worker (the cli sibling does the same). Tools,
|
|
33
|
-
* sub-agents, MCP, hooks, and the security fabric port over when we point the
|
|
34
|
-
* emitter at a shared worker runtime instead of inlining the client.
|
|
20
|
+
* Loop contract 0.4 (Batch F, G12/G83) — each step now runs the SHARED
|
|
21
|
+
* `runWorkerLoop` from `@crewhaus/worker-runtime` over a stateless
|
|
22
|
+
* {@link WorkerPlatform}, so a step gains REAL tools (the edge-safe set),
|
|
23
|
+
* budget, limits, and the Batch C trace frames THROUGH the shared runtime.
|
|
24
|
+
* Host tools are rejected at compile time; a step that overflows its context
|
|
25
|
+
* ends the run with a classified error frame (no compaction on the edge). The
|
|
26
|
+
* `/chat` `text`/`done`/`error` vocabulary is byte-compatible.
|
|
35
27
|
*/
|
|
36
28
|
export declare function emitCfWorkerWorkflow(ir: IrWorkflowV0, opts?: EmitOptions): Bundle;
|
|
37
29
|
export declare class TargetEmitError extends CrewhausError {
|
|
38
30
|
readonly name = "TargetEmitError";
|
|
39
31
|
constructor(message: string, cause?: unknown);
|
|
40
32
|
}
|
|
33
|
+
export type EdgeToolWiring = {
|
|
34
|
+
readonly imports: string;
|
|
35
|
+
readonly inits: string;
|
|
36
|
+
/** One `TOOLS` array expression per step, in step order. */
|
|
37
|
+
readonly stepTools: readonly string[];
|
|
38
|
+
readonly packages: readonly string[];
|
|
39
|
+
readonly unwired: readonly string[];
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Resolve edge-safe tool wiring across every step: ONE import block (deduped
|
|
43
|
+
* across steps) + per-step `TOOLS` arrays. Host tools in any step hard-fail the
|
|
44
|
+
* compile. `justify`/MCP/custom tools are permitted but left unwired.
|
|
45
|
+
*/
|
|
46
|
+
export declare function resolveWorkflowTools(steps: readonly IrWorkflowStep[]): EdgeToolWiring;
|
package/dist/index.js
CHANGED
|
@@ -1,54 +1,43 @@
|
|
|
1
1
|
import { CrewhausError } from "@crewhaus/errors";
|
|
2
2
|
import { escapeJsonString } from "@crewhaus/infra-utils";
|
|
3
|
-
import { renderBundleReadme } from "@crewhaus/ir";
|
|
3
|
+
import { renderBundleReadme, } from "@crewhaus/ir";
|
|
4
4
|
import { parseModelString } from "@crewhaus/model-router";
|
|
5
|
+
import { partitionEdgeTools } from "@crewhaus/worker-runtime/tool-policy";
|
|
5
6
|
const DEFAULT_ALLOWED_ORIGINS = ["https://studio.crewhaus.ai", "http://localhost:4322"];
|
|
6
7
|
/**
|
|
7
8
|
* Emit a Cloudflare Worker bundle for a WORKFLOW-target IR. Workflow sibling
|
|
8
|
-
* of `@crewhaus/target-cf-worker-cli`'s `emitCfWorkerCli`: same
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* call; the prior step's terminal assistant text is threaded into the next
|
|
12
|
-
* step's user message (mirrors `@crewhaus/target-workflow`'s local runtime).
|
|
9
|
+
* of `@crewhaus/target-cf-worker-cli`'s `emitCfWorkerCli`: same `/chat` SSE
|
|
10
|
+
* protocol, but instead of a single agent it runs the IR's steps sequentially
|
|
11
|
+
* server-side, threading each step's terminal assistant text into the next.
|
|
13
12
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
* - `wrangler.toml` — deploy descriptor for users who do prefer CLI
|
|
22
|
-
* - `package.json` — declares the runtime version stamp
|
|
23
|
-
*
|
|
24
|
-
* M2 emits a tools-free Worker (the cli sibling does the same). Tools,
|
|
25
|
-
* sub-agents, MCP, hooks, and the security fabric port over when we point the
|
|
26
|
-
* emitter at a shared worker runtime instead of inlining the client.
|
|
13
|
+
* Loop contract 0.4 (Batch F, G12/G83) — each step now runs the SHARED
|
|
14
|
+
* `runWorkerLoop` from `@crewhaus/worker-runtime` over a stateless
|
|
15
|
+
* {@link WorkerPlatform}, so a step gains REAL tools (the edge-safe set),
|
|
16
|
+
* budget, limits, and the Batch C trace frames THROUGH the shared runtime.
|
|
17
|
+
* Host tools are rejected at compile time; a step that overflows its context
|
|
18
|
+
* ends the run with a classified error frame (no compaction on the edge). The
|
|
19
|
+
* `/chat` `text`/`done`/`error` vocabulary is byte-compatible.
|
|
27
20
|
*/
|
|
28
21
|
export function emitCfWorkerWorkflow(ir, opts = {}) {
|
|
29
22
|
if (ir.target !== "workflow") {
|
|
30
23
|
throw new TargetEmitError(`emitCfWorkerWorkflow requires target "workflow", got "${ir.target}"`);
|
|
31
24
|
}
|
|
32
25
|
for (const step of ir.steps) {
|
|
33
|
-
// Provider gate — the
|
|
34
|
-
//
|
|
35
|
-
// would compile cleanly and 502 at runtime. Fail at compile time instead.
|
|
26
|
+
// Provider gate — the shared runtime's edge adapter POSTs each step's model
|
|
27
|
+
// verbatim, so a non-Anthropic model string would 502 at runtime.
|
|
36
28
|
assertAnthropicModel(step.model, `step "${step.name}"`);
|
|
37
|
-
if (step.tools.length > 0) {
|
|
38
|
-
throw new TargetEmitError(`cf-worker-workflow does not yet support tools (step "${step.name}"); use the local workflow target`);
|
|
39
|
-
}
|
|
40
29
|
}
|
|
30
|
+
// Loop contract 0.4 (Batch F, G12/G83) — the edge-safety tool gate replaces
|
|
31
|
+
// the old blanket "does not support tools" rejection, per step.
|
|
32
|
+
const wiring = resolveWorkflowTools(ir.steps);
|
|
41
33
|
const allowedOrigins = opts.allowedOrigins && opts.allowedOrigins.length > 0
|
|
42
34
|
? [...opts.allowedOrigins]
|
|
43
35
|
: DEFAULT_ALLOWED_ORIGINS;
|
|
44
36
|
const files = [
|
|
45
|
-
{ path: "worker.js", content: renderWorker(ir, allowedOrigins) },
|
|
37
|
+
{ path: "worker.js", content: renderWorker(ir, wiring, allowedOrigins) },
|
|
46
38
|
{ path: "wrangler.toml", content: renderWrangler(ir) },
|
|
47
|
-
{ path: "package.json", content: renderPackageJson(ir) },
|
|
39
|
+
{ path: "package.json", content: renderPackageJson(ir, wiring) },
|
|
48
40
|
];
|
|
49
|
-
// Item 42 — generated bundle README; default ON. The default per-target
|
|
50
|
-
// run snippet keys on ir.target ("workflow" → `bun agent.ts`), which is
|
|
51
|
-
// wrong for a Worker bundle, so substitute the wrangler flow.
|
|
52
41
|
if (opts.readme !== false) {
|
|
53
42
|
files.push({ path: "README.md", content: renderBundleReadme(ir, CF_WORKER_README_OPTS) });
|
|
54
43
|
}
|
|
@@ -59,12 +48,12 @@ const CF_WORKER_README_OPTS = {
|
|
|
59
48
|
heading: "Deploy",
|
|
60
49
|
body: [
|
|
61
50
|
"```sh",
|
|
62
|
-
"
|
|
63
|
-
"wrangler
|
|
51
|
+
"npm install # resolve the crewhaus runtime + tools",
|
|
52
|
+
"wrangler secret put ANTHROPIC_API_KEY # one-time Worker secret",
|
|
53
|
+
"wrangler deploy # bundles worker.js + its imports",
|
|
64
54
|
"```",
|
|
65
55
|
].join("\n"),
|
|
66
56
|
},
|
|
67
|
-
// A deployed Worker has no local `.crewhaus/` workspace.
|
|
68
57
|
includeWorkspaceNote: false,
|
|
69
58
|
};
|
|
70
59
|
export class TargetEmitError extends CrewhausError {
|
|
@@ -75,8 +64,7 @@ export class TargetEmitError extends CrewhausError {
|
|
|
75
64
|
}
|
|
76
65
|
/**
|
|
77
66
|
* Reject any model string the router would dispatch to a non-Anthropic
|
|
78
|
-
* provider
|
|
79
|
-
* client only speaks the Anthropic Messages API.
|
|
67
|
+
* provider — the edge adapter only speaks the Anthropic Messages API.
|
|
80
68
|
*/
|
|
81
69
|
function assertAnthropicModel(model, where) {
|
|
82
70
|
let providerId;
|
|
@@ -90,44 +78,176 @@ function assertAnthropicModel(model, where) {
|
|
|
90
78
|
throw new TargetEmitError(`${where} model "${model}" routes to provider "${providerId}" — cf-worker targets currently support claude-* models only — use the cli target for other providers`);
|
|
91
79
|
}
|
|
92
80
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
81
|
+
const EDGE_TOOL_IMPORTS = {
|
|
82
|
+
fetch: { package: "@crewhaus/tool-fetch", export: "fetch", initSymbol: "registerFetchConfig" },
|
|
83
|
+
webFetch: {
|
|
84
|
+
package: "@crewhaus/tool-web",
|
|
85
|
+
export: "webFetch",
|
|
86
|
+
initSymbol: "registerWebFetchConfig",
|
|
87
|
+
},
|
|
88
|
+
webSearch: { package: "@crewhaus/tool-web", export: "webSearch" },
|
|
89
|
+
sendMessage: { package: "@crewhaus/tool-message-channel", export: "sendMessage" },
|
|
90
|
+
imageGenerate: {
|
|
91
|
+
package: "@crewhaus/tool-image-generation",
|
|
92
|
+
export: "imageGenerate",
|
|
93
|
+
initSymbol: "registerImageGenerationConfig",
|
|
94
|
+
},
|
|
95
|
+
todoWrite: { package: "@crewhaus/tool-todo", export: "todoWrite" },
|
|
96
|
+
};
|
|
97
|
+
/** Classify one unit's tools: THROW on host tools, return the wireable
|
|
98
|
+
* edge-safe builtins (order-preserving, deduped) + the permitted-but-unwired
|
|
99
|
+
* names (custom + MCP). */
|
|
100
|
+
function classifyUnitTools(names) {
|
|
101
|
+
const { rejected, warned, allowed } = partitionEdgeTools(names);
|
|
102
|
+
if (rejected.length > 0) {
|
|
103
|
+
const detail = rejected.map((r) => r.reason).join("; ");
|
|
104
|
+
throw new TargetEmitError(`cf-worker target cannot run ${rejected.length} host tool(s): ${detail}. These need a host (process/filesystem/sandbox/device) the edge does not provide — use the cli target for them, or remove them.`);
|
|
105
|
+
}
|
|
106
|
+
const seen = new Set();
|
|
107
|
+
const wired = [];
|
|
108
|
+
for (const name of names) {
|
|
109
|
+
if (seen.has(name))
|
|
110
|
+
continue;
|
|
111
|
+
seen.add(name);
|
|
112
|
+
if (EDGE_TOOL_IMPORTS[name] !== undefined)
|
|
113
|
+
wired.push(name);
|
|
114
|
+
}
|
|
115
|
+
const unwired = [
|
|
116
|
+
...allowed.filter((n) => EDGE_TOOL_IMPORTS[n] === undefined),
|
|
117
|
+
...warned.map((w) => w.name),
|
|
118
|
+
];
|
|
119
|
+
return { wired, unwired };
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Resolve edge-safe tool wiring across every step: ONE import block (deduped
|
|
123
|
+
* across steps) + per-step `TOOLS` arrays. Host tools in any step hard-fail the
|
|
124
|
+
* compile. `justify`/MCP/custom tools are permitted but left unwired.
|
|
125
|
+
*/
|
|
126
|
+
export function resolveWorkflowTools(steps) {
|
|
127
|
+
const stepWired = [];
|
|
128
|
+
const allUnwired = new Set();
|
|
129
|
+
// Global import grouping + first-config-wins init calls.
|
|
130
|
+
const byPackage = new Map();
|
|
131
|
+
const initEmitted = new Set();
|
|
132
|
+
const inits = [];
|
|
133
|
+
for (const step of steps) {
|
|
134
|
+
const { wired, unwired } = classifyUnitTools(step.tools);
|
|
135
|
+
stepWired.push(wired);
|
|
136
|
+
for (const u of unwired)
|
|
137
|
+
allUnwired.add(u);
|
|
138
|
+
for (const name of wired) {
|
|
139
|
+
const entry = EDGE_TOOL_IMPORTS[name];
|
|
140
|
+
if (entry === undefined)
|
|
141
|
+
continue;
|
|
142
|
+
const group = byPackage.get(entry.package) ?? {
|
|
143
|
+
specs: new Set(),
|
|
144
|
+
extras: new Set(),
|
|
145
|
+
};
|
|
146
|
+
group.specs.add(`${entry.export} as __t_${name}`);
|
|
147
|
+
if (entry.initSymbol !== undefined) {
|
|
148
|
+
const cfg = step.toolConfigs[name];
|
|
149
|
+
if (cfg !== undefined && !initEmitted.has(entry.initSymbol)) {
|
|
150
|
+
group.extras.add(entry.initSymbol);
|
|
151
|
+
inits.push(`${entry.initSymbol}(${JSON.stringify(cfg)});`);
|
|
152
|
+
initEmitted.add(entry.initSymbol);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
byPackage.set(entry.package, group);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const importLines = [];
|
|
159
|
+
for (const pkg of [...byPackage.keys()].sort()) {
|
|
160
|
+
const group = byPackage.get(pkg);
|
|
161
|
+
if (group === undefined)
|
|
162
|
+
continue;
|
|
163
|
+
const symbols = [...[...group.specs].sort(), ...[...group.extras].sort()].join(", ");
|
|
164
|
+
importLines.push(`import { ${symbols} } from "${pkg}";`);
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
imports: importLines.join("\n"),
|
|
168
|
+
inits: inits.join("\n"),
|
|
169
|
+
stepTools: stepWired.map((w) => `[${w.map((n) => `__t_${n}`).join(", ")}]`),
|
|
170
|
+
packages: [...byPackage.keys()].sort(),
|
|
171
|
+
unwired: [...allUnwired],
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
/** Map the IR's `limits:` block to the runWorkerLoop `limits` subset the edge
|
|
175
|
+
* honours (justify escalation degrades to warn). */
|
|
176
|
+
function renderLimits(limits) {
|
|
177
|
+
if (limits === undefined)
|
|
178
|
+
return "undefined";
|
|
179
|
+
const out = {};
|
|
180
|
+
if (limits.maxToolIterations !== undefined)
|
|
181
|
+
out["maxToolIterations"] = limits.maxToolIterations;
|
|
182
|
+
if (limits.contextLimit !== undefined)
|
|
183
|
+
out["contextLimit"] = limits.contextLimit;
|
|
184
|
+
if (limits.deadlineMs !== undefined)
|
|
185
|
+
out["deadlineMs"] = limits.deadlineMs;
|
|
186
|
+
if (limits.loopDetection !== undefined) {
|
|
187
|
+
const ld = {};
|
|
188
|
+
if (limits.loopDetection.window !== undefined)
|
|
189
|
+
ld["window"] = limits.loopDetection.window;
|
|
190
|
+
if (limits.loopDetection.threshold !== undefined)
|
|
191
|
+
ld["threshold"] = limits.loopDetection.threshold;
|
|
192
|
+
if (limits.loopDetection.escalation !== undefined) {
|
|
193
|
+
ld["escalation"] =
|
|
194
|
+
limits.loopDetection.escalation === "justify" ? "warn" : limits.loopDetection.escalation;
|
|
195
|
+
}
|
|
196
|
+
if (Object.keys(ld).length > 0)
|
|
197
|
+
out["loopDetection"] = ld;
|
|
198
|
+
}
|
|
199
|
+
return Object.keys(out).length > 0 ? JSON.stringify(out) : "undefined";
|
|
200
|
+
}
|
|
201
|
+
function edgeToolNote(unwired) {
|
|
202
|
+
if (unwired.length === 0)
|
|
203
|
+
return "";
|
|
204
|
+
return `// note: ${unwired.length} tool(s) permitted but not wired on this edge worker (${unwired.join(", ")}) — custom tools cannot be verified fetch/KV-only offline, and mcp__* tools arrive from mcp_servers (unwired on cf-worker); they are omitted from the model's tool set\n`;
|
|
205
|
+
}
|
|
206
|
+
// --------------------------------------------------------------------------
|
|
207
|
+
// worker.js
|
|
208
|
+
// --------------------------------------------------------------------------
|
|
209
|
+
function renderWorker(ir, wiring, allowedOrigins) {
|
|
98
210
|
const name = escapeJsonString(ir.name);
|
|
99
|
-
// Build the steps array literal by hand so each field is escaped exactly
|
|
100
|
-
// once. Same fixed-bug discipline as the cli emitter: escapeJsonString
|
|
101
|
-
// already returns a quoted literal, so the surrounding object literal just
|
|
102
|
-
// interpolates it directly.
|
|
103
211
|
const steps = ir.steps
|
|
104
212
|
.map((step) => {
|
|
105
213
|
const stepName = escapeJsonString(step.name);
|
|
106
214
|
const stepModel = escapeJsonString(step.model);
|
|
107
215
|
const stepInstructions = escapeJsonString(step.instructions);
|
|
108
|
-
|
|
216
|
+
const maxTokens = step.maxTokens ?? 4096;
|
|
217
|
+
const thinking = step.thinking !== undefined ? JSON.stringify(step.thinking) : "undefined";
|
|
218
|
+
return ` { name: ${stepName}, model: ${stepModel}, instructions: ${stepInstructions}, maxTokens: ${maxTokens}, thinking: ${thinking} }`;
|
|
109
219
|
})
|
|
110
220
|
.join(",\n");
|
|
111
221
|
const allowed = JSON.stringify(allowedOrigins);
|
|
112
|
-
|
|
113
|
-
// (
|
|
114
|
-
//
|
|
222
|
+
const limits = renderLimits(ir.limits);
|
|
223
|
+
// Loop contract 0.4 (Batch C, item 3). IrWorkflowV0 does not carry an
|
|
224
|
+
// `observability` field today; the structural read keeps the gate
|
|
225
|
+
// forward-compatible (defaults to trace-ON, honours an explicit off).
|
|
226
|
+
const traceEnabled = (ir.observability?.trace?.level ??
|
|
227
|
+
"ring") !== "off";
|
|
115
228
|
const taxonomyWarning = ir.failureTaxonomy !== undefined && ir.failureTaxonomy.length > 0
|
|
116
|
-
? "// note: failure_taxonomy configured but target-cf-worker-workflow does not
|
|
229
|
+
? "// note: failure_taxonomy configured but target-cf-worker-workflow does not wire it up on the edge — it is ignored\n"
|
|
117
230
|
: "";
|
|
231
|
+
const toolNote = edgeToolNote(wiring.unwired);
|
|
232
|
+
const toolImports = wiring.imports.length > 0 ? `${wiring.imports}\n` : "";
|
|
233
|
+
const toolInits = wiring.inits.length > 0 ? `\n${wiring.inits}\n` : "";
|
|
234
|
+
const stepTools = `[${wiring.stepTools.join(", ")}]`;
|
|
118
235
|
return `// Generated by @crewhaus/target-cf-worker-workflow. Do not edit by hand.
|
|
119
236
|
// Regenerate via the studio PWA or \`crewhaus compile --target cf-worker-workflow\`.
|
|
120
|
-
${taxonomyWarning}
|
|
237
|
+
${taxonomyWarning}${toolNote}import { runWorkerLoop, createEdgeAnthropicAdapter } from "@crewhaus/worker-runtime";
|
|
238
|
+
${toolImports}${toolInits}
|
|
121
239
|
const CONFIG = {
|
|
122
240
|
name: ${name},
|
|
123
241
|
steps: [
|
|
124
242
|
${steps}
|
|
125
243
|
],
|
|
126
244
|
allowedOrigins: ${allowed},
|
|
245
|
+
trace: ${traceEnabled},
|
|
246
|
+
limits: ${limits},
|
|
127
247
|
};
|
|
128
248
|
|
|
129
|
-
|
|
130
|
-
const
|
|
249
|
+
// One real edge-safe RegisteredTool array per step, in step order.
|
|
250
|
+
const STEP_TOOLS = ${stepTools};
|
|
131
251
|
|
|
132
252
|
export default {
|
|
133
253
|
async fetch(request, env) {
|
|
@@ -162,50 +282,98 @@ async function handleChat(request, env, cors) {
|
|
|
162
282
|
}
|
|
163
283
|
|
|
164
284
|
// The workflow's initial input is the user's latest message text. Anthropic
|
|
165
|
-
// rejects empty user content
|
|
166
|
-
// the local workflow target's stdin-empty placeholder).
|
|
285
|
+
// rejects empty user content, so fall back to "begin".
|
|
167
286
|
let initialInput = "";
|
|
168
287
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
169
288
|
if (messages[i].role === "user") { initialInput = messages[i].content; break; }
|
|
170
289
|
}
|
|
171
290
|
if (!initialInput) initialInput = "begin";
|
|
172
291
|
|
|
173
|
-
//
|
|
174
|
-
//
|
|
175
|
-
|
|
292
|
+
// A stateless WorkerPlatform: clock + id resolved at the request boundary,
|
|
293
|
+
// the platform fetch, and no KV binding.
|
|
294
|
+
const platform = {
|
|
295
|
+
now: () => Date.now(),
|
|
296
|
+
randomId: () => crypto.randomUUID(),
|
|
297
|
+
fetch: (input, init) => fetch(input, init),
|
|
298
|
+
};
|
|
299
|
+
|
|
176
300
|
const stream = new ReadableStream({
|
|
177
301
|
async start(controller) {
|
|
178
302
|
const enc = new TextEncoder();
|
|
179
303
|
const emit = (event, data) => {
|
|
180
304
|
controller.enqueue(enc.encode(\`event: \${event}\\ndata: \${JSON.stringify(data)}\\n\\n\`));
|
|
181
305
|
};
|
|
306
|
+
const emitTrace = (event) => { if (CONFIG.trace) emit("trace", event); };
|
|
307
|
+
const base = createEdgeAnthropicAdapter(platform, { apiKey: env.ANTHROPIC_API_KEY });
|
|
182
308
|
const total = CONFIG.steps.length;
|
|
309
|
+
|
|
183
310
|
try {
|
|
184
311
|
let priorOutput = "";
|
|
185
312
|
for (let i = 0; i < total; i++) {
|
|
186
313
|
const step = CONFIG.steps[i];
|
|
187
314
|
const stepNum = i + 1;
|
|
188
|
-
|
|
189
|
-
//
|
|
190
|
-
//
|
|
315
|
+
const isLast = i === total - 1;
|
|
316
|
+
// First step gets the user text; later steps get a synthetic message
|
|
317
|
+
// embedding the prior step's output.
|
|
191
318
|
const userContent =
|
|
192
319
|
i === 0
|
|
193
320
|
? initialInput
|
|
194
321
|
: \`## Output of previous step:\\n\${priorOutput}\\n\\n## Your task:\\n(continue based on the previous step's output)\`;
|
|
195
322
|
|
|
196
|
-
// Progress marker so the user sees the workflow advancing. The chat
|
|
197
|
-
// panel appends text deltas, so this renders inline.
|
|
198
323
|
emit("text", { text: \`\\n[step \${stepNum}/\${total}: \${step.name}]\\n\` });
|
|
324
|
+
emitTrace({ kind: "step_start", name: step.name, step: stepNum, total });
|
|
325
|
+
|
|
326
|
+
// Only the final step streams text to the client; intermediate steps
|
|
327
|
+
// thread their terminal text into the next step.
|
|
328
|
+
let acc = "";
|
|
329
|
+
let lastStop = "end_turn";
|
|
330
|
+
const adapter = isLast
|
|
331
|
+
? {
|
|
332
|
+
...base,
|
|
333
|
+
async *stream(req) {
|
|
334
|
+
for await (const ev of base.stream(req)) {
|
|
335
|
+
if (ev.kind === "content_block_delta" && ev.delta && ev.delta.type === "text_delta") {
|
|
336
|
+
acc += ev.delta.text;
|
|
337
|
+
emit("text", { text: ev.delta.text });
|
|
338
|
+
}
|
|
339
|
+
yield ev;
|
|
340
|
+
}
|
|
341
|
+
},
|
|
342
|
+
}
|
|
343
|
+
: base;
|
|
344
|
+
const trace = (event) => {
|
|
345
|
+
if (event.kind === "model_response" && typeof event.stopReason === "string") {
|
|
346
|
+
lastStop = event.stopReason;
|
|
347
|
+
}
|
|
348
|
+
emitTrace(event);
|
|
349
|
+
};
|
|
199
350
|
|
|
200
|
-
|
|
201
|
-
|
|
351
|
+
const startedAt = platform.now();
|
|
352
|
+
const result = await runWorkerLoop({
|
|
353
|
+
platform,
|
|
354
|
+
adapter,
|
|
355
|
+
model: step.model,
|
|
356
|
+
instructions: step.instructions,
|
|
357
|
+
messages: [{ role: "user", content: userContent }],
|
|
358
|
+
tools: STEP_TOOLS[i],
|
|
359
|
+
maxTokens: step.maxTokens,
|
|
360
|
+
...(step.thinking ? { thinking: step.thinking } : {}),
|
|
361
|
+
...(CONFIG.limits ? { limits: CONFIG.limits } : {}),
|
|
362
|
+
emitTrace: trace,
|
|
363
|
+
});
|
|
364
|
+
if (result.failure) {
|
|
365
|
+
emit("error", { message: \`step "\${step.name}": \${result.failure.title}: \${result.failure.detail}\` });
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
emitTrace({ kind: "step_end", name: step.name, step: stepNum, durationMs: platform.now() - startedAt });
|
|
369
|
+
|
|
370
|
+
if (isLast) {
|
|
371
|
+
emit("done", { text: acc || result.text, stopReason: lastStop });
|
|
202
372
|
} else {
|
|
203
|
-
|
|
204
|
-
emit("done", { text: final.text, stopReason: final.stopReason });
|
|
373
|
+
priorOutput = result.text;
|
|
205
374
|
}
|
|
206
375
|
}
|
|
207
|
-
//
|
|
208
|
-
// Emit a terminal done so the client doesn't hang.
|
|
376
|
+
// A zero-step workflow can't reach the streaming branch; terminate.
|
|
209
377
|
if (total === 0) emit("done", { text: "", stopReason: "end_turn" });
|
|
210
378
|
} catch (err) {
|
|
211
379
|
emit("error", { message: err && err.message ? err.message : String(err) });
|
|
@@ -226,97 +394,6 @@ async function handleChat(request, env, cors) {
|
|
|
226
394
|
});
|
|
227
395
|
}
|
|
228
396
|
|
|
229
|
-
// One non-streaming Anthropic call. Reads the full JSON response and
|
|
230
|
-
// concatenates the text blocks into a single string.
|
|
231
|
-
async function runStepNonStreaming(env, step, userContent) {
|
|
232
|
-
const upstream = await fetch(ANTHROPIC_URL, {
|
|
233
|
-
method: "POST",
|
|
234
|
-
headers: {
|
|
235
|
-
"Content-Type": "application/json",
|
|
236
|
-
"x-api-key": env.ANTHROPIC_API_KEY,
|
|
237
|
-
"anthropic-version": ANTHROPIC_VERSION,
|
|
238
|
-
},
|
|
239
|
-
body: JSON.stringify({
|
|
240
|
-
model: step.model,
|
|
241
|
-
max_tokens: 4096,
|
|
242
|
-
system: step.instructions,
|
|
243
|
-
stream: false,
|
|
244
|
-
messages: [{ role: "user", content: userContent }],
|
|
245
|
-
}),
|
|
246
|
-
});
|
|
247
|
-
if (!upstream.ok) {
|
|
248
|
-
const text = await upstream.text().catch(() => "");
|
|
249
|
-
throw new Error(\`upstream \${upstream.status}: \${text.slice(0, 500)}\`);
|
|
250
|
-
}
|
|
251
|
-
const payload = await upstream.json();
|
|
252
|
-
let acc = "";
|
|
253
|
-
if (payload && Array.isArray(payload.content)) {
|
|
254
|
-
for (const block of payload.content) {
|
|
255
|
-
if (block && block.type === "text" && typeof block.text === "string") acc += block.text;
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
return acc;
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
// One streaming Anthropic call. Translates Anthropic's SSE stream into the
|
|
262
|
-
// studio's simpler {text} delta vocabulary (the caller emits the terminal
|
|
263
|
-
// \`done\`). Buffers across chunks because events can split mid-line. Returns
|
|
264
|
-
// the accumulated text + stop reason for the \`done\` event.
|
|
265
|
-
async function runStepStreaming(env, step, userContent, emit) {
|
|
266
|
-
const upstream = await fetch(ANTHROPIC_URL, {
|
|
267
|
-
method: "POST",
|
|
268
|
-
headers: {
|
|
269
|
-
"Content-Type": "application/json",
|
|
270
|
-
"x-api-key": env.ANTHROPIC_API_KEY,
|
|
271
|
-
"anthropic-version": ANTHROPIC_VERSION,
|
|
272
|
-
},
|
|
273
|
-
body: JSON.stringify({
|
|
274
|
-
model: step.model,
|
|
275
|
-
max_tokens: 4096,
|
|
276
|
-
system: step.instructions,
|
|
277
|
-
stream: true,
|
|
278
|
-
messages: [{ role: "user", content: userContent }],
|
|
279
|
-
}),
|
|
280
|
-
});
|
|
281
|
-
|
|
282
|
-
if (!upstream.ok || !upstream.body) {
|
|
283
|
-
const text = await upstream.text().catch(() => "");
|
|
284
|
-
throw new Error(\`upstream \${upstream.status}: \${text.slice(0, 500)}\`);
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
const dec = new TextDecoder();
|
|
288
|
-
const reader = upstream.body.getReader();
|
|
289
|
-
let buffer = "";
|
|
290
|
-
let acc = "";
|
|
291
|
-
let stopReason = "end_turn";
|
|
292
|
-
while (true) {
|
|
293
|
-
const { value, done } = await reader.read();
|
|
294
|
-
if (done) break;
|
|
295
|
-
buffer += dec.decode(value, { stream: true });
|
|
296
|
-
let sep;
|
|
297
|
-
while ((sep = buffer.indexOf("\\n\\n")) !== -1) {
|
|
298
|
-
const raw = buffer.slice(0, sep);
|
|
299
|
-
buffer = buffer.slice(sep + 2);
|
|
300
|
-
let eventName = "message";
|
|
301
|
-
let data = "";
|
|
302
|
-
for (const line of raw.split("\\n")) {
|
|
303
|
-
if (line.startsWith("event: ")) eventName = line.slice(7);
|
|
304
|
-
else if (line.startsWith("data: ")) data += line.slice(6);
|
|
305
|
-
}
|
|
306
|
-
if (!data || data === "[DONE]") continue;
|
|
307
|
-
let payload;
|
|
308
|
-
try { payload = JSON.parse(data); } catch { continue; }
|
|
309
|
-
if (eventName === "content_block_delta" && payload.delta && payload.delta.type === "text_delta") {
|
|
310
|
-
acc += payload.delta.text;
|
|
311
|
-
emit("text", { text: payload.delta.text });
|
|
312
|
-
} else if (eventName === "message_delta" && payload.delta && payload.delta.stop_reason) {
|
|
313
|
-
stopReason = payload.delta.stop_reason;
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
return { text: acc, stopReason };
|
|
318
|
-
}
|
|
319
|
-
|
|
320
397
|
function normalizeMessages(raw) {
|
|
321
398
|
if (!Array.isArray(raw)) return null;
|
|
322
399
|
const out = [];
|
|
@@ -354,7 +431,9 @@ main = "worker.js"
|
|
|
354
431
|
compatibility_date = "2026-05-01"
|
|
355
432
|
compatibility_flags = ["nodejs_compat"]
|
|
356
433
|
|
|
357
|
-
#
|
|
434
|
+
# worker.js imports @crewhaus/worker-runtime and the edge-safe tool packages;
|
|
435
|
+
# \`wrangler deploy\` bundles them (run \`npm install\` first). ANTHROPIC_API_KEY
|
|
436
|
+
# is a Worker Secret (never committed):
|
|
358
437
|
# wrangler secret put ANTHROPIC_API_KEY
|
|
359
438
|
# The studio PWA sets this automatically via the Deploy flow.
|
|
360
439
|
|
|
@@ -362,20 +441,18 @@ compatibility_flags = ["nodejs_compat"]
|
|
|
362
441
|
enabled = true
|
|
363
442
|
`;
|
|
364
443
|
}
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
// string (this manifest is reachable from the hosted compiler-worker HTTP
|
|
368
|
-
// endpoint), allowing dependency/script injection into package.json (#148).
|
|
444
|
+
const RUNTIME_DEP_RANGE = "^0.3.0";
|
|
445
|
+
function renderPackageJson(ir, wiring) {
|
|
369
446
|
const safeName = ir.name.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
`;
|
|
447
|
+
const deps = { "@crewhaus/worker-runtime": RUNTIME_DEP_RANGE };
|
|
448
|
+
for (const pkg of wiring.packages)
|
|
449
|
+
deps[pkg] = RUNTIME_DEP_RANGE;
|
|
450
|
+
return `${JSON.stringify({
|
|
451
|
+
name: safeName,
|
|
452
|
+
version: "0.0.0",
|
|
453
|
+
private: true,
|
|
454
|
+
type: "module",
|
|
455
|
+
scripts: { deploy: "wrangler deploy", dev: "wrangler dev --local" },
|
|
456
|
+
dependencies: deps,
|
|
457
|
+
}, null, 2)}\n`;
|
|
381
458
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crewhaus/target-cf-worker-workflow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Codegen backend for the workflow target emitted as a Cloudflare Worker. Sibling of target-cf-worker-cli; reads the same IrWorkflowV0 variant, emits a self-contained Worker bundle that runs the steps sequentially.",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -15,10 +15,14 @@
|
|
|
15
15
|
"test": "bun test src"
|
|
16
16
|
},
|
|
17
17
|
"dependencies": {
|
|
18
|
-
"@crewhaus/errors": "0.
|
|
19
|
-
"@crewhaus/infra-utils": "0.
|
|
20
|
-
"@crewhaus/ir": "0.
|
|
21
|
-
"@crewhaus/model-router": "0.
|
|
18
|
+
"@crewhaus/errors": "0.4.0",
|
|
19
|
+
"@crewhaus/infra-utils": "0.4.0",
|
|
20
|
+
"@crewhaus/ir": "0.4.0",
|
|
21
|
+
"@crewhaus/model-router": "0.4.0",
|
|
22
|
+
"@crewhaus/worker-runtime": "0.4.0"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"@crewhaus/tool-todo": "0.4.0"
|
|
22
26
|
},
|
|
23
27
|
"license": "Apache-2.0",
|
|
24
28
|
"author": {
|