diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 1ed8b48d..3225f4cf 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1030,6 +1030,112 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/skills": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Search global skills + * @description Requires the skills:read scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + get: operations["get_api_v1_skills"]; + put?: never; + /** + * Create a global skill + * @description Requires the skills:write scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + post: operations["post_api_v1_skills"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/skills/preview": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Preview a composed job prompt + * @description Requires the skills:read scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + post: operations["post_api_v1_skills_preview"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/skills/{skillId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Get a global skill + * @description Requires the skills:read scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + get: operations["get_api_v1_skills_skillId"]; + /** + * Update a global skill + * @description Requires the skills:write scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + put: operations["put_api_v1_skills_skillId"]; + post?: never; + /** + * Delete an unused global skill + * @description Requires the skills:write scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + delete: operations["delete_api_v1_skills_skillId"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/skills/{skillId}/jobs": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List jobs using a skill + * @description Requires the skills:read scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + get: operations["get_api_v1_skills_skillId_jobs"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/jobs/{jobId}/project": { parameters: { query?: never; @@ -1888,6 +1994,7 @@ export interface components { states: ("succeeded" | "failed" | "stopped" | "edited")[]; }; })[]; + skillIds?: string[]; }; ManualInvocation: { /** @default */ @@ -3471,7 +3578,7 @@ export interface operations { content: { "application/json": { name: string; - scopes: (("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "integrations:read" | "integrations:write") | ("flows:read" | "flows:write" | "runs:write"))[]; + scopes: (("projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write") | ("flows:read" | "flows:write" | "runs:write"))[]; expiryDays: 7 | 30 | 90; }; }; @@ -4172,6 +4279,294 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_skills: { + parameters: { + query?: { + q?: string; + limit?: number; + cursor?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Skills */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + items: { + /** Format: uuid */ + id: string; + key: string; + revision: number; + usageCount: number; + createdAt: string; + updatedAt: string; + }[]; + nextCursor: string | null; + }; + }; + }; + 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"]; + }; + }; + post_api_v1_skills: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + key: string; + body: string; + }; + }; + }; + responses: { + /** @description Created */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + key: string; + revision: number; + body: string; + usageCount: number; + createdAt: string; + updatedAt: 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"]; + }; + }; + post_api_v1_skills_preview: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + skillIds: string[]; + jobContext: string; + sampleTriggerData?: { + [key: string]: unknown; + }; + }; + }; + }; + responses: { + /** @description Prompt preview */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": Record; + }; + }; + 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_skills_skillId: { + parameters: { + query?: never; + header?: never; + path: { + skillId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Skill */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + key: string; + revision: number; + body: string; + usageCount: number; + createdAt: string; + updatedAt: 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_skills_skillId: { + parameters: { + query?: never; + header?: never; + path: { + skillId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + key?: string; + body?: string; + expectedRevision: number; + }; + }; + }; + responses: { + /** @description Updated */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + key: string; + revision: number; + body: string; + usageCount: number; + createdAt: string; + updatedAt: 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"]; + }; + }; + delete_api_v1_skills_skillId: { + parameters: { + query: { + expectedRevision: number; + }; + header?: never; + path: { + skillId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Deleted */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": Record; + }; + }; + 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"]; + }; + }; + get_api_v1_skills_skillId_jobs: { + parameters: { + query?: never; + header?: never; + path: { + skillId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Jobs */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + skillId: string; + jobs: { + /** Format: uuid */ + id: string; + name: string; + slug: string; + enabled: boolean; + /** Format: uuid */ + projectId: 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"]; + }; + }; post_api_v1_jobs_jobId_project: { parameters: { query?: never; @@ -4335,6 +4730,13 @@ export interface operations { createdAt: string; updatedAt: string; })[]; + skills?: { + /** Format: uuid */ + id: string; + key: string; + revision: number; + position: number; + }[]; createdAt: string; updatedAt: string; }; @@ -4503,6 +4905,13 @@ export interface operations { createdAt: string; updatedAt: string; })[]; + skills?: { + /** Format: uuid */ + id: string; + key: string; + revision: number; + position: number; + }[]; createdAt: string; updatedAt: string; }[]; @@ -4674,6 +5083,13 @@ export interface operations { createdAt: string; updatedAt: string; })[]; + skills?: { + /** Format: uuid */ + id: string; + key: string; + revision: number; + position: number; + }[]; createdAt: string; updatedAt: string; }; @@ -5017,6 +5433,13 @@ export interface operations { createdAt: string; updatedAt: string; })[]; + skills?: { + /** Format: uuid */ + id: string; + key: string; + revision: number; + position: number; + }[]; createdAt: string; updatedAt: string; }; @@ -5143,6 +5566,7 @@ export interface operations { states: ("succeeded" | "failed" | "stopped" | "edited")[]; }; })[]; + skillIds?: string[]; /** Format: date-time */ expectedUpdatedAt?: string; }; @@ -5292,6 +5716,13 @@ export interface operations { createdAt: string; updatedAt: string; })[]; + skills?: { + /** Format: uuid */ + id: string; + key: string; + revision: number; + position: number; + }[]; createdAt: string; updatedAt: string; }; diff --git a/packages/api/migrations/0022_global_skills.sql b/packages/api/migrations/0022_global_skills.sql new file mode 100644 index 00000000..623e3ed1 --- /dev/null +++ b/packages/api/migrations/0022_global_skills.sql @@ -0,0 +1,4 @@ +CREATE TABLE app.skills (tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, id uuid NOT NULL, key text NOT NULL, encrypted_body text NOT NULL, revision integer NOT NULL DEFAULT 1, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,key), CHECK (revision > 0)); +CREATE TABLE app.job_skills (tenant_id uuid NOT NULL, job_id uuid NOT NULL, skill_id uuid NOT NULL, position integer NOT NULL, PRIMARY KEY (tenant_id,job_id,skill_id), UNIQUE (tenant_id,job_id,position), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE, FOREIGN KEY (tenant_id,skill_id) REFERENCES app.skills(tenant_id,id) ON DELETE RESTRICT); +CREATE INDEX job_skills_skill_usage ON app.job_skills(tenant_id,skill_id); +ALTER TABLE app.job_runs ADD COLUMN IF NOT EXISTS encrypted_skill_snapshot text; diff --git a/packages/api/src/access-tokens.ts b/packages/api/src/access-tokens.ts index f9c04afa..2e5db7a1 100644 --- a/packages/api/src/access-tokens.ts +++ b/packages/api/src/access-tokens.ts @@ -2,7 +2,7 @@ import type { Env, OAuthProps } from "./types"; import { databaseFor } from "./postgres/database"; import { AccessTokenRepository } from "./postgres/access-token-repository"; -export const ACCESS_SCOPES = ["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write"] as const; +export const ACCESS_SCOPES = ["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write", "skills:read", "skills:write"] as const; export type AccessScope = typeof ACCESS_SCOPES[number]; export type LegacyScope = "flows:read" | "flows:write" | "runs:write"; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 36aebab3..1a80561a 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -18,6 +18,7 @@ import { import { traceReplaySchema } from "./trace-replay-schemas"; import document from "./api-document.json"; import { authInputs, authSuccess, continuationSuccess, connectionStartInput, connectionStartSuccess, connectionResumeInput, loginSuccess, sessionResponse, type AuthAction } from "./auth-api"; +import { skillInput, skillUpdateInput, skillPage, skillResponse, skillJobsResponse, previewSkillInput } from "./skills"; type JsonSchema = Record; export interface RouteContract { @@ -93,6 +94,7 @@ const traceQuery = z.object({ limit: z.coerce.number().int().min(1).max(200).default(100), }); const searchQuery = z.object({ q: z.string().default("") }); +const skillQuery = z.object({ q: z.string().default(""), limit: z.coerce.number().int().min(1).max(100).default(30), cursor: z.guid().optional() }); const clickUpQuery = z.object({ listId: z.string().default("") }); const scheduleBody = z .object({ @@ -651,6 +653,13 @@ export const API_ROUTES: RouteContract[] = [ route("GET", "/api/v1/projects/{projectId}", "flows:read", { summary: "Get project", responses: { "200": { description: "Project", content: { "application/json": { schema: jsonSchema(projectResponse, "output") } } } } }, (service, { params }) => service.getProject(params.projectId)), route("PUT", "/api/v1/projects/{projectId}", "flows:write", { summary: "Update project", responses: { "200": { description: "Updated", content: { "application/json": { schema: jsonSchema(projectResponse, "output") } } } } }, (service, { params, body }) => service.updateProject(params.projectId, body), { body: projectInput }), route("DELETE", "/api/v1/projects/{projectId}", "flows:write", { summary: "Delete empty project", responses: { "200": { description: "Deleted" } } }, (service, { params }) => service.deleteProject(params.projectId)), + route("GET", "/api/v1/skills", "skills:read", { summary: "Search global skills", responses: { "200": { description: "Skills", content: { "application/json": { schema: jsonSchema(skillPage, "output") } } } } }, (service, { query }) => service.listSkills(query), { query: skillQuery }), + route("POST", "/api/v1/skills", "skills:write", { summary: "Create a global skill", responses: { "201": { description: "Created", content: { "application/json": { schema: jsonSchema(skillResponse, "output") } } } } }, (service, { body }) => service.createSkill(body), { body: skillInput }), + route("POST", "/api/v1/skills/preview", "skills:read", { summary: "Preview a composed job prompt", responses: { "200": { description: "Prompt preview" } } }, (service, { body }) => service.previewJobPrompt(body), { body: previewSkillInput }), + route("GET", "/api/v1/skills/{skillId}", "skills:read", { summary: "Get a global skill", responses: { "200": { description: "Skill", content: { "application/json": { schema: jsonSchema(skillResponse, "output") } } } } }, (service, { params }) => service.getSkill(params.skillId)), + route("PUT", "/api/v1/skills/{skillId}", "skills:write", { summary: "Update a global skill", responses: { "200": { description: "Updated", content: { "application/json": { schema: jsonSchema(skillResponse, "output") } } } } }, (service, { params, body }) => service.updateSkill(params.skillId, body), { body: skillUpdateInput }), + route("DELETE", "/api/v1/skills/{skillId}", "skills:write", { summary: "Delete an unused global skill", responses: { "200": { description: "Deleted" } } }, (service, { params, query }) => service.deleteSkill(params.skillId, query.expectedRevision), { query: z.object({ expectedRevision: z.coerce.number().int().positive() }) }), + route("GET", "/api/v1/skills/{skillId}/jobs", "skills:read", { summary: "List jobs using a skill", responses: { "200": { description: "Jobs", content: { "application/json": { schema: jsonSchema(skillJobsResponse, "output") } } } } }, (service, { params }) => service.listSkillJobs(params.skillId)), route("POST", "/api/v1/jobs/{jobId}/project", "flows:write", { summary: "Move a job to a project", responses: { "200": { description: "Moved", content: { "application/json": { schema: jsonSchema(jobResponse, "output") } } } } }, (service, { params, body }) => service.moveJob(params.jobId, body.projectId, body.expectedUpdatedAt), { body: z.object({ projectId: z.guid(), expectedUpdatedAt: z.iso.datetime().optional() }) }), route( "GET", diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/flow-schemas.ts index 7870532d..9960fca9 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -1,7 +1,7 @@ import { z } from "zod"; import { conditionsSchema, preparedWebhookSchema } from "./webhook-conditions"; -export const scopeSchema = z.enum(["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write"]); +export const scopeSchema = z.enum(["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write", "skills:read", "skills:write"]); export const runStateSchema = z.enum(["queued", "reserved", "starting", "running", "done", "blocked", "failed", "ignored", "succeeded", "stopping", "stopped"]); export const matchRuleSchema = z.object({ type: z.enum(["owner", "creator", "status", "label", "assignee"]), @@ -45,6 +45,7 @@ export const jobInputSchema = z.object({ model: z.string().trim().max(120).optional(), effort: z.string().trim().max(40).optional(), triggers: z.array(triggerSchema).max(50).default([]), + skillIds: z.array(z.guid()).max(50).optional(), }).strict(); export const jobIdSchema = z.object({ jobId: z.string().min(1) }); export const manualInvocationSchema = z.object({ diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index e74cf792..a96032ea 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -33,6 +33,8 @@ import { TraceProjectionRepository } from "./postgres/trace-projection-repositor import { replayTrace, traceReplaySchema, traceReplayRunIdSchema, TraceReplayError } from "./trace-replay"; import { ProjectRepository } from "./postgres/project-repository"; import { effortOptions, selectableExeTags, type ExeConnection } from "./exe"; +import { SkillRepository, SkillConflict, SkillReferenced } from "./postgres/skill-repository"; +import { skillInput, skillUpdateInput, skillPage, skillResponse, skillJobsResponse, previewSkillInput, composePrompt } from "./skills"; export class ServiceError extends Error { constructor(public status: number, public code: string, message: string) { super(message); } @@ -48,7 +50,7 @@ export function publicValue(schema: T, value: unknown): z.o return result.data; } -type Scope = "projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "integrations:read" | "integrations:write"; +type Scope = "projects:read" | "projects:write" | "jobs:read" | "jobs:write" | "runs:read" | "runs:invoke" | "runs:cancel" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write"; export class ApiService { authorizationDuration = 0; @@ -57,6 +59,7 @@ export class ApiService { private jobs() { return new PostgresJobRepository(databaseFor(this.env), this.auth.tenantId, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), value => decrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)); } private connections() { return new ConnectionRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } private projects() { return new ProjectRepository(databaseFor(this.env), this.auth.tenantId); } + private skills() { return new SkillRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } private async executionConfig(id: string) { // Target IDs created by the migration are deterministic md5-derived UUIDs, // so they do not necessarily have RFC 4122 version/variant bits. Any @@ -98,6 +101,12 @@ export class ApiService { return { id: old?.id ?? crypto.randomUUID(), jobId: old?.jobId ?? "", kind: trigger.kind, slug, enabled: trigger.enabled !== false, config: trigger.config, createdAt: old?.createdAt ?? timestamp, updatedAt: timestamp }; }); } + private async skillSelections(ids: string[]) { + if (new Set(ids).size !== ids.length) throw new ServiceError(400, "invalid_request", "A skill may only be selected once per job."); + const values = await Promise.all(ids.map(id => this.skills().get(id))); + if (values.some(value => !value)) throw new ServiceError(400, "invalid_request", "One or more selected skills are unavailable."); + return values.map((value, position) => ({ id: value!.id, key: value!.key, revision: value!.revision, body: value!.body ?? "", position })); + } private async jobStatistics(ids: string[]) { if (!ids.length) return new Map(); @@ -117,8 +126,15 @@ export class ApiService { private async presentJob(job: Job, loadedStats?: { running_count: string; last_run_state: string | null }) { const stats = loadedStats ?? (await this.jobStatistics([job.id])).get(job.id); const runningCount = Number(stats?.running_count ?? 0); - return publicValue(jobResponse, { ...job, triggers: job.triggers.map(trigger => ({ ...trigger, config: trigger.kind === "webhook" ? { ...trigger.config, ...(trigger.config.signingSecret || trigger.config.secret ? { secretConfigured: true } : {}), ...(trigger.config.provider === "cloudflareTail" ? { destination: `${this.env.APP_ORIGIN}/webhooks/cloudflare/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(job.id)}` } : {}) } : trigger.config })), runNameTemplate: job.runNameTemplate ?? "", executionConfigId: job.executionConfig.targetId ?? `${job.executionConfig.agentKind === "Amp" ? "amp:" : ""}${job.executionConfig.connectionId}`, agentKind: job.executionConfig.agentKind, runningCount, currentRuns: runningCount, maxConcurrency: job.concurrencyLimit, lastRunState: stats?.last_run_state ?? null }); + return publicValue(jobResponse, { ...job, skills: (job.selectedSkills ?? []).map(skill => ({ id: skill.id, key: skill.key, revision: skill.revision, position: skill.position })), triggers: job.triggers.map(trigger => ({ ...trigger, config: trigger.kind === "webhook" ? { ...trigger.config, ...(trigger.config.signingSecret || trigger.config.secret ? { secretConfigured: true } : {}), ...(trigger.config.provider === "cloudflareTail" ? { destination: `${this.env.APP_ORIGIN}/webhooks/cloudflare/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(job.id)}` } : {}) } : trigger.config })), runNameTemplate: job.runNameTemplate ?? "", executionConfigId: job.executionConfig.targetId ?? `${job.executionConfig.agentKind === "Amp" ? "amp:" : ""}${job.executionConfig.connectionId}`, agentKind: job.executionConfig.agentKind, runningCount, currentRuns: runningCount, maxConcurrency: job.concurrencyLimit, lastRunState: stats?.last_run_state ?? null }); } + async listSkills(query: { q: string; limit: number; cursor?: string }) { await this.authorize("skills:read"); return publicValue(skillPage, await this.skills().list(query.q, query.limit, query.cursor)); } + async getSkill(id: string) { await this.authorize("skills:read"); const value = await this.skills().get(id); if (!value) throw new ServiceError(404, "not_found", "Skill not found"); return publicValue(skillResponse, value); } + async createSkill(input: unknown) { await this.authorize("skills:write"); return publicValue(skillResponse, await this.skills().create(skillInput.parse(input).key, skillInput.parse(input).body)); } + async updateSkill(id: string, input: unknown) { await this.authorize("skills:write"); try { const value = await this.skills().update(id, skillUpdateInput.parse(input)); if (!value) throw new ServiceError(404, "not_found", "Skill not found"); return publicValue(skillResponse, value); } catch (e) { if (e instanceof SkillConflict) throw new ServiceError(409, "stale_skill", e.message); throw e; } } + async deleteSkill(id: string, expectedRevision: number) { await this.authorize("skills:write"); try { if (!await this.skills().remove(id, expectedRevision)) throw new ServiceError(404, "not_found", "Skill not found"); return { id, deleted: true }; } catch (e) { if (e instanceof SkillReferenced) throw new ServiceError(409, "skill_referenced", `${e.message} Jobs: ${e.jobs.map(job => job.name).join(", ")}`); if (e instanceof SkillConflict) throw new ServiceError(409, "stale_skill", e.message); throw e; } } + async listSkillJobs(id: string) { await this.authorize("skills:read"); return publicValue(skillJobsResponse, { skillId: id, jobs: await this.skills().jobs(id) }); } + async previewJobPrompt(input: unknown) { await this.authorize("skills:read"); const parsed = previewSkillInput.parse(input); const skills = await Promise.all(parsed.skillIds.map(async id => { const skill = await this.skills().get(id); if (!skill) throw new ServiceError(400, "invalid_request", "A selected skill is unavailable."); return skill; })); return { prompt: composePrompt(skills.map(skill => ({ body: skill.body ?? "" })), parsed.jobContext), skills: skills.map(skill => ({ id: skill.id, key: skill.key, revision: skill.revision })) }; } private async authorize(scope: Scope): Promise { if (!normalizeScopes(this.auth.scopes).includes(scope)) throw new ServiceError(403, "insufficient_scope", `The ${scope} scope is required.`); @@ -214,14 +230,16 @@ export class ApiService { await this.validateExecutionOptions(input.executionConfigId, input.model ?? "", input.effort ?? "", input.tags ?? []); const triggers = this.normalizedTriggers(input.triggers).map(trigger => ({ ...trigger, jobId: id })); const projectId = input.projectId ?? await this.projects().defaultProjectId(); - const job: Job = { id, projectId, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", tags: input.tags ?? [], model: input.model ?? "", ...(input.effort ? { effort: input.effort } : {}), executionConfig: await this.executionConfig(input.executionConfigId), concurrencyLimit: input.concurrencyLimit, enabled: true, triggers, createdAt: timestamp, updatedAt: timestamp }; + const selectedSkills = input.skillIds ? await this.skillSelections(input.skillIds) : []; + const job: Job = { id, projectId, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", tags: input.tags ?? [], model: input.model ?? "", ...(input.effort ? { effort: input.effort } : {}), executionConfig: await this.executionConfig(input.executionConfigId), concurrencyLimit: input.concurrencyLimit, enabled: true, triggers, selectedSkills, createdAt: timestamp, updatedAt: timestamp }; try { return this.presentJob(await this.jobs().create(job)); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "Job slug is already in use"); throw error; } } async updateJob(jobId: string, input: JobInput & { expectedUpdatedAt?: string }) { await this.authorize("jobs:write"); const repository = this.jobs(), current = await repository.getJob(jobId); if (!current) throw new ServiceError(404, "not_found", "Job not found"); await this.validateExecutionOptions(input.executionConfigId, input.model ?? "", input.effort ?? "", input.tags ?? []); const triggers = this.normalizedTriggers(input.triggers, current.triggers).map(trigger => ({ ...trigger, jobId })); - const updated = await repository.update({ ...current, projectId: input.projectId ?? current.projectId, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", tags: input.tags ?? [], model: input.model ?? "", effort: input.effort, executionConfig: await this.executionConfig(input.executionConfigId), concurrencyLimit: input.concurrencyLimit, triggers, updatedAt: new Date().toISOString() }, input.expectedUpdatedAt).catch(error => { if (error instanceof StaleJobEdit) throw new ServiceError(409, "stale_job", "This job changed. Reload its configuration before saving."); throw error; }); + const selectedSkills = input.skillIds === undefined ? current.selectedSkills : await this.skillSelections(input.skillIds); + const updated = await repository.update({ ...current, projectId: input.projectId ?? current.projectId, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", tags: input.tags ?? [], model: input.model ?? "", effort: input.effort, executionConfig: await this.executionConfig(input.executionConfigId), concurrencyLimit: input.concurrencyLimit, triggers, selectedSkills, updatedAt: new Date().toISOString() }, input.expectedUpdatedAt).catch(error => { if (error instanceof StaleJobEdit) throw new ServiceError(409, "stale_job", "This job changed. Reload its configuration before saving."); throw error; }); await this.wakeScheduler(); return this.presentJob(updated); } diff --git a/packages/api/src/job-contracts.ts b/packages/api/src/job-contracts.ts index 20033959..c576c2d8 100644 --- a/packages/api/src/job-contracts.ts +++ b/packages/api/src/job-contracts.ts @@ -39,6 +39,7 @@ export const jobResponse = z.object({ executionConfigId: z.string(), agentKind: z.string(), concurrencyLimit: z.number().int(), runningCount: z.number().int(), currentRuns: z.number().int(), maxConcurrency: z.number().int(), lastRunState: z.enum(["queued", "reserved", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped", "done", "ignored"]).nullable(), triggers: z.array(triggerResponse), + skills: z.array(z.object({ id: z.guid(), key: z.string(), revision: z.number().int().positive(), position: z.number().int().nonnegative() })).optional(), createdAt: z.string(), updatedAt: z.string(), }); // Omission keeps legacy REST/MCP last-writer-wins behavior. New editors supply diff --git a/packages/api/src/job-domain.ts b/packages/api/src/job-domain.ts index 51d7aefc..ecc53220 100644 --- a/packages/api/src/job-domain.ts +++ b/packages/api/src/job-domain.ts @@ -41,6 +41,7 @@ export interface Job { triggers: Trigger[]; createdAt: string; updatedAt: string; + selectedSkills?: { id: string; key: string; revision: number; body: string; position: number }[]; } export interface InvocationRequest { @@ -72,6 +73,7 @@ export interface JobRun { state: JobRunState; /** Persisted form is encrypted; repositories decrypt only at an authorized read boundary. */ encryptedPrompt: string; + encryptedSkillSnapshot?: string; runName?: string; createdAt: string; updatedAt: string; @@ -93,10 +95,11 @@ export class InvocationError extends Error { constructor(public code: "queue_full" | "job_not_found" | "job_disabled" | "invalid_invocation" | "invalid_template", message: string) { super(message); } } -export function renderJobPrompt(job: Pick, context: Record): string { +export function renderJobPrompt(job: Pick, context: Record): string { try { Mustache.parse(job.promptTemplate); - return renderTextTemplate(job.promptTemplate, context); + const rendered = renderTextTemplate(job.promptTemplate, context); + return [...(job.selectedSkills ?? []).sort((a, b) => a.position - b.position).map(skill => skill.body), rendered].join("\n\n"); } catch (error) { if (error instanceof InvocationError) throw error; throw new InvocationError("invalid_template", "The job prompt is not valid Mustache."); @@ -121,6 +124,7 @@ export class InvocationService { private encryptPrompt: (prompt: string) => Promise, private makeId: () => string = () => crypto.randomUUID(), private clock: () => string = () => new Date().toISOString(), + private encryptSnapshot: (snapshot: string) => Promise = encryptPrompt, ) {} async invoke(jobId: string, input: InvocationRequest): Promise { @@ -136,7 +140,8 @@ 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 run: JobRun = { id: this.makeId(), jobId, invocationId: invocation.id, state: "queued", encryptedPrompt: await this.encryptPrompt(renderJobPrompt(job, input.context)), runName: (input.source === "manual" ? input.name?.trim() : undefined) || renderRunName(job.runNameTemplate ?? "", input.context, job.name), createdAt, updatedAt: 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)) { const winner = await this.repository.findInvocation(jobId, input.claimKey); if (!winner) throw new Error("Invocation claim was lost without a persisted winner."); diff --git a/packages/api/src/postgres/job-repository.ts b/packages/api/src/postgres/job-repository.ts index f934f147..e27c1cdf 100644 --- a/packages/api/src/postgres/job-repository.ts +++ b/packages/api/src/postgres/job-repository.ts @@ -21,9 +21,12 @@ export class PostgresJobRepository implements JobRepository { const result = await db.execute(sql`INSERT INTO app.projects(tenant_id,id,name,description) VALUES (${this.tenantId}::uuid,md5(${this.tenantId}::text || ':default')::uuid,'Default','Jobs created by legacy clients') ON CONFLICT (tenant_id,name) DO UPDATE SET updated_at=app.projects.updated_at RETURNING id`); return result.rows[0].id as string; } - private async mapped(row: JobRow, db: any = this.database.orm, loadedTriggers?: TriggerRow[]): Promise { + private async mapped(row: JobRow, db: any = this.database.orm, loadedTriggers?: TriggerRow[], loadedSkills?: any[]): Promise { const triggerRows: TriggerRow[] = loadedTriggers ?? await db.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, row.id), isNull(triggers.removedAt))).orderBy(triggers.position, triggers.createdAt, triggers.id); - return { id: row.id, projectId: row.projectId, name: row.name, slug: row.slug, promptTemplate: await this.decrypt(row.encryptedPromptTemplate), runNameTemplate: row.encryptedRunNameTemplate ? await this.decrypt(row.encryptedRunNameTemplate) : "", tags: row.tags ?? [], model: row.model, ...(row.effort ? { effort: row.effort } : {}), executionConfig: row.executionConfig, concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, triggers: triggerRows.map(value => this.trigger(value)), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; + const skillRows = loadedSkills?.filter(skill => skill.job_id === row.id) ?? (db === this.database.orm + ? (await this.database.pool.query("SELECT s.id,s.key,s.revision,s.encrypted_body,js.position FROM app.job_skills js JOIN app.skills s ON s.tenant_id=js.tenant_id AND s.id=js.skill_id WHERE js.tenant_id=$1 AND js.job_id=$2 ORDER BY js.position", [this.tenantId, row.id])).rows + : (await db.execute(sql`SELECT s.id,s.key,s.revision,s.encrypted_body,js.position FROM app.job_skills js JOIN app.skills s ON s.tenant_id=js.tenant_id AND s.id=js.skill_id WHERE js.tenant_id=${this.tenantId}::uuid AND js.job_id=${row.id}::uuid ORDER BY js.position`)).rows); + return { id: row.id, projectId: row.projectId, name: row.name, slug: row.slug, promptTemplate: await this.decrypt(row.encryptedPromptTemplate), runNameTemplate: row.encryptedRunNameTemplate ? await this.decrypt(row.encryptedRunNameTemplate) : "", tags: row.tags ?? [], model: row.model, ...(row.effort ? { effort: row.effort } : {}), executionConfig: row.executionConfig, concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, triggers: triggerRows.map(value => this.trigger(value)), selectedSkills: await Promise.all(skillRows.map(async (skill: any) => ({ id: skill.id, key: skill.key, revision: skill.revision, body: await this.decrypt(skill.encrypted_body), position: skill.position }))), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; } async getJob(id: string): Promise { @@ -41,13 +44,14 @@ export class PostgresJobRepository implements JobRepository { group.push(trigger); byJob.set(trigger.jobId, group); } - return Promise.all(rows.map(row => this.mapped(row, this.database.orm, byJob.get(row.id) ?? []))); + return Promise.all(rows.map(row => this.mapped(row, this.database.orm, byJob.get(row.id) ?? [], []))); } async create(job: Job): Promise { return this.database.orm.transaction(async tx => { const [row] = await tx.insert(jobs).values({ tenantId: this.tenantId, id: job.id, projectId: job.projectId ?? await this.defaultProjectId(tx), name: job.name, slug: job.slug, encryptedPromptTemplate: await this.encrypt(job.promptTemplate), encryptedRunNameTemplate: job.runNameTemplate ? await this.encrypt(job.runNameTemplate) : "", executionConfig: job.executionConfig, tags: job.tags ?? [], model: job.model, effort: job.effort ?? "", concurrencyLimit: job.concurrencyLimit, enabled: job.enabled, createdAt: new Date(job.createdAt), updatedAt: new Date(job.updatedAt) }).returning(); await this.reconcileTriggers(tx, job, []); + await this.reconcileSkills(tx, job, []); return this.mapped(row!, tx); }); } @@ -61,6 +65,7 @@ export class PostgresJobRepository implements JobRepository { const existing: TriggerRow[] = await tx.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, job.id), isNull(triggers.removedAt))).orderBy(triggers.position); const [row] = await tx.update(jobs).set({ projectId: job.projectId, name: job.name, slug: job.slug, encryptedPromptTemplate: await this.encrypt(job.promptTemplate), encryptedRunNameTemplate: job.runNameTemplate ? await this.encrypt(job.runNameTemplate) : "", executionConfig: job.executionConfig, tags: job.tags ?? [], model: job.model, effort: job.effort ?? "", concurrencyLimit: job.concurrencyLimit, enabled: job.enabled, updatedAt: new Date(job.updatedAt) }).where(and(eq(jobs.tenantId, this.tenantId), eq(jobs.id, job.id))).returning(); await this.reconcileTriggers(tx, job, existing); + await this.reconcileSkills(tx, job, []); await this.recordEdit(tx, job.id, job.updatedAt); return this.mapped(row!, tx); }); @@ -123,13 +128,24 @@ export class PostgresJobRepository implements JobRepository { } else await tx.delete(scheduleState).where(and(eq(scheduleState.tenantId, this.tenantId), eq(scheduleState.triggerId, trigger.id))); } } + private async reconcileSkills(tx: any, job: Job, _existing: unknown[]): Promise { + const selected = job.selectedSkills ?? []; + const ids = selected.map(skill => skill.id); + if (new Set(ids).size !== ids.length) throw new Error("A skill may only be selected once per job"); + if (ids.length) { + const found = await tx.execute(sql`SELECT id FROM app.skills WHERE tenant_id=${this.tenantId}::uuid AND id IN (${sql.join(ids.map(id => sql`${id}::uuid`), sql`, `)}) FOR SHARE`); + if (found.rows.length !== ids.length) throw new Error("One or more selected skills are unavailable"); + } + await tx.execute(sql`DELETE FROM app.job_skills WHERE tenant_id=${this.tenantId}::uuid AND job_id=${job.id}::uuid`); + for (const [position, skill] of selected.entries()) await tx.execute(sql`INSERT INTO app.job_skills(tenant_id,job_id,skill_id,position) VALUES(${this.tenantId}::uuid,${job.id}::uuid,${skill.id}::uuid,${position})`); + } async delete(id: string): Promise { return Boolean((await this.database.orm.delete(jobs).where(and(eq(jobs.tenantId, this.tenantId), eq(jobs.id, id))).returning({ id: jobs.id })).length); } async findInvocation(jobId: string, claimKey: string) { - const result = await this.database.pool.query(`SELECT i.id invocation_id,i.job_id,i.source,i.claim_key,i.trigger_id,i.context,i.occurrence,i.created_at invocation_created_at,r.id run_id,r.state run_state,r.encrypted_prompt,r.run_name,r.created_at run_created_at,r.updated_at run_updated_at,r.started_at + const result = await this.database.pool.query(`SELECT i.id invocation_id,i.job_id,i.source,i.claim_key,i.trigger_id,i.context,i.occurrence,i.created_at invocation_created_at,r.id run_id,r.state run_state,r.encrypted_prompt,r.encrypted_skill_snapshot,r.run_name,r.created_at run_created_at,r.updated_at run_updated_at,r.started_at FROM app.invocations i JOIN app.job_runs r ON r.tenant_id=i.tenant_id AND r.invocation_id=i.id WHERE i.tenant_id=$1 AND i.job_id=$2 AND i.claim_key=$3`, [this.tenantId, jobId, claimKey]); const row = result.rows[0]; if (!row) return null; - return { invocation: { id: row.invocation_id, jobId: row.job_id, source: row.source, claimKey: row.claim_key, triggerId: row.trigger_id, context: row.context, ...(row.occurrence ? { occurrence: row.occurrence } : {}), createdAt: row.invocation_created_at.toISOString() } as Invocation, run: { id: row.run_id, jobId: row.job_id, invocationId: row.invocation_id, state: row.run_state, encryptedPrompt: row.encrypted_prompt, ...(row.run_name ? { runName: row.run_name } : {}), createdAt: row.run_created_at.toISOString(), updatedAt: row.run_updated_at.toISOString(), ...(row.started_at ? { startedAt: row.started_at.toISOString() } : {}) } as JobRun }; + return { invocation: { id: row.invocation_id, jobId: row.job_id, source: row.source, claimKey: row.claim_key, triggerId: row.trigger_id, context: row.context, ...(row.occurrence ? { occurrence: row.occurrence } : {}), createdAt: row.invocation_created_at.toISOString() } as Invocation, run: { id: row.run_id, jobId: row.job_id, invocationId: row.invocation_id, state: row.run_state, encryptedPrompt: row.encrypted_prompt, ...(row.encrypted_skill_snapshot ? { encryptedSkillSnapshot: row.encrypted_skill_snapshot } : {}), ...(row.run_name ? { runName: row.run_name } : {}), createdAt: row.run_created_at.toISOString(), updatedAt: row.run_updated_at.toISOString(), ...(row.started_at ? { startedAt: row.started_at.toISOString() } : {}) } as JobRun }; } async insertInvocationAndRun(invocation: Invocation, run: JobRun): Promise { return this.database.transaction(async client => { @@ -137,7 +153,7 @@ export class PostgresJobRepository implements JobRepository { const inserted = await client.query("INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context,occurrence,created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT (tenant_id,job_id,claim_key) DO NOTHING", [this.tenantId, invocation.id, invocation.jobId, invocation.source, invocation.claimKey, invocation.triggerId, invocation.context, invocation.occurrence ?? null, invocation.createdAt]); if (!inserted.rowCount) return false; await reserveExecutionSlot(client, this.tenantId, invocation.jobId, run, concurrencyLimit); - await client.query("INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt,run_name,created_at,updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)", [this.tenantId, run.id, run.jobId, run.invocationId, run.state, run.encryptedPrompt, run.runName ?? "", run.createdAt, run.updatedAt]); + await client.query("INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt,encrypted_skill_snapshot,run_name,created_at,updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)", [this.tenantId, run.id, run.jobId, run.invocationId, run.state, run.encryptedPrompt, run.encryptedSkillSnapshot ?? null, run.runName ?? "", run.createdAt, run.updatedAt]); await client.query(`INSERT INTO app.runs(tenant_id,id,job_id,invocation_id,provider,issue_id,run_name,agent_name,workspace_name,agent_kind,state,execution_backend_kind,execution_config,execution_capabilities,created_at,updated_at) SELECT $1,$2,$3,$4,$5,$6,$8,'',j.slug,j.execution_config->>'agentKind',$7, CASE WHEN j.execution_config->>'agentKind'='Amp' THEN 'amp' ELSE 'exe-vm' END, diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 294186de..840993e9 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -48,6 +48,10 @@ export const projects = app.table("projects", { tenantId: uuid("tenant_id").notN export const jobs = app.table("jobs", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), projectId: uuid("project_id").notNull(), name: text("name").notNull(), slug: text("slug").notNull(), encryptedPromptTemplate: text("encrypted_prompt_template").notNull(), encryptedRunNameTemplate: text("encrypted_run_name_template").notNull().default(""), executionConfig: jsonb("execution_config").$type().notNull(), tags: jsonb("tags").$type().notNull().default([]), model: text("model").notNull().default(""), effort: text("effort").notNull().default(""), concurrencyLimit: integer("concurrency_limit").notNull(), enabled: boolean("enabled").notNull().default(true), createdAt: createdAt(), updatedAt: updatedAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.slug), foreignKey({ columns: [t.tenantId, t.projectId], foreignColumns: [projects.tenantId, projects.id] }).onDelete("restrict"), index("jobs_tenant_project_updated").on(t.tenantId, t.projectId, t.updatedAt), check("jobs_concurrency_limit_check", sql`${t.concurrencyLimit} >= 1`)]); +export const skills = app.table("skills", { + tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), key: text("key").notNull(), encryptedBody: text("encrypted_body").notNull(), revision: integer("revision").notNull().default(1), createdAt: createdAt(), updatedAt: updatedAt(), +}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.key)]); +export const jobSkills = app.table("job_skills", { tenantId: uuid("tenant_id").notNull(), jobId: uuid("job_id").notNull(), skillId: uuid("skill_id").notNull(), position: integer("position").notNull() }, t => [primaryKey({ columns: [t.tenantId, t.jobId, t.skillId] }), unique().on(t.tenantId, t.jobId, t.position), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.skillId], foreignColumns: [skills.tenantId, skills.id] }).onDelete("restrict")]); export const triggers = app.table("triggers", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), kind: text("kind").$type().notNull(), slug: text("slug").notNull(), enabled: boolean("enabled").notNull().default(true), config: jsonb("config").$type>().notNull().default({}), position: integer("position").notNull().default(0), createdAt: createdAt(), updatedAt: updatedAt(), removedAt: timestamp("removed_at", { withTimezone: true }), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("triggers_active_slug").on(t.tenantId, t.jobId, t.slug).where(sql`${t.removedAt} is null`), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), check("no_webhook_handler_code", sql`NOT (${t.config} ? 'handlerCode')`), check("triggers_kind_check", sql`${t.kind} in ('manual','schedule','webhook','jobLifecycle')`)]); @@ -126,7 +130,7 @@ export const runRelations = relations(runs, ({ one, many }) => ({ export const databaseSchema = { schemaMigrations, tenants, oauthConnections, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, - connections, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, triggers, webhookConditionsCutover, invocations, jobRuns, runs, runArtifacts, + connections, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, skills, jobSkills, triggers, webhookConditionsCutover, invocations, jobRuns, runs, runArtifacts, runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, jobEditDeliveries, jobEvents, webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, runTraceCursors, runTraceChunks, runTraceProjections, traceReplayLimits, traceReplayOperations, diff --git a/packages/api/src/postgres/skill-repository.ts b/packages/api/src/postgres/skill-repository.ts new file mode 100644 index 00000000..afb23718 --- /dev/null +++ b/packages/api/src/postgres/skill-repository.ts @@ -0,0 +1,15 @@ +import type { Database } from "./database"; +import { decrypt, encrypt } from "../crypto"; +export class SkillConflict extends Error {} +export class SkillReferenced extends Error { constructor(public jobs: { id: string; name: string; slug: string; enabled: boolean; projectId: string }[]) { super("Skill is referenced by saved jobs."); } } +type SkillRow = { id: string; key: string; revision: number; encrypted_body: string; created_at: Date; updated_at: Date }; +export class SkillRepository { + constructor(private db: Database, private tenantId: string, private encryptionKey: string) {} + private async map(row: SkillRow, usageCount = 0, body = false) { return { id: row.id, key: row.key, revision: row.revision, ...(body ? { body: await decrypt(row.encrypted_body, this.encryptionKey) } : {}), usageCount, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }; } + async list(q = "", limit = 30, cursor?: string) { const result = await this.db.pool.query(`SELECT s.*, count(js.job_id)::text usage_count FROM app.skills s LEFT JOIN app.job_skills js ON js.tenant_id=s.tenant_id AND js.skill_id=s.id WHERE s.tenant_id=$1 AND ($2='' OR s.key ILIKE '%'||$2||'%') AND ($3::uuid IS NULL OR s.id < $3::uuid) GROUP BY s.id ORDER BY s.id DESC LIMIT $4`, [this.tenantId, q, cursor ?? null, limit + 1]); const page = result.rows.slice(0, limit); return { items: await Promise.all(page.map(row => this.map(row, Number(row.usage_count)))), nextCursor: result.rows.length > limit ? page.at(-1)!.id : null }; } + async get(idOrKey: string, includeBody = true) { const row = (await this.db.pool.query("SELECT * FROM app.skills WHERE tenant_id=$1 AND (id=$2::uuid OR key=$2) LIMIT 1", [this.tenantId, idOrKey])).rows[0]; return row ? this.map(row, 0, includeBody) : null; } + async create(key: string, body: string) { try { const row = (await this.db.pool.query("INSERT INTO app.skills(tenant_id,id,key,encrypted_body) VALUES($1,$2,$3,$4) RETURNING *", [this.tenantId, crypto.randomUUID(), key, await encrypt(body, this.encryptionKey)])).rows[0]; return this.map(row, 0, true); } catch (e: any) { if (e.code === "23505") throw new SkillConflict("Skill key is already in use."); throw e; } } + async update(id: string, input: { key?: string; body?: string; expectedRevision: number }) { const row = (await this.db.pool.query("SELECT * FROM app.skills WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.tenantId, id])).rows[0]; if (!row) return null; if (row.revision !== input.expectedRevision) throw new SkillConflict("Skill changed since it was loaded."); try { const updated = (await this.db.pool.query("UPDATE app.skills SET key=COALESCE($3,key),encrypted_body=COALESCE($4,encrypted_body),revision=revision+1,updated_at=now() WHERE tenant_id=$1 AND id=$2 RETURNING *", [this.tenantId, id, input.key ?? null, input.body === undefined ? null : await encrypt(input.body, this.encryptionKey)])).rows[0]; return this.map(updated, 0, true); } catch (e: any) { if (e.code === "23505") throw new SkillConflict("Skill key is already in use."); throw e; } } + async remove(id: string, expectedRevision: number) { return this.db.transaction(async client => { const skill = (await client.query("SELECT * FROM app.skills WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.tenantId, id])).rows[0]; if (!skill) return false; if (skill.revision !== expectedRevision) throw new SkillConflict("Skill changed since it was loaded."); const refs = (await client.query("SELECT j.id,j.name,j.slug,j.enabled,j.project_id FROM app.jobs j JOIN app.job_skills js ON js.tenant_id=j.tenant_id AND js.job_id=j.id WHERE js.tenant_id=$1 AND js.skill_id=$2 ORDER BY j.name", [this.tenantId, id])).rows; if (refs.length) throw new SkillReferenced(refs); await client.query("DELETE FROM app.skills WHERE tenant_id=$1 AND id=$2", [this.tenantId, id]); return true; }); } + async jobs(id: string) { return (await this.db.pool.query("SELECT j.id,j.name,j.slug,j.enabled,j.project_id FROM app.jobs j JOIN app.job_skills js ON js.tenant_id=j.tenant_id AND js.job_id=j.id WHERE js.tenant_id=$1 AND js.skill_id=$2 ORDER BY j.name", [this.tenantId, id])).rows; } +} diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index ee9b6104..9c8898b7 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -108,6 +108,13 @@ function createMcpServer(service: ApiService): McpServer { tool("stop_run", "Stop an active run", runIdSchema, ({ runId }: any) => service.stopRun(runId)); tool("kill_run", "Force a run in any non-terminal state to stop immediately, release its concurrency slot, and clean up its backend asynchronously.", runIdSchema, ({ runId }: any) => service.killRun(runId)); tool("list_jobs", "List jobs with their current run count and maximum concurrency", z.object({}), () => service.listJobs()); + tool("list_skills", "List searchable global skill metadata. Shared edits affect every job using the skill; bodies are omitted.", z.object({ q: z.string().optional(), limit: z.number().int().min(1).max(100).default(30), cursor: z.string().optional() }), (input: any) => service.listSkills({ q: input.q ?? "", limit: input.limit, cursor: input.cursor })); + tool("get_skill", "Read a global skill by stable ID or key. Shared edits affect every job using it.", z.object({ skillId: z.string().min(1) }), ({ skillId }: any) => service.getSkill(skillId)); + tool("create_skill", "Create a reusable literal global skill body.", z.object({ key: z.string().min(1), body: z.string() }), (input: any) => service.createSkill(input)); + tool("update_skill", "Update a shared global skill with optimistic concurrency; the change affects all referencing jobs.", z.object({ skillId: z.string().min(1), key: z.string().optional(), body: z.string().optional(), expectedRevision: z.number().int().positive() }), ({ skillId, ...input }: any) => service.updateSkill(skillId, input)); + tool("delete_skill", "Delete an unused global skill; referenced jobs block deletion.", z.object({ skillId: z.string().min(1), expectedRevision: z.number().int().positive() }), ({ skillId, expectedRevision }: any) => service.deleteSkill(skillId, expectedRevision)); + tool("list_skill_jobs", "List enabled and disabled jobs affected by a shared skill.", z.object({ skillId: z.string().min(1) }), ({ skillId }: any) => service.listSkillJobs(skillId)); + tool("preview_job_prompt", "Preview exact ordered literal skill composition plus rendered job context; does not save or execute.", z.object({ skillIds: z.array(z.string()).max(50), jobContext: z.string(), sampleTriggerData: z.record(z.string(), z.unknown()).optional() }), (input: any) => service.previewJobPrompt(input)); tool("list_projects", "List tenant projects with job counts", z.object({}), () => service.listProjects()); tool("get_project", "Get a tenant project", z.object({ projectId: z.string().min(1) }), ({ projectId }: any) => service.getProject(projectId)); tool("create_project", "Create a tenant project", z.object({ name: z.string().trim().min(1).max(120), description: z.string().max(2000).optional() }), (input: any) => service.createProject(input)); diff --git a/packages/api/src/skills.ts b/packages/api/src/skills.ts new file mode 100644 index 00000000..2c6dbfd3 --- /dev/null +++ b/packages/api/src/skills.ts @@ -0,0 +1,14 @@ +import { z } from "zod"; + +export const SKILL_KEY = /^[a-z][a-z0-9_-]{0,63}$/; +export const SKILL_BODY_LIMIT = 100_000; +export const skillInput = z.object({ key: z.string().trim().regex(SKILL_KEY), body: z.string().max(SKILL_BODY_LIMIT) }).strict(); +export const skillUpdateInput = z.object({ key: z.string().trim().regex(SKILL_KEY).optional(), body: z.string().max(SKILL_BODY_LIMIT).optional(), expectedRevision: z.number().int().positive() }).strict(); +export const skillResponse = z.object({ id: z.guid(), key: z.string(), revision: z.number().int().positive(), body: z.string(), usageCount: z.number().int().nonnegative(), createdAt: z.string(), updatedAt: z.string() }); +export const skillMetadata = skillResponse.omit({ body: true }); +export const skillPage = z.object({ items: z.array(skillMetadata), nextCursor: z.guid().nullable() }); +export const skillJobsResponse = z.object({ skillId: z.guid(), jobs: z.array(z.object({ id: z.guid(), name: z.string(), slug: z.string(), enabled: z.boolean(), projectId: z.guid() })) }); +export const previewSkillInput = z.object({ skillIds: z.array(z.guid()).max(50), jobContext: z.string().max(50_000), sampleTriggerData: z.record(z.string(), z.unknown()).optional() }).strict(); +export type Skill = z.infer; +/** Skill bodies are opaque; only the job template is Mustache-rendered. */ +export function composePrompt(skills: readonly { body: string }[], jobContext: string): string { return [...skills.map(skill => skill.body), jobContext].join("\n\n"); } diff --git a/packages/api/test/scope-redesign.test.ts b/packages/api/test/scope-redesign.test.ts index bfc7aefe..69c5063f 100644 --- a/packages/api/test/scope-redesign.test.ts +++ b/packages/api/test/scope-redesign.test.ts @@ -3,8 +3,8 @@ import { ACCESS_SCOPES, normalizeScopes } from "../src/access-tokens"; import { API_ROUTES } from "../src/api-contract"; describe("GEN-2418 permission boundaries", () => { - it("exposes exactly nine independently issuable scopes and maps legacy grants without issuing them", () => { - expect(ACCESS_SCOPES).toEqual(["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write"]); + it("exposes independently issuable skill scopes and maps legacy grants without issuing them", () => { + expect(ACCESS_SCOPES).toEqual(["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "integrations:read", "integrations:write", "skills:read", "skills:write"]); expect(normalizeScopes(["flows:read", "runs:write"])).toEqual(["projects:read", "jobs:read", "integrations:read", "runs:read", "runs:invoke", "runs:cancel"]); expect(ACCESS_SCOPES).not.toContain("flows:read" as never); }); diff --git a/packages/app/src/features/auth/account-bar.tsx b/packages/app/src/features/auth/account-bar.tsx index abde715c..235de226 100644 --- a/packages/app/src/features/auth/account-bar.tsx +++ b/packages/app/src/features/auth/account-bar.tsx @@ -33,7 +33,7 @@ export function AccountBar() {