@crewhaus/target-cf-worker-workflow 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/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@crewhaus/target-cf-worker-workflow",
3
+ "version": "0.1.0",
4
+ "type": "module",
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
+ "main": "src/index.ts",
7
+ "types": "src/index.ts",
8
+ "exports": {
9
+ ".": "./src/index.ts"
10
+ },
11
+ "scripts": {
12
+ "test": "bun test src"
13
+ },
14
+ "dependencies": {
15
+ "@crewhaus/errors": "0.0.0",
16
+ "@crewhaus/infra-utils": "0.0.0",
17
+ "@crewhaus/ir": "0.0.0"
18
+ },
19
+ "license": "Apache-2.0",
20
+ "author": {
21
+ "name": "Max Meier",
22
+ "email": "max@studiomax.io",
23
+ "url": "https://studiomax.io"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/crewhaus/factory.git",
28
+ "directory": "packages/target-cf-worker-workflow"
29
+ },
30
+ "homepage": "https://github.com/crewhaus/factory/tree/main/packages/target-cf-worker-workflow#readme",
31
+ "bugs": {
32
+ "url": "https://github.com/crewhaus/factory/issues"
33
+ },
34
+ "publishConfig": {
35
+ "access": "restricted"
36
+ },
37
+ "files": [
38
+ "src",
39
+ "README.md",
40
+ "LICENSE",
41
+ "NOTICE"
42
+ ]
43
+ }
@@ -0,0 +1,119 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { IrWorkflowStep, IrWorkflowV0 } from "@crewhaus/ir";
3
+ import { TargetEmitError, emitCfWorkerWorkflow } from "./index";
4
+
5
+ const step = (over: Partial<IrWorkflowStep> = {}): IrWorkflowStep => ({
6
+ name: "research",
7
+ instructions: "You are a research assistant.",
8
+ model: "claude-haiku-4-5-20251001",
9
+ tools: [],
10
+ toolConfigs: Object.freeze({}),
11
+ ...over,
12
+ });
13
+
14
+ const baseIr: IrWorkflowV0 = {
15
+ version: 0,
16
+ name: "summarize-flow",
17
+ target: "workflow",
18
+ steps: [
19
+ step({ name: "research", instructions: "Research the topic thoroughly." }),
20
+ step({
21
+ name: "draft",
22
+ instructions: "Draft a summary from the research.",
23
+ model: "claude-sonnet-4-5-20250929",
24
+ }),
25
+ step({
26
+ name: "polish",
27
+ instructions: "Polish the draft into final prose.",
28
+ model: "claude-opus-4-5-20250101",
29
+ }),
30
+ ],
31
+ mcp_servers: Object.freeze({}),
32
+ permissions: { rules: [] },
33
+ compaction: {},
34
+ };
35
+
36
+ describe("emitCfWorkerWorkflow", () => {
37
+ test("emits worker.js, wrangler.toml, and package.json", () => {
38
+ const bundle = emitCfWorkerWorkflow(baseIr);
39
+ const paths = bundle.files.map((f) => f.path).sort();
40
+ expect(paths).toEqual(["package.json", "worker.js", "wrangler.toml"]);
41
+ });
42
+
43
+ test("worker.js inlines each step's model and instructions and the Anthropic endpoint", () => {
44
+ const bundle = emitCfWorkerWorkflow(baseIr);
45
+ const worker = bundle.files.find((f) => f.path === "worker.js");
46
+ expect(worker?.content).toContain("api.anthropic.com");
47
+ for (const s of baseIr.steps) {
48
+ expect(worker?.content).toContain(s.model);
49
+ expect(worker?.content).toContain(s.instructions);
50
+ expect(worker?.content).toContain(s.name);
51
+ }
52
+ });
53
+
54
+ test("worker.js threads the prior step's output into later steps", () => {
55
+ const worker = emitCfWorkerWorkflow(baseIr).files.find((f) => f.path === "worker.js");
56
+ // The synthetic framing for steps 2..N (mirrors target-workflow).
57
+ expect(worker?.content).toContain("## Output of previous step:");
58
+ // Empty user input falls back to "begin" like the local workflow target.
59
+ expect(worker?.content).toContain("begin");
60
+ });
61
+
62
+ test("wrangler.toml uses sanitized spec name", () => {
63
+ const ir: IrWorkflowV0 = { ...baseIr, name: "Summarize Flow!" };
64
+ const bundle = emitCfWorkerWorkflow(ir);
65
+ const wrangler = bundle.files.find((f) => f.path === "wrangler.toml");
66
+ expect(wrangler?.content).toContain('name = "summarize-flow-"');
67
+ });
68
+
69
+ test("worker.js escapes special characters in instructions", () => {
70
+ const ir: IrWorkflowV0 = {
71
+ ...baseIr,
72
+ steps: [step({ instructions: 'Respond with "quoted" text\nand newlines.' })],
73
+ };
74
+ const bundle = emitCfWorkerWorkflow(ir);
75
+ const worker = bundle.files.find((f) => f.path === "worker.js");
76
+ expect(worker?.content).toContain('\\"quoted\\"');
77
+ expect(worker?.content).toContain("\\n");
78
+ });
79
+
80
+ test("rejects non-workflow IR variants", () => {
81
+ const wrong = { ...baseIr, target: "cli" } as unknown as IrWorkflowV0;
82
+ expect(() => emitCfWorkerWorkflow(wrong)).toThrow(TargetEmitError);
83
+ });
84
+
85
+ test("rejects steps with tools until M2+", () => {
86
+ const ir: IrWorkflowV0 = {
87
+ ...baseIr,
88
+ steps: [step({ name: "research" }), step({ name: "draft", tools: ["read", "write"] })],
89
+ };
90
+ expect(() => emitCfWorkerWorkflow(ir)).toThrow(TargetEmitError);
91
+ });
92
+
93
+ // Regression: the cli emitter previously wrapped JSON.stringify output in an
94
+ // extra pair of quotes (`name: ""x""`), which Cloudflare rejected at upload
95
+ // with "Unexpected identifier". The substring assertions above miss it, so
96
+ // parse the whole module instead.
97
+ const parseJs = (code: string) => new Bun.Transpiler({ loader: "js" }).transformSync(code);
98
+
99
+ test("worker.js is syntactically valid JavaScript", () => {
100
+ const worker = emitCfWorkerWorkflow(baseIr).files.find((f) => f.path === "worker.js");
101
+ expect(() => parseJs(worker?.content ?? "")).not.toThrow();
102
+ });
103
+
104
+ test("worker.js stays valid with hyphenated name and tricky instructions", () => {
105
+ const ir: IrWorkflowV0 = {
106
+ ...baseIr,
107
+ name: "summarize-flow",
108
+ steps: [
109
+ step({
110
+ name: "tricky-step",
111
+ instructions: 'Quotes "here", a newline\nhere, a ${dollar} and a ` backtick.',
112
+ }),
113
+ step({ name: "second-step", instructions: "Plain second step." }),
114
+ ],
115
+ };
116
+ const worker = emitCfWorkerWorkflow(ir).files.find((f) => f.path === "worker.js");
117
+ expect(() => parseJs(worker?.content ?? "")).not.toThrow();
118
+ });
119
+ });
package/src/index.ts ADDED
@@ -0,0 +1,353 @@
1
+ import { CrewhausError } from "@crewhaus/errors";
2
+ import { escapeJsonString } from "@crewhaus/infra-utils";
3
+ import type { Bundle, IrWorkflowV0 } from "@crewhaus/ir";
4
+
5
+ export type EmitOptions = {
6
+ /**
7
+ * Origins the generated Worker should accept on `/chat`. Defaults to the
8
+ * production studio + local dev. Threading this through compile-time
9
+ * lets the studio PWA bake its own origin in so users can host the PWA
10
+ * anywhere (pages.dev, ngrok, LAN IP) without editing the emitter.
11
+ */
12
+ readonly allowedOrigins?: readonly string[];
13
+ };
14
+
15
+ const DEFAULT_ALLOWED_ORIGINS = ["https://studio.crewhaus.dev", "http://localhost:4322"];
16
+
17
+ /**
18
+ * Emit a Cloudflare Worker bundle for a WORKFLOW-target IR. Workflow sibling
19
+ * of `@crewhaus/target-cf-worker-cli`'s `emitCfWorkerCli`: same self-contained
20
+ * Worker shape and `/chat` SSE protocol, but instead of a single agent it runs
21
+ * the IR's steps sequentially server-side. Each step is one single-turn LLM
22
+ * call; the prior step's terminal assistant text is threaded into the next
23
+ * step's user message (mirrors `@crewhaus/target-workflow`'s local runtime).
24
+ *
25
+ * Like the cli emitter, the worker is fully self-contained — it inlines a
26
+ * minimal Anthropic streaming-SSE client so the studio PWA can upload the
27
+ * bundle directly via the Cloudflare API without a build step on the user's
28
+ * device.
29
+ *
30
+ * Bundle contents:
31
+ * - `worker.js` — entrypoint, runs as an ES module Worker
32
+ * - `wrangler.toml` — deploy descriptor for users who do prefer CLI
33
+ * - `package.json` — declares the runtime version stamp
34
+ *
35
+ * M2 emits a tools-free Worker (the cli sibling does the same). Tools,
36
+ * sub-agents, MCP, hooks, and the security fabric port over when we point the
37
+ * emitter at a shared worker runtime instead of inlining the client.
38
+ */
39
+ export function emitCfWorkerWorkflow(ir: IrWorkflowV0, opts: EmitOptions = {}): Bundle {
40
+ if (ir.target !== "workflow") {
41
+ throw new TargetEmitError(
42
+ `emitCfWorkerWorkflow requires target "workflow", got "${ir.target}"`,
43
+ );
44
+ }
45
+ for (const step of ir.steps) {
46
+ if (step.tools.length > 0) {
47
+ throw new TargetEmitError(
48
+ `cf-worker-workflow does not yet support tools (step "${step.name}"); use the local workflow target`,
49
+ );
50
+ }
51
+ }
52
+ const allowedOrigins =
53
+ opts.allowedOrigins && opts.allowedOrigins.length > 0
54
+ ? [...opts.allowedOrigins]
55
+ : DEFAULT_ALLOWED_ORIGINS;
56
+ return {
57
+ files: [
58
+ { path: "worker.js", content: renderWorker(ir, allowedOrigins) },
59
+ { path: "wrangler.toml", content: renderWrangler(ir) },
60
+ { path: "package.json", content: renderPackageJson(ir) },
61
+ ],
62
+ };
63
+ }
64
+
65
+ export class TargetEmitError extends CrewhausError {
66
+ override readonly name = "TargetEmitError";
67
+ constructor(message: string, cause?: unknown) {
68
+ super("compiler", message, cause);
69
+ }
70
+ }
71
+
72
+ function renderWorker(ir: IrWorkflowV0, allowedOrigins: readonly string[]): string {
73
+ // escapeJsonString === JSON.stringify: each of these is a COMPLETE,
74
+ // quoted JS/JSON string literal already. Do NOT wrap them in extra quotes
75
+ // in the template below, or the output becomes `name: ""my-workflow""` — a
76
+ // syntax error Cloudflare rejects at upload time.
77
+ const name = escapeJsonString(ir.name);
78
+ // Build the steps array literal by hand so each field is escaped exactly
79
+ // once. Same fixed-bug discipline as the cli emitter: escapeJsonString
80
+ // already returns a quoted literal, so the surrounding object literal just
81
+ // interpolates it directly.
82
+ const steps = ir.steps
83
+ .map((step) => {
84
+ const stepName = escapeJsonString(step.name);
85
+ const stepModel = escapeJsonString(step.model);
86
+ const stepInstructions = escapeJsonString(step.instructions);
87
+ return ` { name: ${stepName}, model: ${stepModel}, instructions: ${stepInstructions} }`;
88
+ })
89
+ .join(",\n");
90
+ const allowed = JSON.stringify(allowedOrigins);
91
+
92
+ return `// Generated by @crewhaus/target-cf-worker-workflow. Do not edit by hand.
93
+ // Regenerate via the studio PWA or \`crewhaus compile --target cf-worker-workflow\`.
94
+
95
+ const CONFIG = {
96
+ name: ${name},
97
+ steps: [
98
+ ${steps}
99
+ ],
100
+ allowedOrigins: ${allowed},
101
+ };
102
+
103
+ const ANTHROPIC_URL = "https://api.anthropic.com/v1/messages";
104
+ const ANTHROPIC_VERSION = "2023-06-01";
105
+
106
+ export default {
107
+ async fetch(request, env) {
108
+ const origin = request.headers.get("origin");
109
+ const cors = buildCors(origin);
110
+ if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: cors });
111
+
112
+ const url = new URL(request.url);
113
+ if (request.method === "GET" && url.pathname === "/health") {
114
+ return json({ ok: true, harness: CONFIG.name }, 200, cors);
115
+ }
116
+ if (request.method === "POST" && url.pathname === "/chat") {
117
+ return handleChat(request, env, cors);
118
+ }
119
+ return json({ error: { code: "NOT_FOUND" } }, 404, cors);
120
+ },
121
+ };
122
+
123
+ async function handleChat(request, env, cors) {
124
+ if (!env.ANTHROPIC_API_KEY) {
125
+ return json({ error: { code: "NO_KEY", message: "ANTHROPIC_API_KEY not configured" } }, 500, cors);
126
+ }
127
+ let body;
128
+ try {
129
+ body = await request.json();
130
+ } catch {
131
+ return json({ error: { code: "BAD_JSON" } }, 400, cors);
132
+ }
133
+ const messages = normalizeMessages(body && body.messages);
134
+ if (!messages) {
135
+ return json({ error: { code: "BAD_REQUEST", message: "messages must be an array of {role,content}" } }, 400, cors);
136
+ }
137
+
138
+ // The workflow's initial input is the user's latest message text. Anthropic
139
+ // rejects empty user content with a 400, so fall back to "begin" (matches
140
+ // the local workflow target's stdin-empty placeholder).
141
+ let initialInput = "";
142
+ for (let i = messages.length - 1; i >= 0; i--) {
143
+ if (messages[i].role === "user") { initialInput = messages[i].content; break; }
144
+ }
145
+ if (!initialInput) initialInput = "begin";
146
+
147
+ // Run steps 1..N-1 as non-streaming calls server-side, threading each
148
+ // step's terminal assistant text into the next. The FINAL step streams via
149
+ // the inlined SSE translator so the chat panel renders tokens live.
150
+ const stream = new ReadableStream({
151
+ async start(controller) {
152
+ const enc = new TextEncoder();
153
+ const emit = (event, data) => {
154
+ controller.enqueue(enc.encode(\`event: \${event}\\ndata: \${JSON.stringify(data)}\\n\\n\`));
155
+ };
156
+ const total = CONFIG.steps.length;
157
+ try {
158
+ let priorOutput = "";
159
+ for (let i = 0; i < total; i++) {
160
+ const step = CONFIG.steps[i];
161
+ const stepNum = i + 1;
162
+ // First step gets the incoming user text; later steps get a
163
+ // synthetic message embedding the prior step's output (mirrors the
164
+ // local workflow target's \`## Output of previous step:\` framing).
165
+ const userContent =
166
+ i === 0
167
+ ? initialInput
168
+ : \`## Output of previous step:\\n\${priorOutput}\\n\\n## Your task:\\n(continue based on the previous step's output)\`;
169
+
170
+ // Progress marker so the user sees the workflow advancing. The chat
171
+ // panel appends text deltas, so this renders inline.
172
+ emit("text", { text: \`\\n[step \${stepNum}/\${total}: \${step.name}]\\n\` });
173
+
174
+ if (i < total - 1) {
175
+ priorOutput = await runStepNonStreaming(env, step, userContent);
176
+ } else {
177
+ const final = await runStepStreaming(env, step, userContent, emit);
178
+ emit("done", { text: final.text, stopReason: final.stopReason });
179
+ }
180
+ }
181
+ // Defensive: a zero-step workflow can't reach the streaming branch.
182
+ // Emit a terminal done so the client doesn't hang.
183
+ if (total === 0) emit("done", { text: "", stopReason: "end_turn" });
184
+ } catch (err) {
185
+ emit("error", { message: err && err.message ? err.message : String(err) });
186
+ } finally {
187
+ controller.close();
188
+ }
189
+ },
190
+ });
191
+
192
+ return new Response(stream, {
193
+ status: 200,
194
+ headers: {
195
+ "Content-Type": "text/event-stream; charset=utf-8",
196
+ "Cache-Control": "no-cache, no-transform",
197
+ Connection: "keep-alive",
198
+ ...cors,
199
+ },
200
+ });
201
+ }
202
+
203
+ // One non-streaming Anthropic call. Reads the full JSON response and
204
+ // concatenates the text blocks into a single string.
205
+ async function runStepNonStreaming(env, step, userContent) {
206
+ const upstream = await fetch(ANTHROPIC_URL, {
207
+ method: "POST",
208
+ headers: {
209
+ "Content-Type": "application/json",
210
+ "x-api-key": env.ANTHROPIC_API_KEY,
211
+ "anthropic-version": ANTHROPIC_VERSION,
212
+ },
213
+ body: JSON.stringify({
214
+ model: step.model,
215
+ max_tokens: 4096,
216
+ system: step.instructions,
217
+ stream: false,
218
+ messages: [{ role: "user", content: userContent }],
219
+ }),
220
+ });
221
+ if (!upstream.ok) {
222
+ const text = await upstream.text().catch(() => "");
223
+ throw new Error(\`upstream \${upstream.status}: \${text.slice(0, 500)}\`);
224
+ }
225
+ const payload = await upstream.json();
226
+ let acc = "";
227
+ if (payload && Array.isArray(payload.content)) {
228
+ for (const block of payload.content) {
229
+ if (block && block.type === "text" && typeof block.text === "string") acc += block.text;
230
+ }
231
+ }
232
+ return acc;
233
+ }
234
+
235
+ // One streaming Anthropic call. Translates Anthropic's SSE stream into the
236
+ // studio's simpler {text} delta vocabulary (the caller emits the terminal
237
+ // \`done\`). Buffers across chunks because events can split mid-line. Returns
238
+ // the accumulated text + stop reason for the \`done\` event.
239
+ async function runStepStreaming(env, step, userContent, emit) {
240
+ const upstream = await fetch(ANTHROPIC_URL, {
241
+ method: "POST",
242
+ headers: {
243
+ "Content-Type": "application/json",
244
+ "x-api-key": env.ANTHROPIC_API_KEY,
245
+ "anthropic-version": ANTHROPIC_VERSION,
246
+ },
247
+ body: JSON.stringify({
248
+ model: step.model,
249
+ max_tokens: 4096,
250
+ system: step.instructions,
251
+ stream: true,
252
+ messages: [{ role: "user", content: userContent }],
253
+ }),
254
+ });
255
+
256
+ if (!upstream.ok || !upstream.body) {
257
+ const text = await upstream.text().catch(() => "");
258
+ throw new Error(\`upstream \${upstream.status}: \${text.slice(0, 500)}\`);
259
+ }
260
+
261
+ const dec = new TextDecoder();
262
+ const reader = upstream.body.getReader();
263
+ let buffer = "";
264
+ let acc = "";
265
+ let stopReason = "end_turn";
266
+ while (true) {
267
+ const { value, done } = await reader.read();
268
+ if (done) break;
269
+ buffer += dec.decode(value, { stream: true });
270
+ let sep;
271
+ while ((sep = buffer.indexOf("\\n\\n")) !== -1) {
272
+ const raw = buffer.slice(0, sep);
273
+ buffer = buffer.slice(sep + 2);
274
+ let eventName = "message";
275
+ let data = "";
276
+ for (const line of raw.split("\\n")) {
277
+ if (line.startsWith("event: ")) eventName = line.slice(7);
278
+ else if (line.startsWith("data: ")) data += line.slice(6);
279
+ }
280
+ if (!data || data === "[DONE]") continue;
281
+ let payload;
282
+ try { payload = JSON.parse(data); } catch { continue; }
283
+ if (eventName === "content_block_delta" && payload.delta && payload.delta.type === "text_delta") {
284
+ acc += payload.delta.text;
285
+ emit("text", { text: payload.delta.text });
286
+ } else if (eventName === "message_delta" && payload.delta && payload.delta.stop_reason) {
287
+ stopReason = payload.delta.stop_reason;
288
+ }
289
+ }
290
+ }
291
+ return { text: acc, stopReason };
292
+ }
293
+
294
+ function normalizeMessages(raw) {
295
+ if (!Array.isArray(raw)) return null;
296
+ const out = [];
297
+ for (const item of raw) {
298
+ if (!item || typeof item !== "object") return null;
299
+ if (item.role !== "user" && item.role !== "assistant") return null;
300
+ if (typeof item.content !== "string") return null;
301
+ out.push({ role: item.role, content: item.content });
302
+ }
303
+ return out;
304
+ }
305
+
306
+ function buildCors(origin) {
307
+ const allow = origin && CONFIG.allowedOrigins.includes(origin) ? origin : CONFIG.allowedOrigins[0];
308
+ return {
309
+ "Access-Control-Allow-Origin": allow,
310
+ "Access-Control-Allow-Methods": "GET,POST,OPTIONS",
311
+ "Access-Control-Allow-Headers": "Content-Type",
312
+ Vary: "Origin",
313
+ };
314
+ }
315
+
316
+ function json(body, status, cors) {
317
+ return new Response(JSON.stringify(body), {
318
+ status,
319
+ headers: { "Content-Type": "application/json; charset=utf-8", ...cors },
320
+ });
321
+ }
322
+ `;
323
+ }
324
+
325
+ function renderWrangler(ir: IrWorkflowV0): string {
326
+ const safeName = ir.name.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
327
+ return `name = "${safeName}"
328
+ main = "worker.js"
329
+ compatibility_date = "2026-05-01"
330
+ compatibility_flags = ["nodejs_compat"]
331
+
332
+ # ANTHROPIC_API_KEY is set as a Worker Secret (never committed):
333
+ # wrangler secret put ANTHROPIC_API_KEY
334
+ # The studio PWA sets this automatically via the Deploy flow.
335
+
336
+ [observability]
337
+ enabled = true
338
+ `;
339
+ }
340
+
341
+ function renderPackageJson(ir: IrWorkflowV0): string {
342
+ return `{
343
+ "name": "${ir.name}",
344
+ "version": "0.0.0",
345
+ "private": true,
346
+ "type": "module",
347
+ "scripts": {
348
+ "deploy": "wrangler deploy",
349
+ "dev": "wrangler dev --local"
350
+ }
351
+ }
352
+ `;
353
+ }