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: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 full triggered `context` and its invocation metadata (`source`, parameters, schedule occurrence, claim key, and timestamp). Legacy runs return `null` for `context` and `invocation`. Errors consistently use `{ "error": { "code": "...", "message": "..." } }`.
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": "..." } }`.

## MCP clients

Expand Down
12 changes: 6 additions & 6 deletions docs/execution-boundaries.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,16 @@ state and request/response receipt.

## Job invocation boundary

A `Job` owns a Mustache prompt template, string parameter defaults, an execution
A `Job` owns a Mustache prompt template, an execution
target, a positive concurrency limit, enabled state, and a collection of
`Trigger` records. Stored triggers are `schedule`, `webhook`, or `jobLifecycle`;
manual invocation is an operation available to every enabled Job.
`Trigger` records. Stored triggers are `manual`, `schedule`, `webhook`, or
`jobLifecycle`.

Trigger adapters do only source-specific authentication and normalization. They
then call the same `InvocationService.invoke(jobId, request)` operation. Its
canonical request carries the source, optional reserved `context`, string
parameter overrides, a durable claim key, and optional occurrence metadata.
The invocation boundary validates and renders the prompt, applies defaults,
canonical request carries the source, firing trigger ID, structured context, a
durable claim key, and optional occurrence metadata. The invocation boundary
validates and renders the prompt,
encrypts the rendered prompt, and persists the durable occurrence claim. An
automatic signal creates a queued `JobRun` only when the Job has no pending or
active automatic run; otherwise it marks one bounded trailing wake. The
Expand Down
27 changes: 27 additions & 0 deletions docs/job-trigger-context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Job trigger context

Every Job trigger has a server-generated immutable slug (`trigger-1`, `trigger-2`, …). The slug is returned by REST and MCP and is preserved when a Job is edited, reordered, enabled, or disabled. New triggers receive the next unused number. A manual trigger is created for every Job.

Job prompts are Mustache templates rendered only against the firing trigger's structured context. Missing paths render as an empty string. For example:

```mustache
{{trigger-1.prompt}}
{{trigger-2.issue.title}}
{{trigger-3.pull_request.number}}
```

The available value beneath a slug is:

