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
12 changes: 8 additions & 4 deletions docs/execution-boundaries.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,20 @@ state and request/response receipt.
## Job invocation boundary

A `Job` owns a Mustache prompt template, string parameter defaults, an execution
target, a positive concurrency limit, enabled state, and exactly one `Trigger`.
Triggers have one of three domain kinds: `manual`, `schedule`, or `webhook`.
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 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,
encrypts the rendered prompt, and atomically persists an `Invocation` plus its
queued `JobRun`. The `(job_id, claim_key)` constraint makes retries idempotent.
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
`(job_id, claim_key)` constraint keeps every source retry idempotent and
lifecycle delivery also claims `(trigger_id, source_run_id, terminal_state)`.

Queue consumers call `startIfCapacity`; concurrency is counted by job, never by
trigger source. Provider adapters must not render prompts, insert runs, claim
Expand Down
10 changes: 6 additions & 4 deletions packages/app/src/flow-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,22 @@ export const webhookTriggerConfigSchema = z.discriminatedUnion("provider", [
webhookCommonSchema.extend({ provider: z.literal("custom"), secret: z.string().min(16).optional() }).strict(),
]);
export const triggerSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("manual"), config: z.object({}).strict().default({}) }).strict(),
z.object({ kind: z.literal("schedule"), config: z.object({
z.object({ id: z.string().min(1).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({ kind: z.literal("webhook"), config: webhookTriggerConfigSchema }).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({
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),
trigger: triggerSchema,
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" });
});
Expand Down
8 changes: 5 additions & 3 deletions packages/app/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,11 @@ export class FlowService {
}

private publicJob(value: any) {
const provider = value?.trigger?.kind === "webhook" ? value.trigger.config?.provider : undefined;
if (provider === "cloudflareTail") value.trigger.config.destination = `${this.env.APP_ORIGIN}/webhooks/cloudflare/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(value.id)}`;
if (provider === "custom") value.trigger.config.destination = `${this.env.APP_ORIGIN}/webhooks/custom/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(value.id)}`;
for (const trigger of value?.triggers ?? []) {
const provider = trigger.kind === "webhook" ? trigger.config?.provider : undefined;
if (provider === "cloudflareTail") trigger.config.destination = `${this.env.APP_ORIGIN}/webhooks/cloudflare/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(value.id)}`;
if (provider === "custom") trigger.config.destination = `${this.env.APP_ORIGIN}/webhooks/custom/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(value.id)}`;
}
return value;
}

Expand Down
30 changes: 20 additions & 10 deletions packages/app/src/job-domain.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import Mustache from "mustache";

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

export interface ExecutionTarget {
connectionId: string;
Expand All @@ -15,6 +15,7 @@ export interface Trigger {
id: string;
jobId: string;
kind: TriggerKind;
enabled: boolean;
config: Record<string, unknown>;
createdAt: string;
updatedAt: string;
Expand All @@ -28,7 +29,7 @@ export interface Job {
executionTarget: ExecutionTarget;
concurrencyLimit: number;
enabled: boolean;
trigger: Trigger;
triggers: Trigger[];
createdAt: string;
updatedAt: string;
}
Expand Down Expand Up @@ -112,7 +113,7 @@ export class InvocationService {

async invoke(jobId: string, input: InvocationRequest): Promise<InvocationResult> {
if (!input.claimKey?.trim()) throw new InvocationError("invalid_invocation", "An invocation claim key is required.");
if (!(["manual", "schedule", "webhook"] as const).includes(input.source)) throw new InvocationError("invalid_invocation", "Invocation source is invalid.");
if (!(["manual", "schedule", "webhook", "jobLifecycle"] as const).includes(input.source)) throw new InvocationError("invalid_invocation", "Invocation source is invalid.");
const job = await this.repository.getJob(jobId);
if (!job) throw new InvocationError("job_not_found", "Job not found.");
if (!job.enabled) throw new InvocationError("job_disabled", "Job is disabled.");
Expand Down Expand Up @@ -149,20 +150,20 @@ export const JOB_SCHEMA = `
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 UNIQUE REFERENCES jobs(id) ON DELETE CASCADE,
kind TEXT NOT NULL CHECK (kind IN ('manual','schedule','webhook')), config TEXT NOT NULL,
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
);
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')), claim_key TEXT NOT NULL,
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,
UNIQUE(job_id, claim_key)
);
CREATE TABLE IF NOT EXISTS job_runs (
id TEXT PRIMARY KEY, job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
invocation_id TEXT NOT NULL UNIQUE REFERENCES invocations(id) ON DELETE CASCADE,
state TEXT NOT NULL CHECK (state IN ('queued','running','succeeded','failed','cancelled')),
state TEXT NOT NULL CHECK (state IN ('queued','running','succeeded','failed','stopped')),
encrypted_prompt TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, started_at TEXT
);
CREATE INDEX IF NOT EXISTS job_runs_queue ON job_runs(state, created_at);
Expand All @@ -175,8 +176,17 @@ export const JOB_SCHEMA = `
CREATE INDEX IF NOT EXISTS job_events_by_job ON job_events(job_id, received_at DESC);
CREATE TABLE IF NOT EXISTS schedule_state (
trigger_id TEXT PRIMARY KEY REFERENCES triggers(id) ON DELETE CASCADE,
job_id TEXT NOT NULL UNIQUE REFERENCES jobs(id) ON DELETE CASCADE,
job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
next_run_at INTEGER, last_triggered_at TEXT
);
CREATE INDEX IF NOT EXISTS schedules_due ON schedule_state(next_run_at);
CREATE TABLE IF NOT EXISTS automatic_wakes (
job_id TEXT PRIMARY KEY REFERENCES jobs(id) ON DELETE CASCADE,
trailing INTEGER NOT NULL DEFAULT 0, summary TEXT NOT NULL DEFAULT '{}', updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS lifecycle_deliveries (
trigger_id TEXT NOT NULL REFERENCES triggers(id) ON DELETE CASCADE,
source_run_id TEXT NOT NULL, terminal_state TEXT NOT NULL, created_at TEXT NOT NULL,
PRIMARY KEY(trigger_id,source_run_id,terminal_state)
);
`;
4 changes: 2 additions & 2 deletions packages/app/src/protected-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export class ProtectedApiHandler extends WorkerEntrypoint<Env, OAuthProps> {
tool("list_projects", "List Linear projects", z.object({}), () => service.listProjects());
tool("list_flow_options", "List match-rule options", z.object({}), () => service.listFlowOptions());
tool("list_exe_connections", "List safe metadata for saved exe.dev connections. Select a connectionId before creating or updating a flow; API tokens are never returned.", z.object({}), () => service.listExeConnections());
tool("list_runs", "List and filter job runs by job ID, state, and an optional case-insensitive literal substring of the exact triggered context. Context matches include only a bounded excerpt.", listRunsSchema, (input: any) => service.listRuns(queryOf(input)));
tool("list_runs", "List authoritative job runs by job ID, state, and an optional case-insensitive literal substring of triggered context. Automatic webhook, schedule, and lifecycle signals coalesce, so query runs and the provider API for authoritative work. Context matches include only a bounded excerpt.", listRunsSchema, (input: any) => service.listRuns(queryOf(input)));
tool("get_run", "Get a run with its full triggered context, invocation metadata, execution metadata, output, and activity", runIdSchema, ({ runId }: any) => service.getRun(runId));
tool("list_flow_events", "List webhook activity for a flow", listEventsSchema, (input: any) => service.listFlowEvents(queryOf(input)));
tool("stop_run", "Stop an active run", runIdSchema, ({ runId }: any) => service.stopRun(runId));
Expand All @@ -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", "Manually invoke any enabled job, overriding string parameters and optional reserved context", manualInvocationSchema.extend({ jobId: z.string().min(1) }), ({ jobId, ...input }: any) => service.invokeJob(jobId, input));
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("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
Loading