Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/job-trigger-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,5 @@ The available value beneath a slug is:
Manual invocation accepts `{ "prompt": "...", "idempotencyKey": "..." }`. Parameter defaults and invocation, schedule, or webhook parameter overrides are not accepted.

Run inspection returns `context` as the complete persisted object and `invocation.trigger_id` as the trigger that fired. Parameter-era stored Jobs are migrated: old context and parameters are retained beneath `legacy_context` and `legacy_parameters` in the corresponding trigger context. They are not used as global template variables.

Every webhook trigger may also define `handlerCode` containing one synchronous `function handler(webhook)` declaration. Factorize runs it only after provider authentication and trigger scoping, inside an isolated Worker with no bindings or outbound network access. Returning `false` rejects the delivery, `true` retains the default value above, and a JSON-compatible object replaces that value beneath the stable trigger slug. Timeouts, exceptions, and invalid return values are recorded in webhook activity and never create a run. REST `POST /api/v1/job-handlers/test` and MCP `test_job_webhook_handler` exercise the same isolation boundary without creating an invocation.
36 changes: 30 additions & 6 deletions packages/app/src/custom-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const CUSTOM_HANDLER_COMPATIBILITY_DATE = "2026-09-10";
export const CUSTOM_HANDLER_DEADLINE_MS = 250;

export type HandlerDecision =
| { ok: true; decision: boolean }
| { ok: true; decision: boolean | Record<string, unknown> }
| { ok: false; category: "handler_error" | "invalid_return" | "timeout" | "platform_error" };

const encoder = new TextEncoder();
Expand All @@ -34,21 +34,44 @@ export function validateCustomHandler(origin: unknown, handlerName: unknown, han
return { origin, handlerName: handlerName.trim(), handlerCode };
}

export function validateHandlerCode(handlerCode: unknown): string {
if (typeof handlerCode !== "string" || encoder.encode(handlerCode).byteLength > CUSTOM_HANDLER_MAX_CODE_BYTES) throw new Error(`Handler code must be at most ${CUSTOM_HANDLER_MAX_CODE_BYTES} bytes.`);
if (!/^\s*function\s+handler\s*\(\s*webhook\s*\)\s*\{[\s\S]*\}\s*;?\s*$/.test(handlerCode)) throw new Error("Provide one complete function handler(webhook) declaration.");
return handlerCode;
}

export function userWorkerModule(handlerCode: string): string {
return `${handlerCode}\n
const jsonCompatible = (value, seen = new Set()) => {
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
if (typeof value === "number") return Number.isFinite(value);
if (typeof value !== "object" || seen.has(value)) return false;
seen.add(value);
const valid = Array.isArray(value)
? value.every(item => jsonCompatible(item, seen))
: (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null) && Object.values(value).every(item => jsonCompatible(item, seen));
seen.delete(value);
return valid;
};
export default { async fetch(request) {
if (request.method !== "POST") return Response.json({ ok: false, category: "handler_error" }, { status: 405 });
try {
const webhook = await request.json();
const result = handler(webhook);
if (result !== null && (typeof result === "object" || typeof result === "function") && typeof result.then === "function") return Response.json({ ok: false, category: "invalid_return" });
if (typeof result !== "boolean") return Response.json({ ok: false, category: "invalid_return" });
return Response.json({ ok: true, decision: result });
if (typeof result === "boolean") return Response.json({ ok: true, decision: result });
if (result === null || typeof result !== "object" || Array.isArray(result) || !jsonCompatible(result)) return Response.json({ ok: false, category: "invalid_return" });
try {
const serialized = JSON.stringify(result);
const decision = JSON.parse(serialized);
if (decision === null || typeof decision !== "object" || Array.isArray(decision)) return Response.json({ ok: false, category: "invalid_return" });
return Response.json({ ok: true, decision });
} catch { return Response.json({ ok: false, category: "invalid_return" }); }
} catch { return Response.json({ ok: false, category: "handler_error" }); }
} };`;
}

export async function invokeCustomHandler(loader: WorkerLoader, source: CustomSource, payload: unknown): Promise<HandlerDecision> {
export async function invokeCustomHandler(loader: WorkerLoader, source: Pick<CustomSource, "handlerCode">, payload: unknown): Promise<HandlerDecision> {
const body = JSON.stringify(payload);
if (encoder.encode(body).byteLength > CUSTOM_HANDLER_MAX_PAYLOAD_BYTES) return { ok: false, category: "platform_error" };
const controller = new AbortController();
Expand All @@ -64,8 +87,9 @@ export async function invokeCustomHandler(loader: WorkerLoader, source: CustomSo
});
const response = await worker.getEntrypoint().fetch("https://handler.internal/", { method: "POST", headers: { "Content-Type": "application/json" }, body, signal: controller.signal });
if (!response.ok) return { ok: false, category: "platform_error" };
const result = await response.json() as HandlerDecision;
return result?.ok === true && typeof result.decision === "boolean" ? result : result?.ok === false && ["handler_error", "invalid_return", "timeout", "platform_error"].includes(result.category) ? result : { ok: false, category: "platform_error" };
const result = await response.json() as any;
const validDecision = typeof result?.decision === "boolean" || (result?.decision !== null && typeof result?.decision === "object" && !Array.isArray(result?.decision));
return result?.ok === true && validDecision ? result : result?.ok === false && ["handler_error", "invalid_return", "timeout", "platform_error"].includes(result.category) ? result : { ok: false, category: "platform_error" };
} catch (error) {
return { ok: false, category: error instanceof DOMException && error.name === "AbortError" ? "timeout" : "platform_error" };
} finally { clearTimeout(deadline); }
Expand Down
5 changes: 4 additions & 1 deletion packages/app/src/flow-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const listEventsSchema = z.object({
flowId: z.string().min(1), limit: z.coerce.number().int().min(1).max(100).default(50), cursor: z.string().min(1).optional(),
});

