@crewhaus/target-cf-worker-workflow 0.8.2 → 0.8.3

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 CHANGED
@@ -17,13 +17,21 @@ export type EmitOptions = {
17
17
  * protocol, but instead of a single agent it runs the IR's steps sequentially
18
18
  * server-side, threading each step's terminal assistant text into the next.
19
19
  *
20
- * Loop contract 0.4 (Batch F, G12/G83) — each step now runs the SHARED
20
+ * Loop contract 0.4 (Batch F, G12/G83) — each step runs the SHARED
21
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.
22
+ * {@link WorkerPlatform}. Through the shared runtime the worker carries real
23
+ * edge-safe tools decided by the spec's permission rules, the `limits:` keys
24
+ * the edge enforces, the `CHAT_TOKEN` bearer on `/chat`, and the trace
25
+ * frames. A tool runs only when an `alwaysAllow` rule covers the call, since
26
+ * a worker has nobody to approve one. `limits.deadline_ms` bounds the whole
27
+ * run, as a local workflow's does: the run's start is stamped once, no step
28
+ * starts after the deadline, and each step's loop gets the time that remains.
24
29
  * 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.
30
+ * ends the run with a classified error frame (no compaction on the edge).
31
+ * `/chat` streams the `text`/`done`/`error` SSE vocabulary.
32
+ *
33
+ * A `kind: judge` step is refused with `TargetEmitError`: the worker runs no
34
+ * judge gate. Use the local `@crewhaus/target-workflow` for a gated workflow.
27
35
  */
28
36
  export declare function emitCfWorkerWorkflow(ir: IrWorkflowV0, opts?: EmitOptions): Bundle;
29
37
  export declare class TargetEmitError extends CrewhausError {
package/dist/index.js CHANGED
@@ -12,19 +12,31 @@ const DEFAULT_ALLOWED_ORIGINS = ["https://studio.crewhaus.ai", "http://localhost
12
12
  * protocol, but instead of a single agent it runs the IR's steps sequentially
13
13
  * server-side, threading each step's terminal assistant text into the next.
14
14
  *
15
- * Loop contract 0.4 (Batch F, G12/G83) — each step now runs the SHARED
15
+ * Loop contract 0.4 (Batch F, G12/G83) — each step runs the SHARED
16
16
  * `runWorkerLoop` from `@crewhaus/worker-runtime` over a stateless
17
- * {@link WorkerPlatform}, so a step gains REAL tools (the edge-safe set),
18
- * budget, limits, and the Batch C trace frames THROUGH the shared runtime.
17
+ * {@link WorkerPlatform}. Through the shared runtime the worker carries real
18
+ * edge-safe tools decided by the spec's permission rules, the `limits:` keys
19
+ * the edge enforces, the `CHAT_TOKEN` bearer on `/chat`, and the trace
20
+ * frames. A tool runs only when an `alwaysAllow` rule covers the call, since
21
+ * a worker has nobody to approve one. `limits.deadline_ms` bounds the whole
22
+ * run, as a local workflow's does: the run's start is stamped once, no step
23
+ * starts after the deadline, and each step's loop gets the time that remains.
19
24
  * Host tools are rejected at compile time; a step that overflows its context
20
- * ends the run with a classified error frame (no compaction on the edge). The
21
- * `/chat` `text`/`done`/`error` vocabulary is byte-compatible.
25
+ * ends the run with a classified error frame (no compaction on the edge).
26
+ * `/chat` streams the `text`/`done`/`error` SSE vocabulary.
27
+ *
28
+ * A `kind: judge` step is refused with `TargetEmitError`: the worker runs no
29
+ * judge gate. Use the local `@crewhaus/target-workflow` for a gated workflow.
22
30
  */
23
31
  export function emitCfWorkerWorkflow(ir, opts = {}) {
24
32
  if (ir.target !== "workflow") {
25
33
  throw new TargetEmitError(`emitCfWorkerWorkflow requires target "workflow", got "${ir.target}"`);
26
34
  }
27
35
  for (const step of ir.steps) {
36
+ // A worker runs no judge gate, so a gate step is refused.
37
+ if (step.kind === "judge") {
38
+ throw new TargetEmitError(`cf-worker-workflow does not run judge gates (step "${step.name}" is kind: judge); use the local workflow target for a gated workflow`);
39
+ }
28
40
  // Provider gate — the shared runtime's edge adapter POSTs each step's model
29
41
  // verbatim, so a non-Anthropic model string would 502 at runtime.
30
42
  assertAnthropicModel(step.model, `step "${step.name}"`);
@@ -32,19 +44,20 @@ export function emitCfWorkerWorkflow(ir, opts = {}) {
32
44
  // Loop contract 0.4 (Batch F, G12/G83) — the edge-safety tool gate replaces
33
45
  // the old blanket "does not support tools" rejection, per step.
34
46
  const wiring = resolveWorkflowTools(ir.steps);
47
+ const publicChat = ir.cfWorker?.publicChat === true;
35
48
  const allowedOrigins = opts.allowedOrigins && opts.allowedOrigins.length > 0
36
49
  ? [...opts.allowedOrigins]
37
50
  : DEFAULT_ALLOWED_ORIGINS;
38
51
  const files = [
39
52
  { path: "worker.js", content: renderWorker(ir, wiring, allowedOrigins) },
40
- { path: "wrangler.toml", content: renderWrangler(ir) },
53
+ { path: "wrangler.toml", content: renderWrangler(ir, publicChat) },
41
54
  { path: "package.json", content: renderPackageJson(ir, wiring) },
42
55
  ];
43
56
  if (opts.readme !== false) {
44
57
  files.push({
45
58
  path: "README.md",
46
59
  content: renderBundleReadme(ir, {
47
- ...CF_WORKER_README_OPTS,
60
+ ...cfWorkerReadmeOpts(publicChat, wiring.stepTools.some((tools) => tools !== "[]")),
48
61
  unwiredTools: { names: new Set(wiring.unwired), note: CF_WORKER_UNWIRED_NOTE },
49
62
  toolFacts: readmeToolFacts(ir.steps.map((s) => ({ tools: s.tools, toolConfigs: s.toolConfigs }))),
50
63
  }),
@@ -54,19 +67,72 @@ export function emitCfWorkerWorkflow(ir, opts = {}) {
54
67
  }
55
68
  /** The README note for a tool the worker leaves out. */
56
69
  const CF_WORKER_UNWIRED_NOTE = "left out of this worker — the edge runtime does not run it (see the compile warning)";
57
- const CF_WORKER_README_OPTS = {
58
- usage: {
59
- heading: "Deploy",
60
- body: [
61
- "```sh",
62
- "npm install # resolve the crewhaus runtime + tools",
63
- "wrangler secret put ANTHROPIC_API_KEY # one-time Worker secret",
64
- "wrangler deploy # bundles worker.js + its imports",
65
- "```",
66
- ].join("\n"),
67
- },
68
- includeWorkspaceNote: false,
69
- };
70
+ /**
71
+ * The README's Deploy steps and the sections that say how the worker is
72
+ * called and which tool calls it runs. `publicChat` is the spec's
73
+ * `cf_worker.public_chat`; `hasTools` says some step wires a tool.
74
+ */
75
+ function cfWorkerReadmeOpts(publicChat, hasTools) {
76
+ const deploy = [
77
+ "```sh",
78
+ "npm install # resolve the crewhaus runtime + tools",
79
+ "wrangler secret put ANTHROPIC_API_KEY # one-time Worker secret",
80
+ ...(publicChat
81
+ ? []
82
+ : ["wrangler secret put CHAT_TOKEN # the bearer token POST /chat requires"]),
83
+ "wrangler deploy # bundles worker.js + its imports",
84
+ "```",
85
+ ...(publicChat
86
+ ? []
87
+ : [
88
+ "",
89
+ "Pick a long random `CHAT_TOKEN` (for example `openssl rand -base64 32`) and give it only to the clients that call this worker; for `wrangler dev`, put it in `.dev.vars`.",
90
+ ]),
91
+ ];
92
+ const curl = [
93
+ "```sh",
94
+ "curl -N https://<your-worker>.workers.dev/chat \\",
95
+ ...(publicChat ? [] : [' -H "Authorization: Bearer $CHAT_TOKEN" \\']),
96
+ ' -H "Content-Type: application/json" \\',
97
+ ` -d '{"messages":[{"role":"user","content":"Hello"}]}'`,
98
+ "```",
99
+ ];
100
+ const calling = publicChat
101
+ ? [
102
+ "`POST /chat` answers without a token (`cf_worker.public_chat: true`): anyone with this worker's URL can run it on your `ANTHROPIC_API_KEY` and its tools. Put Cloudflare Access or a rate-limiting rule in front of it.",
103
+ "",
104
+ ...curl,
105
+ "",
106
+ '`GET /health` answers `{"ok":true}`.',
107
+ ]
108
+ : [
109
+ "Send the bearer token with every `POST /chat` request:",
110
+ "",
111
+ ...curl,
112
+ "",
113
+ 'A missing or wrong token is answered with 401, and every `/chat` request is answered with 503 and the code `NO_CHAT_TOKEN` until `CHAT_TOKEN` is set. `GET /health` answers `{"ok":true}` without a token.',
114
+ "",
115
+ "A token written into a web page can be read by everyone who opens it: call the worker from a backend, or put Cloudflare Access in front of it.",
116
+ ];
117
+ return {
118
+ usage: { heading: "Deploy", body: deploy.join("\n") },
119
+ // A deployed Worker has no local `.crewhaus/` workspace.
120
+ includeWorkspaceNote: false,
121
+ extraSections: [
122
+ {
123
+ heading: "Calling the worker",
124
+ body: [
125
+ ...calling,
126
+ "",
127
+ "This worker keeps no spend meter: set a spending limit on the Anthropic account its key belongs to.",
128
+ ].join("\n"),
129
+ },
130
+ ...(hasTools ? [{ heading: "Tools on this worker", body: CF_WORKER_TOOLS_NOTE }] : []),
131
+ ],
132
+ };
133
+ }
134
+ /** The README's word on which tool calls the worker runs. */
135
+ const CF_WORKER_TOOLS_NOTE = "A tool runs on this worker only when an `alwaysAllow` rule in `permissions.rules` covers the call: `WebFetch`, or `WebFetch(https://api.example.com/**)` for one site. A matching `alwaysDeny` or `alwaysAsk` rule wins over any `alwaysAllow`. `mode: auto` reads as `default`, and `mode: plan` runs only read-only tools. Any other call returns an error to the model, because a worker has nobody to approve it.";
70
136
  export class TargetEmitError extends CrewhausError {
71
137
  name = "TargetEmitError";
72
138
  constructor(message, cause) {
@@ -111,8 +177,11 @@ export function resolveWorkflowTools(steps) {
111
177
  unwired: [...resolved.unwired],
112
178
  };
113
179
  }
114
- /** Map the IR's `limits:` block to the runWorkerLoop `limits` subset the edge
115
- * honours (justify escalation degrades to warn). */
180
+ /** The refusal for a `justify` escalation, which needs the intent gate. */
181
+ const JUSTIFY_REFUSAL = "limits.loop_detection.escalation: justify needs the intent gate, which a worker does not run — use warn or abort";
182
+ /** Map the IR's `limits:` block to the runWorkerLoop `limits` the edge
183
+ * enforces. A `justify` escalation needs the intent gate, which a worker does
184
+ * not run, so it is refused with a `TargetEmitError`. */
116
185
  function renderLimits(limits) {
117
186
  if (limits === undefined)
118
187
  return "undefined";
@@ -129,15 +198,25 @@ function renderLimits(limits) {
129
198
  ld["window"] = limits.loopDetection.window;
130
199
  if (limits.loopDetection.threshold !== undefined)
131
200
  ld["threshold"] = limits.loopDetection.threshold;
201
+ if (limits.loopDetection.escalation === "justify")
202
+ throw new TargetEmitError(JUSTIFY_REFUSAL);
132
203
  if (limits.loopDetection.escalation !== undefined) {
133
- ld["escalation"] =
134
- limits.loopDetection.escalation === "justify" ? "warn" : limits.loopDetection.escalation;
204
+ ld["escalation"] = limits.loopDetection.escalation;
135
205
  }
136
206
  if (Object.keys(ld).length > 0)
137
207
  out["loopDetection"] = ld;
138
208
  }
139
209
  return Object.keys(out).length > 0 ? JSON.stringify(out) : "undefined";
140
210
  }
211
+ /** The worker's `permissions`: the spec's mode, only when set, and its rules
212
+ * in declared order. `askMode` is not carried: every ask is refused on a
213
+ * worker, whatever it says. */
214
+ function renderPermissions(permissions) {
215
+ return JSON.stringify({
216
+ ...(permissions.mode !== undefined ? { mode: permissions.mode } : {}),
217
+ rules: permissions.rules.map((rule) => ({ type: rule.type, pattern: rule.pattern })),
218
+ });
219
+ }
141
220
  function edgeToolNote(unwired) {
142
221
  if (unwired.length === 0)
143
222
  return "";
@@ -160,6 +239,29 @@ function renderWorker(ir, wiring, allowedOrigins) {
160
239
  .join(",\n");
161
240
  const allowed = JSON.stringify(allowedOrigins);
162
241
  const limits = renderLimits(ir.limits);
242
+ const permissions = renderPermissions(ir.permissions);
243
+ const publicChat = ir.cfWorker?.publicChat === true;
244
+ // `limits.deadline_ms` bounds the whole run, so only a spec that declares
245
+ // it stamps the run's start and hands each step what remains.
246
+ const deadline = ir.limits?.deadlineMs !== undefined;
247
+ const runStart = deadline
248
+ ? `
249
+ // limits.deadline_ms bounds the whole run, as a local workflow's does:
250
+ // the run's start is stamped once, no step starts once the deadline
251
+ // has passed, and each step's loop gets the time that remains.
252
+ const runStartedAt = platform.now();`
253
+ : "";
254
+ const stepGuard = deadline
255
+ ? `
256
+ const elapsed = platform.now() - runStartedAt;
257
+ if (elapsed >= CONFIG.limits.deadlineMs) {
258
+ emit("error", { message: \`step "\${step.name}": run deadline exceeded: the run exceeded its \${CONFIG.limits.deadlineMs}ms deadline before this step started\` });
259
+ return;
260
+ }`
261
+ : "";
262
+ const stepLimits = deadline
263
+ ? "limits: { ...CONFIG.limits, deadlineMs: Math.max(1, CONFIG.limits.deadlineMs - elapsed) },"
264
+ : "...(CONFIG.limits ? { limits: CONFIG.limits } : {}),";
163
265
  // Loop contract 0.4 (Batch C, item 3). IrWorkflowV0 does not carry an
164
266
  // `observability` field today; the structural read keeps the gate
165
267
  // forward-compatible (defaults to trace-ON, honours an explicit off).
@@ -174,7 +276,7 @@ function renderWorker(ir, wiring, allowedOrigins) {
174
276
  const stepTools = `[${wiring.stepTools.join(", ")}]`;
175
277
  return `// Generated by @crewhaus/target-cf-worker-workflow. Do not edit by hand.
176
278
  // Regenerate via the studio PWA or \`crewhaus compile --target cf-worker-workflow\`.
177
- ${taxonomyWarning}${toolNote}import { runWorkerLoop, createEdgeAnthropicAdapter } from "@crewhaus/worker-runtime";
279
+ ${taxonomyWarning}${toolNote}import { runWorkerLoop, createEdgeAnthropicAdapter, chatAuthRefusal } from "@crewhaus/worker-runtime";
178
280
  ${toolImports}${toolInits}
179
281
  const CONFIG = {
180
282
  name: ${name},
@@ -184,6 +286,8 @@ ${steps}
184
286
  allowedOrigins: ${allowed},
185
287
  trace: ${traceEnabled},
186
288
  limits: ${limits},
289
+ permissions: ${permissions},
290
+ publicChat: ${publicChat},
187
291
  };
188
292
 
189
293
  // One real edge-safe RegisteredTool array per step, in step order.
@@ -197,9 +301,18 @@ export default {
197
301
 
198
302
  const url = new URL(request.url);
199
303
  if (request.method === "GET" && url.pathname === "/health") {
200
- return json({ ok: true, harness: CONFIG.name }, 200, cors);
304
+ return json({ ok: true }, 200, cors);
201
305
  }
202
306
  if (request.method === "POST" && url.pathname === "/chat") {
307
+ // The CHAT_TOKEN bearer is checked first: a request without it is
308
+ // answered before its body is read or the model key is looked up.
309
+ if (!CONFIG.publicChat) {
310
+ const refusal = await chatAuthRefusal(request.headers.get("authorization"), env.CHAT_TOKEN);
311
+ if (refusal) {
312
+ const headers = refusal.status === 401 ? { ...cors, "WWW-Authenticate": "Bearer" } : cors;
313
+ return json({ error: { code: refusal.code, message: refusal.message } }, refusal.status, headers);
314
+ }
315
+ }
203
316
  return handleChat(request, env, cors);
204
317
  }
205
318
  return json({ error: { code: "NOT_FOUND" } }, 404, cors);
@@ -248,11 +361,11 @@ async function handleChat(request, env, cors) {
248
361
  const total = CONFIG.steps.length;
249
362
 
250
363
  try {
251
- let priorOutput = "";
364
+ let priorOutput = "";${runStart}
252
365
  for (let i = 0; i < total; i++) {
253
366
  const step = CONFIG.steps[i];
254
367
  const stepNum = i + 1;
255
- const isLast = i === total - 1;
368
+ const isLast = i === total - 1;${stepGuard}
256
369
  // First step gets the user text; later steps get a synthetic message
257
370
  // embedding the prior step's output.
258
371
  const userContent =
@@ -298,7 +411,8 @@ async function handleChat(request, env, cors) {
298
411
  tools: STEP_TOOLS[i],
299
412
  maxTokens: step.maxTokens,
300
413
  ...(step.thinking ? { thinking: step.thinking } : {}),
301
- ...(CONFIG.limits ? { limits: CONFIG.limits } : {}),
414
+ ${stepLimits}
415
+ permissions: CONFIG.permissions,
302
416
  emitTrace: trace,
303
417
  });
304
418
  if (result.failure) {
@@ -351,7 +465,7 @@ function buildCors(origin) {
351
465
  return {
352
466
  "Access-Control-Allow-Origin": allow,
353
467
  "Access-Control-Allow-Methods": "GET,POST,OPTIONS",
354
- "Access-Control-Allow-Headers": "Content-Type",
468
+ "Access-Control-Allow-Headers": "Content-Type, Authorization",
355
469
  Vary: "Origin",
356
470
  };
357
471
  }
@@ -364,7 +478,7 @@ function json(body, status, cors) {
364
478
  }
365
479
  `;
366
480
  }
367
- function renderWrangler(ir) {
481
+ function renderWrangler(ir, publicChat) {
368
482
  const safeName = ir.name.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
369
483
  return `name = "${safeName}"
370
484
  main = "worker.js"
@@ -372,15 +486,22 @@ compatibility_date = "2026-05-01"
372
486
  compatibility_flags = ["nodejs_compat"]
373
487
 
374
488
  # worker.js imports @crewhaus/worker-runtime and the edge-safe tool packages;
375
- # \`wrangler deploy\` bundles them (run \`npm install\` first). ANTHROPIC_API_KEY
376
- # is a Worker Secret (never committed):
489
+ # \`wrangler deploy\` bundles them (run \`npm install\` first). Its secrets are
490
+ # Worker Secrets (never committed):
377
491
  # wrangler secret put ANTHROPIC_API_KEY
378
- # The studio PWA sets this automatically via the Deploy flow.
492
+ ${chatTokenLine(publicChat)}
493
+ # The studio PWA sets ANTHROPIC_API_KEY through its Deploy flow.
379
494
 
380
495
  [observability]
381
496
  enabled = true
382
497
  `;
383
498
  }
499
+ /** The wrangler.toml line that names the `/chat` bearer, or says there is none. */
500
+ function chatTokenLine(publicChat) {
501
+ return publicChat
502
+ ? "# cf_worker.public_chat: POST /chat answers without a token"
503
+ : "# wrangler secret put CHAT_TOKEN # the bearer every POST /chat must send";
504
+ }
384
505
  /**
385
506
  * The version every @crewhaus package the generated worker imports is pinned
386
507
  * to: this emitter's own. The release train stamps every @crewhaus package with
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewhaus/target-cf-worker-workflow",
3
- "version": "0.8.2",
3
+ "version": "0.8.3",
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",
@@ -16,15 +16,16 @@
16
16
  "test": "bun test src"
17
17
  },
18
18
  "dependencies": {
19
- "@crewhaus/errors": "0.8.2",
20
- "@crewhaus/infra-utils": "0.8.2",
21
- "@crewhaus/ir": "0.8.2",
22
- "@crewhaus/model-router": "0.8.2",
23
- "@crewhaus/tool-categories": "0.8.2",
24
- "@crewhaus/worker-runtime": "0.8.2"
19
+ "@crewhaus/errors": "0.8.3",
20
+ "@crewhaus/infra-utils": "0.8.3",
21
+ "@crewhaus/ir": "0.8.3",
22
+ "@crewhaus/model-router": "0.8.3",
23
+ "@crewhaus/tool-categories": "0.8.3",
24
+ "@crewhaus/worker-runtime": "0.8.3"
25
25
  },
26
26
  "devDependencies": {
27
- "@crewhaus/tool-todo": "workspace:*"
27
+ "@crewhaus/tool-todo": "workspace:*",
28
+ "@crewhaus/tool-web": "workspace:*"
28
29
  },
29
30
  "license": "Apache-2.0",
30
31
  "author": {