@crewhaus/target-cf-worker-workflow 0.1.3 → 0.1.5

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.
@@ -0,0 +1,38 @@
1
+ import { CrewhausError } from "@crewhaus/errors";
2
+ import type { Bundle, IrWorkflowV0 } from "@crewhaus/ir";
3
+ export type EmitOptions = {
4
+ /**
5
+ * Origins the generated Worker should accept on `/chat`. Defaults to the
6
+ * production studio + local dev. Threading this through compile-time
7
+ * lets the studio PWA bake its own origin in so users can host the PWA
8
+ * anywhere (pages.dev, ngrok, LAN IP) without editing the emitter.
9
+ */
10
+ readonly allowedOrigins?: readonly string[];
11
+ };
12
+ /**
13
+ * Emit a Cloudflare Worker bundle for a WORKFLOW-target IR. Workflow sibling
14
+ * of `@crewhaus/target-cf-worker-cli`'s `emitCfWorkerCli`: same self-contained
15
+ * Worker shape and `/chat` SSE protocol, but instead of a single agent it runs
16
+ * the IR's steps sequentially server-side. Each step is one single-turn LLM
17
+ * call; the prior step's terminal assistant text is threaded into the next
18
+ * step's user message (mirrors `@crewhaus/target-workflow`'s local runtime).
19
+ *
20
+ * Like the cli emitter, the worker is fully self-contained — it inlines a
21
+ * minimal Anthropic streaming-SSE client so the studio PWA can upload the
22
+ * bundle directly via the Cloudflare API without a build step on the user's
23
+ * device.
24
+ *
25
+ * Bundle contents:
26
+ * - `worker.js` — entrypoint, runs as an ES module Worker
27
+ * - `wrangler.toml` — deploy descriptor for users who do prefer CLI
28
+ * - `package.json` — declares the runtime version stamp
29
+ *
30
+ * M2 emits a tools-free Worker (the cli sibling does the same). Tools,
31
+ * sub-agents, MCP, hooks, and the security fabric port over when we point the
32
+ * emitter at a shared worker runtime instead of inlining the client.
33
+ */
34
+ export declare function emitCfWorkerWorkflow(ir: IrWorkflowV0, opts?: EmitOptions): Bundle;
35
+ export declare class TargetEmitError extends CrewhausError {
36
+ readonly name = "TargetEmitError";
37
+ constructor(message: string, cause?: unknown);
38
+ }
@@ -1,20 +1,7 @@
1
1
  import { CrewhausError } from "@crewhaus/errors";
2
2
  import { escapeJsonString } from "@crewhaus/infra-utils";
3
- import type { Bundle, IrWorkflowV0 } from "@crewhaus/ir";
4
3
  import { parseModelString } from "@crewhaus/model-router";
5
-
6
- export type EmitOptions = {
7
- /**
8
- * Origins the generated Worker should accept on `/chat`. Defaults to the
9
- * production studio + local dev. Threading this through compile-time
10
- * lets the studio PWA bake its own origin in so users can host the PWA
11
- * anywhere (pages.dev, ngrok, LAN IP) without editing the emitter.
12
- */
13
- readonly allowedOrigins?: readonly string[];
14
- };
15
-
16
4
  const DEFAULT_ALLOWED_ORIGINS = ["https://studio.crewhaus.ai", "http://localhost:4322"];
17
-
18
5
  /**
19
6
  * Emit a Cloudflare Worker bundle for a WORKFLOW-target IR. Workflow sibling
20
7
  * of `@crewhaus/target-cf-worker-cli`'s `emitCfWorkerCli`: same self-contained
@@ -37,83 +24,73 @@ const DEFAULT_ALLOWED_ORIGINS = ["https://studio.crewhaus.ai", "http://localhost
37
24
  * sub-agents, MCP, hooks, and the security fabric port over when we point the
38
25
  * emitter at a shared worker runtime instead of inlining the client.
39
26
  */
