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 docs/job-trigger-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ The available value beneath a slug is:

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": "..." }`. `idempotencyKey` is the client-facing value and must not include the reserved internal `manual:` prefix. Reusing the same value returns the original invocation. Run inspection exposes that reusable value as `invocation.idempotency_key`, while `invocation.claim_key` is the internal prefixed claim and must not be passed back to the invocation API. Parameter defaults and invocation, schedule, or webhook parameter overrides are not accepted.
Manual invocation accepts an optional display `name`, `prompt`, JSON object `data`, and `idempotencyKey`. The display name is used as the run name, while prompt and data are exposed beneath the manual trigger slug. `idempotencyKey` is the client-facing value and must not include the reserved internal `manual:` prefix. Reusing the same value returns the original invocation. Run inspection exposes that reusable value as `invocation.idempotency_key`, while `invocation.claim_key` is the internal prefixed claim and must not be passed back to the invocation API. 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.

Expand Down
1 change: 1 addition & 0 deletions packages/app/src/flow-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export const jobIdSchema = z.object({ jobId: z.string().min(1) });
export const manualInvocationSchema = z.object({
prompt: z.string().max(50_000).default(""),
data: z.record(z.string(), z.unknown()).optional(),
name: z.string().trim().min(1).max(120).optional(),
idempotencyKey: z.string().trim().min(1).max(200).refine(key => !key.startsWith("manual:"), {
message: "idempotencyKey must not include the reserved manual: claim-key prefix",
}).optional(),
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 @@ -89,7 +89,7 @@ function createMcpServer(service: ApiService): McpServer {
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", "Invoke a job's manual trigger with a prompt and optional JSON data exposed beneath that trigger's stable slug. Manual invocations are never coalesced. idempotencyKey is a client value and must not include the internal manual: claim-key prefix; reuse invocation.idempotency_key from get_run.", manualInvocationSchema.extend({ jobId: z.string().min(1) }), ({ jobId, ...input }: any) => service.invokeJob(jobId, input));
tool("invoke_job", "Invoke a job's manual trigger with an optional display name, prompt, and JSON data exposed beneath that trigger's stable slug. Manual invocations are never coalesced. idempotencyKey is a client value and must not include the internal manual: claim-key prefix; reuse invocation.idempotency_key from get_run.", 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_webhook_deliveries", "Search tenant-scoped webhook deliveries by provider, delivery ID, event, outcome, job, time range, or safe diagnostic text. Results are newest first and cursor paginated.", z.object({ provider: z.string().optional(), deliveryId: z.string().optional(), event: z.string().optional(), action: z.string().optional(), outcome: z.string().optional(), jobId: z.string().optional(), q: z.string().optional(), from: z.string().optional(), to: z.string().optional(), limit: z.number().int().min(1).max(100).default(50), cursor: z.string().optional() }), (input: any) => service.listWebhookDeliveries(queryOf(input)));
tool("get_webhook_delivery", "Get a webhook delivery and its safe processing timeline. Secrets and payloads are never returned.", z.object({ deliveryId: z.string().min(1) }), ({ deliveryId }: any) => service.getWebhookDelivery(deliveryId));
Expand Down
6 changes: 3 additions & 3 deletions packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -786,13 +786,13 @@ export class TenantV2 extends DurableObject<Env> {
if (!Boolean(job.enabled)) return Response.json({ error: "Job is disabled" }, { status: 409 });
const trigger = this.one("SELECT id,slug FROM triggers WHERE job_id=? AND kind='manual' AND enabled=1 ORDER BY created_at,id LIMIT 1", jobId) as Row | undefined;
if (!trigger) return Response.json({ error: "The manual trigger is disabled" }, { status: 409 });
const result = await this.invokeCanonicalJob(jobId, "manual", String(trigger.id), input.idempotencyKey ? `manual:${input.idempotencyKey}` : `manual:${id()}`, { [String(trigger.slug)]: { prompt: String(input.prompt ?? ""), data: input.data ?? {} } });
const result = await this.invokeCanonicalJob(jobId, "manual", String(trigger.id), input.idempotencyKey ? `manual:${input.idempotencyKey}` : `manual:${id()}`, { [String(trigger.slug)]: { prompt: String(input.prompt ?? ""), data: input.data ?? {} } }, undefined, typeof input.name === "string" ? input.name.trim() : undefined);
if (!result) return Response.json({ error: "Job is disabled" }, { status: 409 });
return json(result);
}

/** Single persistence boundary used by manual and every automatic trigger adapter. */
private async invokeCanonicalJob(jobId: string, source: "manual" | "schedule" | "webhook" | "jobLifecycle", triggerId: string, claimKey: string, context: Record<string, unknown>, occurrence?: Record<string, unknown>): Promise<Record<string, unknown> | null> {
private async invokeCanonicalJob(jobId: string, source: "manual" | "schedule" | "webhook" | "jobLifecycle", triggerId: string, claimKey: string, context: Record<string, unknown>, occurrence?: Record<string, unknown>, explicitRunName?: string): Promise<Record<string, unknown> | null> {
const row = this.one("SELECT * FROM jobs WHERE id = ?", jobId) as Row | undefined;
if (!row || !Boolean(row.enabled)) return null;
const existing = this.one("SELECT i.id AS invocation_id,r.id AS run_id,r.state FROM invocations i JOIN job_runs r ON r.invocation_id=i.id WHERE i.job_id=? AND i.claim_key=?", jobId, claimKey) as Row | undefined;
Expand All @@ -801,7 +801,7 @@ export class TenantV2 extends DurableObject<Env> {
const prompt = renderJobPrompt({ promptTemplate: String(job.promptTemplate) }, context);
const triggerContext = Object.fromEntries(this.triggersFor(jobId).map(trigger => [String(trigger.slug), false]));
Object.assign(triggerContext, context);
const runName = renderRunName(String(job.runNameTemplate ?? ""), triggerContext, `Run ${id().slice(0, 8)}`);
const runName = explicitRunName || renderRunName(String(job.runNameTemplate ?? ""), triggerContext, `Run ${id().slice(0, 8)}`);
const invocationId = id(), runId = id(), timestamp = now();
this.ctx.storage.sql.exec("INSERT OR IGNORE INTO invocations (id,job_id,source,claim_key,trigger_id,context,occurrence,created_at) VALUES (?,?,?,?,?,?,?,?)", invocationId, jobId, source, claimKey, triggerId, JSON.stringify(context), occurrence ? JSON.stringify(occurrence) : null, timestamp);
const winner = this.one("SELECT id FROM invocations WHERE job_id=? AND claim_key=?", jobId, claimKey) as Row;
Expand Down
5 changes: 4 additions & 1 deletion packages/app/src/trigger-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ const commonWebhook: ContextPath[] = [
];

export const triggerContextCatalog: Record<string, ContextPath[]> = {
manual: [{ path: "prompt", type: "string", description: "Prompt supplied by the manual invocation.", example: "Review the failing build" }],
manual: [
{ path: "prompt", type: "string", description: "Prompt supplied by the manual invocation.", example: "Review the failing build" },
{ path: "data", type: "object", description: "JSON data supplied by the manual invocation." },
],
schedule: [
{ path: "scheduled_at", type: "string", description: "Scheduled occurrence as an ISO 8601 timestamp.", example: "2026-09-16T09:00:00.000Z" },
{ path: "cron", type: "string", description: "Configured cron expression.", example: "0 9 * * *" },
Expand Down
3 changes: 2 additions & 1 deletion packages/app/test/flow-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,10 @@ describe("shared API schemas", () => {
expect(() => jobInputSchema.parse({ ...job, apiToken: "secret" })).toThrow();
expect(() => jobInputSchema.parse({ ...job, parameterDefaults: {} })).toThrow();
expect(() => manualInvocationSchema.parse({ parameters: {} })).toThrow();
expect(manualInvocationSchema.parse({ prompt: "ticket", data: { name: "Ticket run", nested: { priority: 1 } } })).toMatchObject({ prompt: "ticket", data: { name: "Ticket run", nested: { priority: 1 } } });
expect(manualInvocationSchema.parse({ name: " Ticket run ", prompt: "ticket", data: { name: "Ticket data", nested: { priority: 1 } } })).toMatchObject({ name: "Ticket run", prompt: "ticket", data: { name: "Ticket data", nested: { priority: 1 } } });
expect(manualInvocationSchema.parse({})).toMatchObject({ prompt: "" });
expect(() => manualInvocationSchema.parse({ data: [] })).toThrow();
expect(() => manualInvocationSchema.parse({ name: " " })).toThrow();
expect(manualInvocationSchema.parse({ idempotencyKey: "dev-dispatch-gen-2032" })).toMatchObject({ idempotencyKey: "dev-dispatch-gen-2032" });
expect(() => manualInvocationSchema.parse({ idempotencyKey: "manual:dev-dispatch-gen-2032" })).toThrow(/reserved manual: claim-key prefix/);
});
Expand Down
2 changes: 1 addition & 1 deletion packages/docs/api/reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,4 @@ All paths are relative to `APP_ORIGIN` and require a bearer token or browser own
| POST | `/api/v1/runs/{runId}/stop` | runs:write | Stop an active run |
| POST | `/api/v1/schedules/preview` | flows:read | `{nextRunAt}` for `{cron,timezone}` |

Job creation requires `name` (1–120), `slug` (lowercase, up to 30), `promptTemplate` (1–50,000), `executionTargetId`, and optional `model`, `effort`, `concurrencyLimit`, and `triggers`. Manual invocation accepts `prompt` (default empty), an optional JSON object `data` (default `{}`), and an optional unique `idempotencyKey` (1–200; never prefix it with reserved `manual:`). Both values are exposed under the manual trigger slug, for example `{{trigger-1.data.name}}`. Run states are `queued`, `starting`, `running`, `recovering`, `done`, `blocked`, `failed`, and `ignored`.
Job creation requires `name` (1–120), `slug` (lowercase, up to 30), `promptTemplate` (1–50,000), `executionTargetId`, and optional `model`, `effort`, `concurrencyLimit`, and `triggers`. Manual invocation accepts an optional display `name` (1–120), `prompt` (default empty), an optional JSON object `data` (default `{}`), and an optional unique `idempotencyKey` (1–200; never prefix it with reserved `manual:`). The display name is used for the run when supplied; prompt and data are exposed under the manual trigger slug, for example `{{trigger-1.data.name}}`. Run states are `queued`, `starting`, `running`, `recovering`, `done`, `blocked`, `failed`, and `ignored`.
2 changes: 1 addition & 1 deletion packages/docs/mcp/tools.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ description: Every tool exposed at /mcp.
| `delete_job` | flows:write | `{jobId}` |
| `enable_job` / `disable_job` | flows:write | `{jobId}` |
| `test_job_webhook_handler` | flows:write | `{handlerCode,payload}` |
| `invoke_job` | runs:write | `{jobId,prompt?,idempotencyKey?}` |
| `invoke_job` | runs:write | `{jobId,name?,prompt?,data?,idempotencyKey?}` |
| `stop_run` | runs:write | `{runId}` |

`list_runs` uses case-insensitive literal substring matching for `contextQuery`; matching rows contain only a bounded excerpt. `get_run` contains the complete context and the reusable `invocation.idempotency_key`, while its internal `claim_key` must not be reused.
1 change: 1 addition & 0 deletions packages/docs/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ components:
type: object
additionalProperties: false
properties:
name: { type: string, minLength: 1, maxLength: 120, description: Display name for the run }
prompt: { type: string, maxLength: 50000, default: '' }
data: { type: object, additionalProperties: true, default: {} }
idempotencyKey: { type: string, minLength: 1, maxLength: 200 }
Expand Down