| Trigger | Fields |
| --- | --- |
| Manual | `prompt` |
| Schedule | `scheduled_at`, `cron`, `timezone` |
| 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` |

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.
25 changes: 8 additions & 17 deletions packages/app/src/flow-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,44 +31,35 @@ 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 stringRecordSchema = z.record(z.string(), z.string());
const webhookCommonSchema = z.object({
context: z.string().max(50_000).optional(), parameters: stringRecordSchema.default({}),
});
const webhookCommonSchema = z.object({});
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), 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(), kind: z.literal("schedule"), enabled: z.boolean().default(true), config: z.object({
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(),
z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^trigger-[1-9][0-9]*$/).optional(), kind: z.literal("schedule"), enabled: z.boolean().default(true), config: z.object({
cron: z.string().trim().min(1), timezone: z.string().trim().min(1),
context: z.string().max(50_000).optional(), parameters: stringRecordSchema.default({}),
}).strict() }).strict(),
z.object({ id: z.string().min(1).optional(), kind: z.literal("webhook"), enabled: z.boolean().default(true), config: webhookTriggerConfigSchema }).strict(),
z.object({ id: z.string().min(1).optional(), kind: z.literal("jobLifecycle"), enabled: z.boolean().default(true), config: z.object({
z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^trigger-[1-9][0-9]*$/).optional(), kind: z.literal("webhook"), enabled: z.boolean().default(true), config: webhookTriggerConfigSchema }).strict(),
z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^trigger-[1-9][0-9]*$/).optional(), kind: z.literal("jobLifecycle"), enabled: z.boolean().default(true), config: z.object({
sourceJobIds: z.array(z.string().min(1)).min(1), states: z.array(z.enum(["succeeded", "failed", "stopped"])).min(1),
}).strict() }).strict(),
]);
export const jobInputSchema = z.object({
name: z.string().trim().min(1).max(120),
promptTemplate: z.string().min(1).max(50_000),
parameterDefaults: stringRecordSchema.default({}),
concurrencyLimit: z.number().int().min(1).max(50).default(1),
executionTargetId: z.string().min(1),
triggers: z.array(triggerSchema).max(50).default([]),
}).strict().superRefine((value, ctx) => {
if (Object.prototype.hasOwnProperty.call(value.parameterDefaults, "context")) ctx.addIssue({ code: "custom", path: ["parameterDefaults", "context"], message: "context is reserved" });
});
}).strict();
export const jobIdSchema = z.object({ jobId: z.string().min(1) });
export const manualInvocationSchema = z.object({
context: z.string().max(50_000).optional(),
parameters: stringRecordSchema.default({}),
prompt: z.string().max(50_000).default(""),
idempotencyKey: z.string().trim().min(1).max(200).optional(),
}).strict().superRefine((value, ctx) => {
if (Object.prototype.hasOwnProperty.call(value.parameters, "context")) ctx.addIssue({ code: "custom", path: ["parameters", "context"], message: "context must use the reserved context field" });
});
}).strict();

export type FlowInput = z.infer<typeof flowInputSchema>;
export type JobInput = z.infer<typeof jobInputSchema>;
Expand Down
43 changes: 16 additions & 27 deletions packages/app/src/job-domain.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Mustache from "mustache";

export type TriggerKind = "schedule" | "webhook" | "jobLifecycle";
export type TriggerKind = "manual" | "schedule" | "webhook" | "jobLifecycle";
export type InvocationSource = "manual" | TriggerKind;
export type JobRunState = "queued" | "running" | "succeeded" | "failed" | "stopped";

Expand All @@ -15,6 +15,7 @@ export interface Trigger {
id: string;
jobId: string;
kind: TriggerKind;
slug: string;
enabled: boolean;
config: Record<string, unknown>;
createdAt: string;
Expand All @@ -25,7 +26,6 @@ export interface Job {
id: string;
name: string;
promptTemplate: string;
parameterDefaults: Record<string, string>;
executionTarget: ExecutionTarget;
concurrencyLimit: number;
enabled: boolean;
Expand All @@ -36,8 +36,8 @@ export interface Job {

export interface InvocationRequest {
source: InvocationSource;
context?: string;
parameters?: Record<string, string>;
triggerId: string;
context: Record<string, unknown>;
/** Stable, source-owned key used to claim this occurrence exactly once. */
claimKey: string;
occurrence?: { occurredAt?: string; externalId?: string; metadata?: Record<string, unknown> };
Expand All @@ -48,8 +48,8 @@ export interface Invocation {
jobId: string;
source: InvocationSource;
claimKey: string;
context?: string;
parameters: Record<string, string>;
triggerId: string;
context: Record<string, unknown>;
occurrence?: InvocationRequest["occurrence"];
createdAt: string;
}
Expand Down Expand Up @@ -80,22 +80,10 @@ export class InvocationError extends Error {
constructor(public code: "job_not_found" | "job_disabled" | "invalid_invocation" | "invalid_template", message: string) { super(message); }
}

const recordOfStrings = (value: unknown, name: string): Record<string, string> => {
if (value === undefined) return {};
if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some(item => typeof item !== "string")) {
throw new InvocationError("invalid_invocation", `${name} must contain only string values.`);
}
return value as Record<string, string>;
};

export function renderJobPrompt(job: Pick<Job, "promptTemplate" | "parameterDefaults">, request: Pick<InvocationRequest, "context" | "parameters">): string {
const defaults = recordOfStrings(job.parameterDefaults, "Job parameter defaults");
if (Object.prototype.hasOwnProperty.call(defaults, "context")) throw new InvocationError("invalid_template", "context is reserved and cannot be a job parameter.");
const overrides = recordOfStrings(request.parameters, "Invocation parameters");
if (Object.prototype.hasOwnProperty.call(overrides, "context")) throw new InvocationError("invalid_invocation", "context is reserved and must be supplied through the context field.");
export function renderJobPrompt(job: Pick<Job, "promptTemplate">, context: Record<string, unknown>): string {
try {
Mustache.parse(job.promptTemplate);
return Mustache.render(job.promptTemplate, { ...defaults, ...overrides, context: request.context ?? "" });
return Mustache.render(job.promptTemplate, context);
} catch (error) {
if (error instanceof InvocationError) throw error;
throw new InvocationError("invalid_template", "The job prompt is not valid Mustache.");
Expand All @@ -121,10 +109,10 @@ export class InvocationService {
const existing = await this.repository.findInvocation(jobId, input.claimKey);
if (existing) return { ...existing, duplicate: true };

const parameters = recordOfStrings(input.parameters, "Invocation parameters");
if (!input.triggerId || !input.context || typeof input.context !== "object" || Array.isArray(input.context)) throw new InvocationError("invalid_invocation", "A trigger and structured context are required.");
const createdAt = this.clock();
const invocation: Invocation = { id: this.makeId(), jobId, source: input.source, claimKey: input.claimKey, ...(input.context === undefined ? {} : { context: input.context }), parameters, ...(input.occurrence ? { occurrence: input.occurrence } : {}), createdAt };
const run: JobRun = { id: this.makeId(), jobId, invocationId: invocation.id, state: "queued", encryptedPrompt: await this.encryptPrompt(renderJobPrompt(job, input)), createdAt, updatedAt: createdAt };
const invocation: Invocation = { id: this.makeId(), jobId, source: input.source, claimKey: input.claimKey, triggerId: input.triggerId, context: input.context, ...(input.occurrence ? { occurrence: input.occurrence } : {}), createdAt };
const run: JobRun = { id: this.makeId(), jobId, invocationId: invocation.id, state: "queued", encryptedPrompt: await this.encryptPrompt(renderJobPrompt(job, input.context)), createdAt, updatedAt: createdAt };
if (!await this.repository.insertInvocationAndRun(invocation, run)) {
const winner = await this.repository.findInvocation(jobId, input.claimKey);
if (!winner) throw new Error("Invocation claim was lost without a persisted winner.");
Expand All @@ -145,19 +133,20 @@ export class InvocationService {
export const JOB_SCHEMA = `
CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY, name TEXT NOT NULL, encrypted_prompt_template TEXT NOT NULL,
parameter_defaults TEXT NOT NULL, execution_target TEXT NOT NULL,
execution_target TEXT NOT NULL,
concurrency_limit INTEGER NOT NULL CHECK (concurrency_limit >= 1), enabled INTEGER NOT NULL,
created_at TEXT NOT NULL, updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS triggers (
id TEXT PRIMARY KEY, job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
kind TEXT NOT NULL CHECK (kind IN ('schedule','webhook','jobLifecycle')), enabled INTEGER NOT NULL DEFAULT 1, config TEXT NOT NULL,
created_at TEXT NOT NULL, updated_at TEXT NOT NULL
kind TEXT NOT NULL CHECK (kind IN ('manual','schedule','webhook','jobLifecycle')), slug TEXT NOT NULL, enabled INTEGER NOT NULL DEFAULT 1, config TEXT NOT NULL,
created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
UNIQUE(job_id, slug)
);
CREATE TABLE IF NOT EXISTS invocations (
id TEXT PRIMARY KEY, job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
source TEXT NOT NULL CHECK (source IN ('manual','schedule','webhook','jobLifecycle')), claim_key TEXT NOT NULL,
context TEXT, parameters TEXT NOT NULL, occurrence TEXT, created_at TEXT NOT NULL,
trigger_id TEXT NOT NULL, context TEXT NOT NULL, occurrence TEXT, created_at TEXT NOT NULL,
UNIQUE(job_id, claim_key)
);
CREATE TABLE IF NOT EXISTS job_runs (
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/protected-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export class ProtectedApiHandler extends WorkerEntrypoint<Env, OAuthProps> {
tool("delete_job", "Delete a job and its queued invocation history", jobIdSchema, ({ jobId }: any) => service.deleteJob(jobId));
tool("enable_job", "Enable a job", jobIdSchema, ({ jobId }: any) => service.setJobEnabled(jobId, true));
tool("disable_job", "Disable a job", jobIdSchema, ({ jobId }: any) => service.setJobEnabled(jobId, false));
tool("invoke_job", "Explicitly invoke any enabled job, overriding string parameters and optional reserved context. Manual invocations are never coalesced with automatic wakes.", manualInvocationSchema.extend({ jobId: z.string().min(1) }), ({ jobId, ...input }: any) => service.invokeJob(jobId, input));
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("list_execution_targets", "List non-secret execution target metadata and capabilities", z.object({}), () => service.listExecutionTargets());
const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined });
Expand Down
2 changes: 0 additions & 2 deletions packages/app/src/schedule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import { CronExpressionParser } from "cron-parser";
export interface ScheduleConfig {
cron: string;
timezone: string;
context?: string;
parameters?: Record<string, string>;
}

export function validateScheduleConfig(value: unknown): ScheduleConfig {
Expand Down
Loading