40
- export function emitCfWorkerWorkflow(ir: IrWorkflowV0, opts: EmitOptions = {}): Bundle {
41
- if (ir.target !== "workflow") {
42
- throw new TargetEmitError(
43
- `emitCfWorkerWorkflow requires target "workflow", got "${ir.target}"`,
44
- );
45
- }
46
- for (const step of ir.steps) {
47
- // Provider gate — the emitted worker inlines an api.anthropic.com client
48
- // and POSTs each step's model verbatim, so a non-Anthropic model string
49
- // would compile cleanly and 502 at runtime. Fail at compile time instead.
50
- assertAnthropicModel(step.model, `step "${step.name}"`);
51
- if (step.tools.length > 0) {
52
- throw new TargetEmitError(
53
- `cf-worker-workflow does not yet support tools (step "${step.name}"); use the local workflow target`,
54
- );
27
+ export function emitCfWorkerWorkflow(ir, opts = {}) {
28
+ if (ir.target !== "workflow") {
29
+ throw new TargetEmitError(`emitCfWorkerWorkflow requires target "workflow", got "${ir.target}"`);
55
30
  }
56
- }
57
- const allowedOrigins =
58
- opts.allowedOrigins && opts.allowedOrigins.length > 0
59
- ? [...opts.allowedOrigins]
60
- : DEFAULT_ALLOWED_ORIGINS;
61
- return {
62
- files: [
63
- { path: "worker.js", content: renderWorker(ir, allowedOrigins) },
64
- { path: "wrangler.toml", content: renderWrangler(ir) },
65
- { path: "package.json", content: renderPackageJson(ir) },
66
- ],
67
- };
31
+ for (const step of ir.steps) {
32
+ // Provider gate — the emitted worker inlines an api.anthropic.com client
33
+ // and POSTs each step's model verbatim, so a non-Anthropic model string
34
+ // would compile cleanly and 502 at runtime. Fail at compile time instead.
35
+ assertAnthropicModel(step.model, `step "${step.name}"`);
36
+ if (step.tools.length > 0) {
37
+ throw new TargetEmitError(`cf-worker-workflow does not yet support tools (step "${step.name}"); use the local workflow target`);
38
+ }
39
+ }
40
+ const allowedOrigins = opts.allowedOrigins && opts.allowedOrigins.length > 0
41
+ ? [...opts.allowedOrigins]
42
+ : DEFAULT_ALLOWED_ORIGINS;
43
+ return {
44
+ files: [
45
+ { path: "worker.js", content: renderWorker(ir, allowedOrigins) },
46
+ { path: "wrangler.toml", content: renderWrangler(ir) },
47
+ { path: "package.json", content: renderPackageJson(ir) },
48
+ ],
49
+ };
68
50
  }
69
-
70
51
  export class TargetEmitError extends CrewhausError {
71
- override readonly name = "TargetEmitError";
72
- constructor(message: string, cause?: unknown) {
73
- super("compiler", message, cause);
74
- }
52
+ name = "TargetEmitError";
53
+ constructor(message, cause) {
54
+ super("compiler", message, cause);
55
+ }
75
56
  }
76
-
77
57
  /**
78
58
  * Reject any model string the router would dispatch to a non-Anthropic
79
59
  * provider (openai/, gemini/, bedrock/, local/…) — the inlined worker
80
60
  * client only speaks the Anthropic Messages API.
81
61
  */
82
- function assertAnthropicModel(model: string, where: string): void {
83
- let providerId: string;
84
- try {
85
- providerId = parseModelString(model).providerId;
86
- } catch (err) {
87
- throw new TargetEmitError(`${where} model "${model}": ${(err as Error).message}`, err);
88
- }
89
- if (providerId !== "anthropic") {
90
- throw new TargetEmitError(
91
- `${where} model "${model}" routes to provider "${providerId}" — cf-worker targets currently support claude-* models only — use the cli target for other providers`,
92
- );
93
- }
62
+ function assertAnthropicModel(model, where) {
63
+ let providerId;
64
+ try {
65
+ providerId = parseModelString(model).providerId;
66
+ }
67
+ catch (err) {
68
+ throw new TargetEmitError(`${where} model "${model}": ${err.message}`, err);
69
+ }
70
+ if (providerId !== "anthropic") {
71
+ 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`);
72
+ }
94
73
  }
95
-
96
- function renderWorker(ir: IrWorkflowV0, allowedOrigins: readonly string[]): string {
97
- // escapeJsonString === JSON.stringify: each of these is a COMPLETE,
98
- // quoted JS/JSON string literal already. Do NOT wrap them in extra quotes
99
- // in the template below, or the output becomes `name: ""my-workflow""` — a
100
- // syntax error Cloudflare rejects at upload time.
101
- const name = escapeJsonString(ir.name);
102
- // Build the steps array literal by hand so each field is escaped exactly
103
- // once. Same fixed-bug discipline as the cli emitter: escapeJsonString
104
- // already returns a quoted literal, so the surrounding object literal just
105
- // interpolates it directly.
106
- const steps = ir.steps
107
- .map((step) => {
108
- const stepName = escapeJsonString(step.name);
109
- const stepModel = escapeJsonString(step.model);
110
- const stepInstructions = escapeJsonString(step.instructions);
111
- return ` { name: ${stepName}, model: ${stepModel}, instructions: ${stepInstructions} }`;
74
+ function renderWorker(ir, allowedOrigins) {
75
+ // escapeJsonString === JSON.stringify: each of these is a COMPLETE,
76
+ // quoted JS/JSON string literal already. Do NOT wrap them in extra quotes
77
+ // in the template below, or the output becomes `name: ""my-workflow""` — a
78
+ // syntax error Cloudflare rejects at upload time.
79
+ const name = escapeJsonString(ir.name);
80
+ // Build the steps array literal by hand so each field is escaped exactly
81
+ // once. Same fixed-bug discipline as the cli emitter: escapeJsonString
82
+ // already returns a quoted literal, so the surrounding object literal just
83
+ // interpolates it directly.
84
+ const steps = ir.steps
85
+ .map((step) => {
86
+ const stepName = escapeJsonString(step.name);
87
+ const stepModel = escapeJsonString(step.model);
88
+ const stepInstructions = escapeJsonString(step.instructions);
89
+ return ` { name: ${stepName}, model: ${stepModel}, instructions: ${stepInstructions} }`;
112
90
  })
113
- .join(",\n");
114
- const allowed = JSON.stringify(allowedOrigins);
115
-
116
- return `// Generated by @crewhaus/target-cf-worker-workflow. Do not edit by hand.
91
+ .join(",\n");
92
+ const allowed = JSON.stringify(allowedOrigins);
93
+ return `// Generated by @crewhaus/target-cf-worker-workflow. Do not edit by hand.
117
94
  // Regenerate via the studio PWA or \`crewhaus compile --target cf-worker-workflow\`.
118
95
 
119
96
  const CONFIG = {
@@ -345,10 +322,9 @@ function json(body, status, cors) {
345
322
  }
346
323
  `;
347
324
  }
348
-
349
- function renderWrangler(ir: IrWorkflowV0): string {
350
- const safeName = ir.name.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
351
- return `name = "${safeName}"
325
+ function renderWrangler(ir) {
326
+ const safeName = ir.name.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
327
+ return `name = "${safeName}"
352
328
  main = "worker.js"
353
329
  compatibility_date = "2026-05-01"
354
330
  compatibility_flags = ["nodejs_compat"]
@@ -361,13 +337,12 @@ compatibility_flags = ["nodejs_compat"]
361
337
  enabled = true
362
338
  `;
363
339
  }
364
-
365
- function renderPackageJson(ir: IrWorkflowV0): string {
366
- // Sanitize like the wrangler name. A raw ir.name breaks out of the JSON
367
- // string (this manifest is reachable from the hosted compiler-worker HTTP
368
- // endpoint), allowing dependency/script injection into package.json (#148).
369
- const safeName = ir.name.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
370
- return `{
340
+ function renderPackageJson(ir) {
341
+ // Sanitize like the wrangler name. A raw ir.name breaks out of the JSON
342
+ // string (this manifest is reachable from the hosted compiler-worker HTTP
343
+ // endpoint), allowing dependency/script injection into package.json (#148).
344
+ const safeName = ir.name.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
345
+ return `{
371
346
  "name": "${safeName}",
372
347
  "version": "0.0.0",
373
348
  "private": true,
package/package.json CHANGED
@@ -1,21 +1,24 @@
1
1
  {
2
2
  "name": "@crewhaus/target-cf-worker-workflow",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
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
- "main": "src/index.ts",
7
- "types": "src/index.ts",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
8
  "exports": {
9
- ".": "./src/index.ts"
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
10
13
  },
11
14
  "scripts": {
12
15
  "test": "bun test src"
13
16
  },
14
17
  "dependencies": {
15
- "@crewhaus/errors": "0.1.3",
16
- "@crewhaus/infra-utils": "0.1.3",
17
- "@crewhaus/ir": "0.1.3",
18
- "@crewhaus/model-router": "0.1.3"
18
+ "@crewhaus/errors": "0.1.5",
19
+ "@crewhaus/infra-utils": "0.1.5",
20
+ "@crewhaus/ir": "0.1.5",
21
+ "@crewhaus/model-router": "0.1.5"
19
22
  },
20
23
  "license": "Apache-2.0",
21
24
  "author": {
@@ -35,5 +38,5 @@
35
38
  "publishConfig": {
36
39
  "access": "public"
37
40
  },
38
- "files": ["src", "README.md", "LICENSE", "NOTICE"]
41
+ "files": ["dist", "README.md", "LICENSE", "NOTICE"]
39
42
  }
package/src/index.test.ts DELETED
@@ -1,165 +0,0 @@
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
- });
120
-
121
- describe("emitCfWorkerWorkflow — package.json name injection (#148)", () => {
122
- test("package.json sanitizes the spec name and resists JSON injection", () => {
123
- const ir: IrWorkflowV0 = {
124
- ...baseIr,
125
- name: '", "dependencies": { "evil-typosquat": "1.0.0" }, "x": "',
126
- };
127
- const pkg = emitCfWorkerWorkflow(ir).files.find((f) => f.path === "package.json");
128
- expect(pkg).toBeDefined();
129
- const parsed = JSON.parse(pkg?.content ?? "") as {
130
- name: string;
131
- dependencies?: Record<string, string>;
132
- };
133
- expect(parsed.name).not.toContain('"'); // sanitized to [a-z0-9-]
134
- expect(parsed.dependencies).toBeUndefined(); // injection did not break out
135
- });
136
- });
137
-
138
- describe("emitCfWorkerWorkflow — provider gate", () => {
139
- test("a workflow with one openai/ step fails at compile time, naming the step", () => {
140
- const ir: IrWorkflowV0 = {
141
- ...baseIr,
142
- steps: [step({ name: "research" }), step({ name: "draft", model: "openai/gpt-4o-mini" })],
143
- };
144
- expect(() => emitCfWorkerWorkflow(ir)).toThrow(TargetEmitError);
145
- expect(() => emitCfWorkerWorkflow(ir)).toThrow(
146
- /cf-worker targets currently support claude-\* models only — use the cli target for other providers/,
147
- );
148
- expect(() => emitCfWorkerWorkflow(ir)).toThrow(/step "draft"/);
149
- });
150
-
151
- test("gemini/, bedrock/, and local/ step models are all rejected", () => {
152
- for (const model of [
153
- "gemini/gemini-2.5-flash",
154
- "bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0",
155
- "local/llama3.2@http://localhost:11434/v1",
156
- ]) {
157
- const ir: IrWorkflowV0 = { ...baseIr, steps: [step({ model })] };
158
- expect(() => emitCfWorkerWorkflow(ir)).toThrow(TargetEmitError);
159
- }
160
- });
161
-
162
- test("all-claude steps still emit cleanly", () => {
163
- expect(emitCfWorkerWorkflow(baseIr).files.length).toBe(3);
164
- });
165
- });