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
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,15 @@ Use authorization-code OAuth and enable **Webhooks** on the OAuth application. C

After changing the webhook settings, re-authorize existing workspaces so Linear creates a fresh workspace subscription.

## Create a flow
## Create a Job

1. Sign in with Linear.
2. Connect your exe.dev VM using its restricted HTTPS API token. Use the same user-qualified SSH destination you use interactively so Factorize and your terminal join the same Herdr session.
3. Create a flow, select a Linear project, and add matching rules. Every rule must match.
3. Create a Job, choose its execution target, and add authenticated provider triggers. Every Linear matching rule must match.

Matching issue updates queue work up to the flow’s configured concurrency. When a run finishes, Factorize fills its slot from the queue and posts a link to the Herdr session in Linear.
Matching provider events queue work up to the Job’s configured concurrency. When a run finishes, Factorize fills its slot from the queue and posts a link to the Herdr session in Linear.

Cloudflare Worker failures can also start flows through the separately deployable Tail relay. See [Cloudflare Tail flow source](docs/cloudflare-tail.md).
Cloudflare Worker failures can also start Jobs through the separately deployable Tail relay. See [Cloudflare Tail job trigger](docs/cloudflare-tail.md).

## Configuration reference

Expand Down Expand Up @@ -138,7 +138,7 @@ The versioned API is rooted at `/api/v1`:

```bash
curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \
https://app.factorize.sh/api/v1/flows
https://app.factorize.sh/api/v1/jobs

curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \
'https://app.factorize.sh/api/v1/runs?jobId=JOB_ID&state=running&contextQuery=customer%20impact&limit=25'
Expand All @@ -150,7 +150,7 @@ curl -X POST -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \
https://app.factorize.sh/api/v1/runs/RUN_ID/stop
```

Flow CRUD is available at `/flows` and `/flows/:id`; supporting collections are `/projects`, `/flow-options`, `/runs`, and `/flow-events`. Run and event collections return `{ "items": [...], "nextCursor": "..." }`; pass `nextCursor` back as the `cursor` query parameter. Runs can be filtered by `jobId`, `state`, and `contextQuery`; context queries use case-insensitive literal substring matching and matching items contain a bounded `context_excerpt`, never the full context. `GET /runs/:runId` returns the complete structured trigger `context` and invocation metadata, including the firing `trigger_id`. Legacy runs return `null` for `context` and `invocation`. The canonical Job prompt contract is documented in [docs/job-trigger-context.md](docs/job-trigger-context.md). Errors consistently use `{ "error": { "code": "...", "message": "..." } }`.
Job CRUD is available at `/jobs` and `/jobs/:id`. Run collections return `{ "items": [...], "nextCursor": "..." }`; pass `nextCursor` back as the `cursor` query parameter. Runs can be filtered by `jobId`, `state`, and `contextQuery`; context queries use case-insensitive literal substring matching and matching items contain a bounded `context_excerpt`, never the full context. `GET /runs/:runId` returns the complete structured trigger `context` and invocation metadata, including the firing `trigger_id`. The canonical Job prompt contract is documented in [docs/job-trigger-context.md](docs/job-trigger-context.md). Errors consistently use `{ "error": { "code": "...", "message": "..." } }`.

## MCP clients