const webhookCommonSchema = z.object({});
const webhookCommonSchema = z.object({ handlerCode: z.string().max(16_384).optional() });
export const webhookTriggerConfigSchema = z.discriminatedUnion("provider", [
webhookCommonSchema.extend({ provider: z.literal("linear"), projectId: z.string().min(1), matchRules: z.array(matchRuleSchema).min(1) }).strict(),
webhookCommonSchema.extend({ provider: z.literal("github"), installationId: z.number().int().positive(), repositoryId: z.number().int().positive(), event: z.string().min(1).default("pull_request"), action: z.string().min(1).default("dequeued") }).strict(),
Expand Down Expand Up @@ -60,6 +60,9 @@ export const manualInvocationSchema = z.object({
prompt: z.string().max(50_000).default(""),
idempotencyKey: z.string().trim().min(1).max(200).optional(),
}).strict();
export const jobHandlerTestSchema = z.object({
handlerCode: z.string().max(16_384), payload: z.record(z.string(), z.unknown()),
}).strict();

export type FlowInput = z.infer<typeof flowInputSchema>;
export type JobInput = z.infer<typeof jobInputSchema>;
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ export class FlowService {
async listJobs() { return (await this.call("flows:read", "/v1/jobs") as any[]).map(value => this.publicJob(value)); }
async getJob(jobId: string) { return this.publicJob(await this.call("flows:read", `/v1/jobs/${encodeURIComponent(jobId)}`)); }
listJobEvents(jobId: string, limit = 50) { return this.call("runs:read", `/v1/jobs/${encodeURIComponent(jobId)}/events?limit=${limit}`); }
testJobHandler(input: { handlerCode: string; payload: Record<string, unknown> }) { return this.call("flows:write", "/v1/job-handlers/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); }
async createJob(input: JobInput) { return this.publicJob(await this.call("flows:write", "/v1/jobs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) })); }
async updateJob(jobId: string, input: JobInput) { return this.publicJob(await this.call("flows:write", `/v1/jobs/${encodeURIComponent(jobId)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) })); }
deleteJob(jobId: string) { return this.call("flows:write", `/v1/jobs/${encodeURIComponent(jobId)}`, { method: "DELETE" }); }
Expand Down
4 changes: 3 additions & 1 deletion packages/app/src/protected-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { McpServer, WebStandardStreamableHTTPServerTransport } from "@modelconte
import { createMcpHonoApp } from "@modelcontextprotocol/hono";
import { z } from "zod";
import { FlowService, ServiceError } from "./flow-service";
import { flowIdSchema, flowInputSchema, jobIdSchema, jobInputSchema, listEventsSchema, listRunsSchema, manualInvocationSchema, runIdSchema } from "./flow-schemas";
import { flowIdSchema, flowInputSchema, jobHandlerTestSchema, jobIdSchema, jobInputSchema, listEventsSchema, listRunsSchema, manualInvocationSchema, runIdSchema } from "./flow-schemas";
import type { Env, OAuthProps } from "./types";

function errorResponse(error: unknown): Response {
Expand Down Expand Up @@ -51,6 +51,7 @@ export class ProtectedApiHandler extends WorkerEntrypoint<Env, OAuthProps> {
if (request.method === "GET" && path === "/api/v1/execution-targets") return Response.json(await service.listExecutionTargets());
if (request.method === "GET" && path === "/api/v1/jobs") return Response.json(await service.listJobs());
if (request.method === "POST" && path === "/api/v1/jobs") return Response.json(await service.createJob(jobInputSchema.parse(await request.json())), { status: 201 });
if (request.method === "POST" && path === "/api/v1/job-handlers/test") return Response.json(await service.testJobHandler(jobHandlerTestSchema.parse(await request.json())));
const invocationMatch = path.match(/^\/api\/v1\/jobs\/([^/]+)\/invocations$/);
if (invocationMatch && request.method === "POST") return Response.json(await service.invokeJob(decodeURIComponent(invocationMatch[1]), manualInvocationSchema.parse(await request.json())), { status: 202 });
const jobEventsMatch = path.match(/^\/api\/v1\/jobs\/([^/]+)\/events$/);
Expand Down Expand Up @@ -98,6 +99,7 @@ export class ProtectedApiHandler extends WorkerEntrypoint<Env, OAuthProps> {
tool("disable_job", "Disable a job", jobIdSchema, ({ jobId }: any) => service.setJobEnabled(jobId, false));
tool("invoke_job", "Invoke a job's manual trigger with a prompt exposed beneath that trigger's stable slug. Manual invocations are never coalesced.", manualInvocationSchema.extend({ jobId: z.string().min(1) }), ({ jobId, ...input }: any) => service.invokeJob(jobId, input));
tool("list_job_webhook_activity", "List matching, rejected, duplicate, and accepted webhook activity for a job", z.object({ jobId: z.string().min(1), limit: z.number().int().min(1).max(100).default(50) }), ({ jobId, limit }: any) => service.listJobEvents(jobId, limit));
tool("test_job_webhook_handler", "Test an isolated synchronous Job webhook handler without creating a run. Returns the decision and never accepts credentials.", jobHandlerTestSchema, (input: any) => service.testJobHandler(input));
tool("list_execution_targets", "List non-secret execution target metadata and capabilities", z.object({}), () => service.listExecutionTargets());
const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined });
await server.connect(transport);
Expand Down
Loading