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": "..." }`. Parameter defaults and invocation, schedule, or webhook parameter overrides are not accepted.
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.

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
4 changes: 3 additions & 1 deletion packages/app/src/flow-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ export const jobInputSchema = z.object({
export const jobIdSchema = z.object({ jobId: z.string().min(1) });
export const manualInvocationSchema = z.object({
prompt: z.string().max(50_000).default(""),
idempotencyKey: z.string().trim().min(1).max(200).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(),
}).strict();
export const jobHandlerTestSchema = z.object({
handlerCode: z.string().max(16_384), payload: z.record(z.string(), z.unknown()),
Expand Down
4 changes: 2 additions & 2 deletions packages/app/src/protected-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ async function mcp(request: Request, service: ApiService, env: Env, ctx: Executi
});
tool("list_exe_connections", "List safe metadata for saved exe.dev connections. API tokens are never returned.", z.object({}), () => service.listExeConnections());
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("get_run", "Get a run with its full triggered context, invocation metadata, execution metadata, output, and activity. For manual invocations, invocation.idempotency_key is the client-reusable value; invocation.claim_key is internal.", runIdSchema, ({ runId }: any) => service.getRun(runId));
tool("stop_run", "Stop an active run", runIdSchema, ({ runId }: any) => service.stopRun(runId));
tool("list_jobs", "List jobs", z.object({}), () => service.listJobs());
tool("get_job", "Get a job", jobIdSchema, ({ jobId }: any) => service.getJob(jobId));
Expand All @@ -80,7 +80,7 @@ async function mcp(request: Request, service: ApiService, env: Env, ctx: Executi
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 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("invoke_job", "Invoke a job's manual trigger with a prompt 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("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());
Expand Down
8 changes: 7 additions & 1 deletion packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -639,6 +639,9 @@ export class TenantV2 extends DurableObject<Env> {
}

private async invokeJob(jobId: string, input: any): Promise<Response> {
if (typeof input.idempotencyKey === "string" && input.idempotencyKey.trim().startsWith("manual:")) {
return Response.json({ error: "idempotencyKey must not include the reserved manual: claim-key prefix" }, { status: 400 });
}
const job = this.one("SELECT enabled FROM jobs WHERE id=?", jobId) as Row | undefined;
if (!job) return new Response("Not found", { status: 404 });
if (!Boolean(job.enabled)) return Response.json({ error: "Job is disabled" }, { status: 409 });
Expand Down Expand Up @@ -872,7 +875,10 @@ export class TenantV2 extends DurableObject<Env> {
try { context = JSON.parse(String(run.context || "{}")); } catch { context = { legacy: String(run.context ?? "") }; }
try { occurrence = run.invocation_occurrence == null ? null : JSON.parse(String(run.invocation_occurrence)); } catch { /* Persisted invocation remains readable if metadata is malformed. */ }
run.context = context;
run.invocation = { id: run.invocation_id, job_id: run.invocation_job_id, source: run.invocation_source, trigger_id: run.invocation_trigger_id, claim_key: run.invocation_claim_key, context, occurrence, created_at: run.invocation_created_at };
const claimKey = String(run.invocation_claim_key);
const invocation: Record<string, unknown> = { id: run.invocation_id, job_id: run.invocation_job_id, source: run.invocation_source, trigger_id: run.invocation_trigger_id, claim_key: claimKey, context, occurrence, created_at: run.invocation_created_at };
if (run.invocation_source === "manual" && claimKey.startsWith("manual:")) invocation.idempotency_key = claimKey.slice("manual:".length);
run.invocation = invocation;
} else {
run.context = null;
run.invocation = null;
Expand Down
2 changes: 2 additions & 0 deletions packages/app/test/flow-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,7 @@ describe("shared API schemas", () => {
expect(() => jobInputSchema.parse({ ...job, parameterDefaults: {} })).toThrow();
expect(() => manualInvocationSchema.parse({ parameters: {} })).toThrow();
expect(manualInvocationSchema.parse({ prompt: "ticket" })).toMatchObject({ prompt: "ticket" });
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/);
});
});
21 changes: 21 additions & 0 deletions packages/app/test/run-inspection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,25 @@ describe("run invocation inspection", () => {
const legacyBody = await ((legacy as any).getRun("legacy-1") as Promise<Response>).then((response: Response) => response.json()) as any;
expect(legacyBody).toMatchObject({ context: null, invocation: null });
});

it("exposes the reusable idempotency key for manual invocations", async () => {
const tenant = tenantWithRows((query) => query.includes("FROM runs r") ? [{
id: "run-1", job_id: "job-1", state: "queued", backend_kind: "amp", capabilities: "[]", result: null,
context: '{"trigger-1":{"prompt":"go"}}', invocation_id: "inv-1", invocation_job_id: "job-1", invocation_source: "manual", invocation_trigger_id: "manual-1",
invocation_claim_key: "manual:dev-dispatch-gen-2032", invocation_occurrence: null, invocation_created_at: "2026-09-16T12:00:01Z",
}] : []);

const body = await ((tenant as any).getRun("run-1") as Promise<Response>).then((response: Response) => response.json()) as any;
expect(body.invocation).toMatchObject({
claim_key: "manual:dev-dispatch-gen-2032",
idempotency_key: "dev-dispatch-gen-2032",
});
});

it("rejects an internal manual claim key before creating an invocation", async () => {
const tenant = Object.create(TenantV2.prototype) as TenantV2;
const response = await (tenant as any).invokeJob("job-1", { idempotencyKey: "manual:dev-dispatch-gen-2032" }) as Response;
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({ error: "idempotencyKey must not include the reserved manual: claim-key prefix" });
});
});