Expand All @@ -160,7 +160,7 @@ Configure a compatible remote MCP client with this single URL:
https://app.factorize.sh/mcp
```

The client discovers OAuth automatically, opens Factorize in a browser, completes Linear sign-in if necessary, requests consent, and returns to the client after PKCE authorization. No Linear or exe.dev credential is copied into the MCP client. The server is stateless Streamable HTTP and exposes flow CRUD, projects/options, run inspection/filtering, webhook activity, and active-run stopping tools.
The client discovers OAuth automatically, opens Factorize in a browser, completes Linear sign-in if necessary, requests consent, and returns to the client after PKCE authorization. No Linear or exe.dev credential is copied into the MCP client. The server is stateless Streamable HTTP and exposes Job CRUD, run inspection/filtering, provider webhook activity, and active-run stopping tools.

Factorize also supports the OAuth 2.0 Device Authorization Grant (RFC 8628) for headless clients. Discovery advertises `device_authorization_endpoint`; clients obtain a code from `POST /oauth/device_authorization`, direct the user to `/device`, and poll `/oauth/token` with grant type `urn:ietf:params:oauth:grant-type:device_code`. Device codes expire after ten minutes, polling is rate-limited, and approved grants use the same scoped access and refresh tokens, tenant checks, and revocation behavior as browser PKCE authorization.

Expand Down
14 changes: 7 additions & 7 deletions docs/cloudflare-tail.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# Cloudflare Tail flow source
# Cloudflare Tail job trigger

Cloudflare Tail is a Factorize flow source for native uncaught Worker exceptions and structured `console.error` failures. Tail Workers require a Workers Paid or Enterprise plan. The relay is a separate Cloudflare Worker and must be deployed in the same Cloudflare account as the producer Workers; the Factorize app Worker may be in any account.
Cloudflare Tail is an authenticated Factorize Job trigger for native uncaught Worker exceptions and structured `console.error` failures. Tail Workers require a Workers Paid or Enterprise plan. The relay is a separate Cloudflare Worker and must be deployed in the same Cloudflare account as the producer Workers; the Factorize app Worker may be in any account.

## Configure the flow and relay
## Configure the job and relay

1. Create a flow, choose **Cloudflare Tail**, and save it. On the edit page, copy the relay destination and signing secret. You can show, copy, edit, or generate a replacement secret there; replacements remain local until **Save Changes** succeeds.
1. Create a Job, add a **Cloudflare Tail** trigger, and save it. Copy its relay destination and signing secret.
2. From the repository root, run `npm ci` and set `FACTORIZE_TAIL_DESTINATION` as a Wrangler variable in `packages/tail-relay/wrangler.jsonc`.
3. Authenticate Wrangler to the producer Workers' Cloudflare account, then run `npm exec --workspace=factorize-tail-relay -- wrangler secret put FACTORIZE_TAIL_SECRET` and `npm run deploy:tail-relay`. Keep the relay name `factorize-tail-relay`; Factorize excludes its own relay traces to prevent loops.
4. Add the relay to every producer Worker. One relay can consume multiple producers and forwards each event with its `scriptName`:
Expand All @@ -15,9 +15,9 @@ Cloudflare Tail is a Factorize flow source for native uncaught Worker exceptions
}
```

Deploy each producer after changing `tail_consumers`. In the flow activity page, use the owner-only **Test Cloudflare Tail delivery** action before enabling concurrency/automation. The synthetic exception traverses the same isolated handler and normal queue path.
Deploy each producer after changing `tail_consumers`.

MCP clients should call `list_exe_connections`, select a `connectionId`, then call `create_flow` with `source: { "kind": "cloudflareTail" }`. The response contains the relay destination but never the signing secret. Omit `handlerCode` for the default exception/`console.error` filter. Protected REST and MCP cannot read or replace the secret; authenticated owners rotate it on the edit page and must then update `FACTORIZE_TAIL_SECRET` in Wrangler and redeploy the relay.
MCP clients create or update a Job with a `cloudflareTail` webhook trigger and an execution target returned by `list_execution_targets`. Protected REST and MCP never return the signing secret. After rotating it, update `FACTORIZE_TAIL_SECRET` in Wrangler and redeploy the relay.

The relay redacts sensitive key names (authorization, cookies, tokens, secrets, credentials, prompts, and bodies), truncates oversized structures, signs the exact body with HMAC-SHA256, and aborts delivery after three seconds. Factorize sanitizes again before activity or agent context, rejects deliveries older than 60 seconds, deduplicates delivery IDs, and rate-limits repeated event fingerprints.

