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
107 changes: 107 additions & 0 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1278,6 +1278,36 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/jobs/{jobId}/invocation-permissions": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* List a source job's manual invocation destinations
* @description Requires the jobs:read scope.
*
* Accepts a scoped bearer token or interactive owner session.
*/
get: operations["get_api_v1_jobs_jobId_invocation_permissions"];
/**
* Replace a source job's manual invocation destinations
* @description Owner session only. Destinations must exist in the same tenant. Lifecycle subscriptions do not create permissions.
*
* Requires the jobs:write scope.
*
* An interactive owner session is required; bearer tokens cannot call this operation.
*/
put: operations["put_api_v1_jobs_jobId_invocation_permissions"];
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/jobs/{jobId}/events": {
parameters: {
query?: never;
Expand Down Expand Up @@ -2030,6 +2060,8 @@ export interface components {
occurrence: {
[key: string]: unknown;
} | null;
source_job_id: string | null;
source_run_id: string | null;
created_at: string;
};
invocation_source: string;
Expand Down Expand Up @@ -5542,6 +5574,81 @@ export interface operations {
503: components["responses"]["Error503"];
};
};
get_api_v1_jobs_jobId_invocation_permissions: {
parameters: {
query?: never;
header?: never;
path: {
jobId: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Configured tenant-local destination jobs */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
/** Format: uuid */
sourceJobId: string;
destinationJobIds: string[];
};
};
};
400: components["responses"]["Error400"];
401: components["responses"]["Error401"];
403: components["responses"]["Error403"];
404: components["responses"]["Error404"];
409: components["responses"]["Error409"];
429: components["responses"]["Error429"];
500: components["responses"]["Error500"];
503: components["responses"]["Error503"];
};
};
put_api_v1_jobs_jobId_invocation_permissions: {
parameters: {
query?: never;
header?: never;
path: {
jobId: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
destinationJobIds: string[];
};
};
};
responses: {
/** @description Saved manual invocation permissions */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
/** Format: uuid */
sourceJobId: string;
destinationJobIds: string[];
};
};
};
400: components["responses"]["Error400"];
401: components["responses"]["Error401"];
403: components["responses"]["Error403"];
404: components["responses"]["Error404"];
409: components["responses"]["Error409"];
415: components["responses"]["Error415"];
429: components["responses"]["Error429"];
500: components["responses"]["Error500"];
503: components["responses"]["Error503"];
};
};
get_api_v1_jobs_jobId_events: {
parameters: {
query?: {
Expand Down
28 changes: 28 additions & 0 deletions packages/api/migrations/0026_manual_invocation_permissions.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
CREATE TABLE app.manual_invocation_permissions (
tenant_id uuid NOT NULL,
source_job_id uuid NOT NULL,
destination_job_id uuid NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, source_job_id, destination_job_id),
FOREIGN KEY (tenant_id, source_job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id, destination_job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE,
CHECK (source_job_id <> destination_job_id)
);
CREATE INDEX manual_invocation_permissions_destination ON app.manual_invocation_permissions(tenant_id,destination_job_id);

CREATE TABLE app.run_credentials (
tenant_id uuid NOT NULL,
run_id uuid NOT NULL,
digest text NOT NULL,
user_id uuid NOT NULL,
session_version integer NOT NULL,
expires_at timestamptz NOT NULL,
PRIMARY KEY (tenant_id,run_id),
FOREIGN KEY (tenant_id,run_id) REFERENCES app.job_runs(tenant_id,id) ON DELETE CASCADE,
FOREIGN KEY (tenant_id,user_id) REFERENCES app.members(tenant_id,user_id) ON DELETE CASCADE
);
CREATE INDEX run_credentials_digest ON app.run_credentials(digest);

ALTER TABLE app.invocations ADD COLUMN source_job_id uuid;
ALTER TABLE app.invocations ADD COLUMN source_run_id uuid;
CREATE INDEX invocations_source_run ON app.invocations(tenant_id,source_run_id) WHERE source_run_id IS NOT NULL;
6 changes: 5 additions & 1 deletion packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import {
manualInvocationSchema,
renameRunSchema,
reportRunErrorSchema,
invocationPermissionsInput,
invocationPermissionsResponse,
reportRunErrorResponse,
jobConditionsTestSchema,
listRunsSchema,
Expand Down Expand Up @@ -712,7 +714,7 @@ export const API_ROUTES: RouteContract[] = [
route(
"POST",
"/api/v1/jobs/{jobId}/invocations",
"runs:write",
"runs:invoke",
{
summary: "Invoke job",
responses: {
Expand Down Expand Up @@ -742,6 +744,8 @@ export const API_ROUTES: RouteContract[] = [
(service, { params, body }) => service.invokeJob(params.jobId, body),
{ body: manualInvocationSchema },
),
route("GET", "/api/v1/jobs/{jobId}/invocation-permissions", "jobs:read", { summary: "List a source job's manual invocation destinations", responses: { "200": { description: "Configured tenant-local destination jobs", content: { "application/json": { schema: jsonSchema(invocationPermissionsResponse, "output") } } } } }, (service, { params }) => service.getInvocationPermissions(params.jobId)),
route("PUT", "/api/v1/jobs/{jobId}/invocation-permissions", "jobs:write", { summary: "Replace a source job's manual invocation destinations", description: "Owner session only. Destinations must exist in the same tenant. Lifecycle subscriptions do not create permissions.", responses: { "200": { description: "Saved manual invocation permissions", content: { "application/json": { schema: jsonSchema(invocationPermissionsResponse, "output") } } } } }, (service, { params, body }) => service.setInvocationPermissions(params.jobId, body.destinationJobIds), { body: invocationPermissionsInput, ownerSession: true }),
route(
"GET",
"/api/v1/jobs/{jobId}/events",
Expand Down
5 changes: 4 additions & 1 deletion packages/api/src/exe-vm-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ export function isOwnedVmName(vm: string): boolean {
}

function harnessCommand(harness: NonNullable<LaunchRequest["harness"]>): string {
const environment = Object.entries(harness.env).map(([name, value]) => `${name}=${shellAtom(value)}`);
const environment = Object.entries(harness.env).map(([name, value]) => {
if (!/^[A-Z_][A-Z0-9_]*$/.test(name)) throw new Error("Invalid harness environment variable name");
return shellAtom(`--setenv=${name}=${value}`);
});
return [...environment, harness.executable, ...harness.args].map((value, index) => index < environment.length ? value : shellAtom(value)).join(" ");
}

Expand Down
2 changes: 2 additions & 0 deletions packages/api/src/flow-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ export const listRunsSchema = z.object({
limit: z.coerce.number().int().min(1).max(100).default(50), cursor: z.string().min(1).optional(),
}).refine(value => !value.direction || value.sort, { message: "direction requires sort" });
export const runIdSchema = z.object({ runId: z.string().min(1) });
export const invocationPermissionsInput = z.object({ destinationJobIds: z.array(z.guid()).max(1000) }).strict();
export const invocationPermissionsResponse = z.object({ sourceJobId: z.guid(), destinationJobIds: z.array(z.guid()) });
export const renameRunSchema = z.object({ name: z.string().trim().min(1).max(120), expectedName: z.string().max(120).optional() }).strict();
export const reportRunErrorSchema = z.object({ reason: z.string().trim().min(1).max(2000) }).strict();
export const reportRunErrorResponse = z.object({ reported: z.literal(true), reason: z.string(), retry: z.boolean() });
Expand Down
40 changes: 36 additions & 4 deletions packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { IntegrationService } from "./postgres/integration-service";
import { OperationsRepository } from "./postgres/operations-repository";
import { installedTriggerAvailability } from "./trigger-availability";
import { evaluateWebhookConditions } from "./webhook-conditions";
import { jobConditionsTestSchema } from "./flow-schemas";
import { jobConditionsTestSchema, invocationPermissionsResponse } from "./flow-schemas";
import { ProviderCatalog } from "./postgres/provider-catalog";
import { ArtifactRepository } from "./postgres/artifact-repository";
import { ACCESS_SCOPES, accessTokenDigest, issueAccessToken, normalizeScopes } from "./access-tokens";
Expand Down Expand Up @@ -187,7 +187,7 @@ export class ApiService {
const run = await repository.get(runId);
if (!run) throw new ServiceError(404, "not_found", "Run not found");
const prompt = await decrypt(run.encrypted_prompt, this.env.CREDENTIAL_ENCRYPTION_KEY);
delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, created_at: run.invocation_created_at };
delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, source_job_id: run.invocation_source_job_id ?? null, source_run_id: run.invocation_source_run_id ?? null, created_at: run.invocation_created_at };
const [activity, projection, cursor, artifacts] = await Promise.all([
repository.activity(runId),
databaseFor(this.env).pool.query("SELECT source_kind,artifact_sha256,parser_version,updated_at FROM app.run_trace_projections WHERE tenant_id=$1 AND run_id=$2", [this.auth.tenantId, runId]),
Expand Down Expand Up @@ -333,13 +333,45 @@ export class ApiService {
}
async setJobEnabled(jobId: string, enabled: boolean) { await this.authorize("jobs:write"); const repository = this.jobs(); if (!await repository.setEnabled(jobId, enabled, new Date().toISOString())) throw new ServiceError(404, "not_found", "Job not found"); await this.wakeScheduler(); return { id: jobId, enabled }; }
async invokeJob(jobId: string, input: ManualInvocationInput) {
await this.authorize("runs:cancel"); const repository = this.jobs(), job = await repository.getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found");
await this.authorize("runs:invoke"); const repository = this.jobs(), job = await repository.getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found");
if (this.auth.authMethod === "run_token") {
if (!this.auth.runId || !this.auth.runJobId) throw new ServiceError(401, "invalid_token", "A verified run identity is required.");
const permission = await databaseFor(this.env).pool.query(`SELECT 1 FROM app.run_credentials c
JOIN app.job_runs r ON r.tenant_id=c.tenant_id AND r.id=c.run_id
JOIN app.manual_invocation_permissions p ON p.tenant_id=c.tenant_id AND p.source_job_id=r.job_id AND p.destination_job_id=$3
WHERE c.tenant_id=$1 AND c.run_id=$2 AND c.digest=$4 AND c.expires_at>now() AND r.state IN ('reserved','starting','running','blocked','stopping')`, [this.auth.tenantId, this.auth.runId, jobId, this.auth.runCredentialDigest]);
if (!permission.rowCount) throw new ServiceError(403, "forbidden", "This run is no longer active or its source job is not authorized to invoke the destination.");
}
const trigger = job.triggers.find(value => value.kind === "manual" && value.enabled); if (!trigger) throw new ServiceError(409, "operation_failed", "The manual trigger is disabled");
const service = new InvocationService(repository, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY));
const result = await service.invoke(jobId, { source: "manual", name: input.name, triggerId: trigger.id, claimKey: input.idempotencyKey ? `manual:${input.idempotencyKey}` : `manual:${crypto.randomUUID()}`, context: { [trigger.slug]: { prompt: input.prompt, data: input.data ?? {} } } });
const claimKey = input.idempotencyKey ? `manual:${this.auth.authMethod === "run_token" ? `run:${this.auth.runId}:` : ""}${input.idempotencyKey}` : `manual:${crypto.randomUUID()}`;
const result = await service.invoke(jobId, { source: "manual", name: input.name, triggerId: trigger.id, claimKey, ...(this.auth.authMethod === "run_token" ? { sourceJobId: this.auth.runJobId, sourceRunId: this.auth.runId } : {}), context: { [trigger.slug]: { prompt: input.prompt, data: input.data ?? {} } } });
if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" });
return { invocationId: result.invocation.id, runId: result.run.id, state: result.run.state, duplicate: result.duplicate };
}
async getInvocationPermissions(sourceJobId: string) {
await this.authorize("jobs:read");
if (!await this.jobs().getJob(sourceJobId)) throw new ServiceError(404, "not_found", "Job not found");
const rows = await databaseFor(this.env).pool.query<{ destination_job_id: string }>("SELECT destination_job_id FROM app.manual_invocation_permissions WHERE tenant_id=$1 AND source_job_id=$2 ORDER BY destination_job_id", [this.auth.tenantId, sourceJobId]);
return publicValue(invocationPermissionsResponse, { sourceJobId, destinationJobIds: rows.rows.map(row => row.destination_job_id) });
}
async setInvocationPermissions(sourceJobId: string, destinationJobIds: string[]) {
await this.authorizeOwnerSession("jobs:write");
const unique = [...new Set(destinationJobIds)];
if (unique.length !== destinationJobIds.length || unique.includes(sourceJobId)) throw new ServiceError(400, "invalid_request", "Destination jobs must be unique and cannot include the source job.");
const db = databaseFor(this.env);
await db.transaction(async client => {
const sources = await client.query("SELECT 1 FROM app.jobs WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.auth.tenantId, sourceJobId]);
if (!sources.rowCount) throw new ServiceError(404, "not_found", "Source job not found");
if (unique.length) {
const found = await client.query("SELECT id FROM app.jobs WHERE tenant_id=$1 AND id=ANY($2::uuid[])", [this.auth.tenantId, unique]);
if (found.rowCount !== unique.length) throw new ServiceError(400, "invalid_request", "Every destination must be an existing job in this tenant.");
}
await client.query("DELETE FROM app.manual_invocation_permissions WHERE tenant_id=$1 AND source_job_id=$2", [this.auth.tenantId, sourceJobId]);
if (unique.length) await client.query("INSERT INTO app.manual_invocation_permissions(tenant_id,source_job_id,destination_job_id) SELECT $1,$2,unnest($3::uuid[])", [this.auth.tenantId, sourceJobId, unique]);
});
return publicValue(invocationPermissionsResponse, { sourceJobId, destinationJobIds: unique });
}
async diagnoseExeIntegration(connectionId: string) { await this.authorize("integrations:write"); const value = await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).diagnoseExe(connectionId); if (!value) throw new ServiceError(404,"not_found","Integration not found"); return value; }
async listJobTriggerAvailability() { await this.authorize("jobs:read"); const [kinds, installations] = await Promise.all([this.connections().kinds(), new GitHubRepository(databaseFor(this.env),this.auth.tenantId).installations()]), states=installations.map((x:any)=>x.state); return installedTriggerAvailability(kinds.includes("linear"),kinds.includes("clickup"),states,kinds.filter(x=>x.startsWith("cloudflare-tail:")).length); }
async previewSchedule(input: unknown) {
Expand Down
6 changes: 5 additions & 1 deletion packages/api/src/job-domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ export interface InvocationRequest {
context: Record<string, unknown>;
/** Stable, source-owned key used to claim this occurrence exactly once. */
claimKey: string;
sourceJobId?: string;
sourceRunId?: string;
occurrence?: { occurredAt?: string; externalId?: string; metadata?: Record<string, unknown> };
}

Expand All @@ -63,6 +65,8 @@ export interface Invocation {
claimKey: string;
triggerId: string;
context: Record<string, unknown>;
sourceJobId?: string;
sourceRunId?: string;
occurrence?: InvocationRequest["occurrence"];
createdAt: string;
}
Expand Down Expand Up @@ -140,7 +144,7 @@ export class InvocationService {

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, triggerId: input.triggerId, context: input.context, ...(input.occurrence ? { occurrence: input.occurrence } : {}), createdAt };
const invocation: Invocation = { id: this.makeId(), jobId, source: input.source, claimKey: input.claimKey, triggerId: input.triggerId, context: input.context, ...(input.sourceJobId ? { sourceJobId: input.sourceJobId } : {}), ...(input.sourceRunId ? { sourceRunId: input.sourceRunId } : {}), ...(input.occurrence ? { occurrence: input.occurrence } : {}), createdAt };
const selectedSkills = (job.selectedSkills ?? []).sort((a, b) => a.position - b.position);
const run: JobRun = { id: this.makeId(), jobId, invocationId: invocation.id, state: "queued", encryptedPrompt: await this.encryptPrompt(renderJobPrompt(job, input.context)), encryptedSkillSnapshot: selectedSkills.length ? await this.encryptSnapshot(JSON.stringify(selectedSkills.map(skill => ({ id: skill.id, key: skill.key, revision: skill.revision, body: skill.body, order: skill.position })))) : undefined, runName: (input.source === "manual" ? input.name?.trim() : undefined) || renderRunName(job.runNameTemplate ?? "", input.context, job.name), createdAt, updatedAt: createdAt };
if (!await this.repository.insertInvocationAndRun(invocation, run)) {
Expand Down
Loading
Loading