Expand All @@ -27,4 +27,4 @@ For caught internal failures, log a structured event:
console.error(JSON.stringify({ event: "factorize_unexpected_failure", component: "billing", message: error.message }));
```

Do not include request bodies, headers, credentials, or prompts in the structured log. Expected 4xx/domain failures remain ordinary Tail events unless the flow handler explicitly accepts them.
Do not include request bodies, headers, credentials, or prompts in the structured log. Expected 4xx/domain failures remain ordinary Tail events unless the Job handler explicitly accepts them.
9 changes: 0 additions & 9 deletions docs/custom-sources-rollout.md

This file was deleted.

3 changes: 1 addition & 2 deletions docs/job-trigger-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,9 @@ The available value beneath a slug is:
| Linear webhook | Complete Linear delivery, plus `provider`, `event`, `delivery_id` |
| GitHub webhook | Complete GitHub delivery, plus `provider`, `event`, `delivery_id` |
| Cloudflare Tail | Complete sanitized Tail delivery, plus `provider`, `event`, `delivery_id` |
| Custom webhook | Complete submitted JSON delivery, plus `provider`, `event`, `delivery_id` |
| Job lifecycle | `source_job_id`, `source_run_id`, `final_state`, `transitioned_at`, `observation_destination` |

Every trigger returned by `GET /api/v1/jobs` and `GET /api/v1/jobs/:id` (and the corresponding MCP `list_jobs` and `get_job` tools) includes a `reflection` object. It contains the stable `slug`, trigger kind/provider, whether the result is dynamic, and a flat `paths` list with nested path, basic value type, description, and occasional example. The Job editor consumes this same canonical contract for Mustache autocomplete. A custom webhook, or any webhook with a replacing handler, reports `dynamic: true` and an explicit `*`/`unknown` fallback because arbitrary handler output cannot be inferred safely.
Every trigger returned by `GET /api/v1/jobs` and `GET /api/v1/jobs/:id` (and the corresponding MCP `list_jobs` and `get_job` tools) includes a `reflection` object. It contains the stable `slug`, trigger kind/provider, whether the result is dynamic, and a flat `paths` list with nested path, basic value type, description, and occasional example. The Job editor consumes this same canonical contract for Mustache autocomplete. A webhook with a replacing handler reports `dynamic: true` and an explicit `*`/`unknown` fallback because arbitrary handler output cannot be inferred safely.

Manual invocation accepts `{ "prompt": "...", "idempotencyKey": "..." }`. Parameter defaults and invocation, schedule, or webhook parameter overrides are not accepted.

Expand Down
7 changes: 7 additions & 0 deletions docs/legacy-removal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Legacy removal rollout

Generic custom webhooks and the legacy Flow product are no longer accepted or exposed. Only Jobs and authenticated Linear, GitHub, and signed Cloudflare Tail triggers are supported.

Deploy the application before removing stored legacy data so old endpoints fail closed with `404` and no unsupported record can launch work. Existing `pipes`, Flow event, custom-source, and legacy delivery rows are inert after deployment and may be deleted during a maintenance window. Preserve `jobs`, `triggers`, `invocations`, `job_runs`, and execution/run records associated with a Job ID.

Before deletion, export any audit data that must be retained. There is intentionally no automatic bridge from a Flow or generic custom webhook to a Job because trigger provenance and authentication cannot be inferred safely. Recreate wanted automation as a Job with an authenticated provider trigger.
2 changes: 1 addition & 1 deletion packages/app/public/styles.css

Large diffs are not rendered by default.

35 changes: 1 addition & 34 deletions packages/app/src/custom-handler.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
import type { CustomOrigin, CustomSource } from "./types";

export const CUSTOM_HANDLER_SCAFFOLD = `function handler(webhook) {
return true;
}`;
export const CUSTOM_HANDLER_MAX_CODE_BYTES = 16_384;
export const CUSTOM_HANDLER_MAX_PAYLOAD_BYTES = 262_144;
export const CUSTOM_HANDLER_COMPATIBILITY_DATE = "2026-09-10";
Expand All @@ -13,27 +8,6 @@ export type HandlerDecision =
| { ok: false; category: "handler_error" | "invalid_return" | "timeout" | "platform_error" };

const encoder = new TextEncoder();
const hex = (bytes: ArrayBuffer) => [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");

export async function sha256(value: string): Promise<string> {
return hex(await crypto.subtle.digest("SHA-256", encoder.encode(value)));
}

export async function customScriptName(tenantId: string, flowId: string): Promise<string> {
return `fh-${(await sha256(`${tenantId}\0${flowId}`)).slice(0, 40)}`;
}

export function validateCustomHandler(origin: unknown, handlerName: unknown, handlerCode: unknown): { origin: CustomOrigin; handlerName: string; handlerCode: string } {
if (origin !== "linear" && origin !== "github" && origin !== "cloudflare") throw new Error("Custom handler origin must be Linear, GitHub, or Cloudflare.");
if (typeof handlerName !== "string" || !handlerName.trim() || handlerName.trim().length > 80) throw new Error("Handler name must be between 1 and 80 characters.");
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.`);
// This is input validation, not the isolation boundary. Requiring exactly one
// complete declaration prevents ambiguous adapters and accidental snippets.
const declaration = /^\s*function\s+handler\s*\(\s*webhook\s*\)\s*\{[\s\S]*\}\s*;?\s*$/;
if (!declaration.test(handlerCode)) throw new Error("Provide one complete function handler(webhook) declaration.");
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.");
Expand Down Expand Up @@ -71,7 +45,7 @@ export default { async fetch(request) {
} };`;
}

export async function invokeCustomHandler(loader: WorkerLoader, source: Pick<CustomSource, "handlerCode">, payload: unknown): Promise<HandlerDecision> {
export async function invokeCustomHandler(loader: WorkerLoader, source: { handlerCode: string }, 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 @@ -94,10 +68,3 @@ export async function invokeCustomHandler(loader: WorkerLoader, source: Pick<Cus
return { ok: false, category: error instanceof DOMException && error.name === "AbortError" ? "timeout" : "platform_error" };
} finally { clearTimeout(deadline); }
}

export async function prepareCustomHandler(tenantId: string, flowId: string, source: Omit<CustomSource, "handlerDeployment">, previous?: CustomSource): Promise<CustomSource> {
const scriptName = await customScriptName(tenantId, flowId);
const codeDigest = await sha256(source.handlerCode);
if (previous?.handlerDeployment.state === "ready" && previous.handlerDeployment.codeDigest === codeDigest) return { ...source, tail: source.tail ?? previous.tail, handlerDeployment: previous.handlerDeployment };
return { ...source, handlerDeployment: { scriptName, codeDigest, state: "ready" } };
}
20 changes: 0 additions & 20 deletions packages/app/src/flow-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,37 +6,18 @@ export const matchRuleSchema = z.object({
type: z.enum(["owner", "creator", "status", "label", "assignee"]),
targetId: z.string().min(1),
});
export const publicSourceSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("linear"), projectId: z.string().min(1), matchRules: z.array(matchRuleSchema).min(1) }).strict(),
z.object({ kind: z.literal("cloudflareTail"), handlerCode: z.string().max(16_384).optional() }).strict(),
]);
export const flowInputSchema = z.object({
name: z.string().trim().min(1).max(120),
flowId: z.string().trim().regex(/^[a-z0-9][a-z0-9-]*$/).optional(),
source: publicSourceSchema,
maxConcurrency: z.number().int().min(0).max(50).default(3),
workspaceName: z.string().max(120).optional(),
contextTemplate: z.string().max(50_000).optional(),
cwd: z.string().max(1_000).optional(),
exeConnectionId: z.string().min(1),
}).strict();
export const flowIdSchema = z.object({ flowId: z.string().min(1) });
export const listRunsSchema = z.object({
jobId: z.string().min(1).optional(), state: runStateSchema.optional(),
contextQuery: z.string().min(1).max(50_000).optional(),
limit: z.coerce.number().int().min(1).max(100).default(50), cursor: z.string().min(1).optional(),
});
export const runIdSchema = z.object({ runId: z.string().min(1) });
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({ 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(),
webhookCommonSchema.extend({ provider: z.literal("cloudflareTail"), signingSecret: z.string().min(16).optional(), handlerCode: z.string().max(16_384).optional() }).strict(),
webhookCommonSchema.extend({ provider: z.literal("custom"), secret: z.string().min(16).optional() }).strict(),
]);
export const triggerSchema = z.discriminatedUnion("kind", [
z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^trigger-[1-9][0-9]*$/).optional(), kind: z.literal("manual"), enabled: z.boolean().default(true), config: z.object({}).strict().default({}) }).strict(),
Expand Down Expand Up @@ -64,6 +45,5 @@ 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>;
export type ManualInvocationInput = z.infer<typeof manualInvocationSchema>;
Loading