From a14a32a4c9ceadc4ede372200288917756cf6237 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 20 Nov 2026 22:16:10 +0000 Subject: [PATCH] Define skills with frontmatter and versioned team presets --- TODO.md | 167 +- packages/api-client/src/schema.d.ts | 745 +++++- packages/api/migrations/0092_presets.sql | 46 + packages/api/src/api-contract.ts | 21 +- packages/api/src/flow-schemas.ts | 12 +- packages/api/src/flow-service.ts | 187 +- packages/api/src/job-domain.ts | 17 +- packages/api/src/mcp-skills.ts | 2 +- .../api/src/postgres/automation-scheduler.ts | 7 +- packages/api/src/postgres/job-repository.ts | 23 +- .../api/src/postgres/operations-repository.ts | 52 +- .../api/src/postgres/preset-repository.ts | 34 + packages/api/src/postgres/queue-admission.ts | 1 + packages/api/src/postgres/run-repository.ts | 4 +- packages/api/src/postgres/run-submission.ts | 11 +- packages/api/src/postgres/schema.ts | 2 +- packages/api/src/postgres/skill-repository.ts | 9 +- packages/api/src/postgres/webhook-service.ts | 3 +- packages/api/src/preset-migration.ts | 95 + packages/api/src/preset-resolution.ts | 37 + packages/api/src/presets.ts | 25 + packages/api/src/protected-api.ts | 18 +- packages/api/src/search-contracts.ts | 4 +- packages/api/src/skill-definition.ts | 54 + packages/api/src/skill-library.ts | 19 +- packages/api/src/skills.ts | 11 +- .../test/direct-run-defaults.postgres.test.ts | 45 +- packages/api/test/docker-code-job.e2e.test.ts | 28 +- .../api/test/hosted-workflow.postgres.test.ts | 1 + .../api/test/job-lifecycle.postgres.test.ts | 11 +- packages/api/test/loading.postgres.test.ts | 3 +- .../manual-invocation-permissions.test.ts | 1 + packages/api/test/mcp-skills.postgres.test.ts | 2 +- packages/api/test/pages-smoke.e2e.test.ts | 8 +- packages/api/test/preset-mcp.postgres.test.ts | 40 + .../test/preset-migration.postgres.test.ts | 73 + .../api/test/preset-runs.postgres.test.ts | 93 + packages/api/test/presets.postgres.test.ts | 41 + .../run-credential-repair.postgres.test.ts | 8 +- .../test/run-input-preview.postgres.test.ts | 3 +- packages/api/test/scope-redesign.test.ts | 2 +- packages/api/test/search.postgres.test.ts | 22 +- packages/api/test/skill-definition.test.ts | 20 + .../api/test/skill-editor.postgres.test.ts | 33 + .../api/test/skill-settings.postgres.test.ts | 98 +- .../api/test/skill-table.postgres.test.ts | 26 + .../api/test/trigger-context.postgres.test.ts | 2 +- .../api/test/workspace-vm.postgres.test.ts | 4 +- packages/app/src/features/jobs/editor.tsx | 2 +- .../app/src/features/jobs/trigger-editor.tsx | 4 +- packages/app/src/features/search/dialog.tsx | 10 +- packages/app/src/features/search/launcher.tsx | 2 +- .../src/features/settings/preset-combobox.tsx | 19 + .../src/features/settings/preset-queries.ts | 9 + .../app/src/features/settings/presets.tsx | 70 + packages/app/src/features/settings/routes.tsx | 5 +- packages/app/src/features/settings/team.tsx | 20 +- packages/app/src/features/skills/detail.tsx | 37 +- packages/app/src/features/skills/editor.tsx | 13 + .../features/skills/execution-settings.tsx | 26 - packages/app/src/features/skills/library.tsx | 30 +- .../app/src/features/skills/navigation.tsx | 5 +- packages/app/src/features/skills/queries.ts | 2 +- packages/app/src/features/skills/routes.tsx | 9 +- .../src/features/skills/trigger-settings.tsx | 4 +- packages/app/test/auth.browser.test.mjs | 3 +- packages/app/test/editor.browser.test.mjs | 18 +- .../app/test/functional/critical.spec.mjs | 4 +- packages/app/test/presets.browser.test.mjs | 58 + packages/app/test/settings.browser.test.mjs | 53 +- .../app/test/skill-search.browser.test.mjs | 36 + .../app/test/skill-triggers.browser.test.mjs | 32 + .../app/test/skills-presets.browser.test.mjs | 38 + .../app/test/skills-table.browser.test.mjs | 37 + packages/app/test/skills.browser.test.mjs | 69 +- packages/app/test/visual/design.spec.mjs | 16 +- packages/app/test/visual/fixtures.mjs | 2 +- packages/docs/integrations/oauth.mdx | 2 +- packages/docs/llms-full.txt | 121 +- packages/docs/llms.txt | 2 +- packages/docs/mcp/tools.mdx | 9 +- packages/docs/openapi.yaml | 2073 ++++++++++++++++- .../work/manual-invocation-permissions.mdx | 48 +- packages/docs/work/prompts.mdx | 2 +- packages/docs/work/results.mdx | 2 +- packages/docs/work/skills.mdx | 54 +- packages/docs/work/triggers.mdx | 6 +- scripts/agent-api-runtime.test.mjs | 12 +- scripts/background-run-acceptance.mjs | 8 +- scripts/docker-execution-e2e.mjs | 2 +- scripts/validation.mjs | 4 +- 91 files changed, 4386 insertions(+), 762 deletions(-) create mode 100644 packages/api/migrations/0092_presets.sql create mode 100644 packages/api/src/postgres/preset-repository.ts create mode 100644 packages/api/src/preset-migration.ts create mode 100644 packages/api/src/preset-resolution.ts create mode 100644 packages/api/src/presets.ts create mode 100644 packages/api/src/skill-definition.ts create mode 100644 packages/api/test/preset-mcp.postgres.test.ts create mode 100644 packages/api/test/preset-migration.postgres.test.ts create mode 100644 packages/api/test/preset-runs.postgres.test.ts create mode 100644 packages/api/test/presets.postgres.test.ts create mode 100644 packages/api/test/skill-definition.test.ts create mode 100644 packages/api/test/skill-editor.postgres.test.ts create mode 100644 packages/api/test/skill-table.postgres.test.ts create mode 100644 packages/app/src/features/settings/preset-combobox.tsx create mode 100644 packages/app/src/features/settings/presets.tsx create mode 100644 packages/app/src/features/skills/editor.tsx delete mode 100644 packages/app/src/features/skills/execution-settings.tsx create mode 100644 packages/app/test/presets.browser.test.mjs create mode 100644 packages/app/test/skill-search.browser.test.mjs create mode 100644 packages/app/test/skill-triggers.browser.test.mjs create mode 100644 packages/app/test/skills-presets.browser.test.mjs create mode 100644 packages/app/test/skills-table.browser.test.mjs diff --git a/TODO.md b/TODO.md index e6165f78..c585d06b 100644 --- a/TODO.md +++ b/TODO.md @@ -1,118 +1,147 @@ -# MCP proxy, skills, Pi telemetry, and Phoenix +# Preset-based skills ## Execution instructions -Complete each item in sequence, from top to bottom. Do not move on until every acceptance criterion for the current item has been met. Check each criterion off only after verification passes, record commands and evidence below the item, and then move to the next item. Do not stop until all items are complete. +Complete each item in sequence, from top to bottom. As its acceptance criteria are met, check them off and record the exact verification command and result under that item. Check off the item only after all its criteria pass. Continue until all items are complete, then push the branch and open a new pull request with the implementation and validation evidence. PR publication is the handoff, not an acceptance criterion requiring an external service. -All acceptance criteria must be achievable by an agent in this VM. Use isolated loopback PostgreSQL, local workerd/R2, Chromium, controlled clocks, and deterministic HTTP/model/Phoenix/client fixtures. No criterion requires production deployment, live credentials, an external client account, mobile hardware, an external registry update, or a live Phoenix service. Wire-contract fixtures do not establish that an external client's current release has been manually verified. Keep external discovery observations separate from proven local defects. +Every acceptance criterion below must be achievable by an agent in this VM. Use the pinned validation runner image, Node 24.12.0, npm 11.19.0, isolated loopback PostgreSQL, local Worker/artifact fixtures, deterministic model/integration fixtures, and Chromium. Do not require production deployment, live provider credentials, a real external model call, a live Git service for skill publication tests, or external approval. Never use production/shared databases. Use npm ci, preserve package boundaries, document JSON application endpoints under /api/v1 in OpenAPI, and regenerate the public client. Run the complete root npm test after the final code change. Do not mark unverified work complete. -Use the pinned validation image, Node 24.12.0 and npm 11.19.0; install with npm ci. Preserve package boundaries, external REST/MCP compatibility and accepted run snapshots. Document new public application operations under /api/v1 in OpenAPI and regenerate the public client. Run the complete root npm test after the final code change. +## 1. [x] Frontmatter contract and round-trip editing primitives -## 1. MCP proxy discovery and actionable reflection +Make SKILL.md the source of truth. Support name, description, and metadata.factorize with optional vm-preset, permission-preset, model-preset slugs; concurrency (nonnegative integer, default 0 = unlimited); and disabled (boolean, default false). Missing preset keys mean team defaults. Preserve unrelated frontmatter and the literal Markdown body. Slugs are human-readable, immutable, and unique within preset type/team. Retain internal IDs for identity and historical references. -Investigate tools/list and protocol compatibility against the observed connector catalog (reflection available, proxy tools missing). Do not assume a production defect from that observation. Keep request_api and read_api_response discoverable independently of proxy consent, with execution authorization enforced. Connect reflection services to exact tool names, integration IDs, relative-path conventions, example arguments and permission requirements. Distinguish permission failures from unavailable credentials. Add a local catalog diagnostic; document external refresh/deployment investigation without making it an acceptance gate. +Acceptance: +- [x] Local tests parse/validate all fields, omitted defaults, malformed YAML, invalid slugs/types, and zero/unlimited concurrency. +- [x] Round-trip tests preserve unknown frontmatter, unrelated metadata, and Markdown content when changing only Factorize controls. +- [x] Structured metadata is available through the public skill contract; generated client and backend/frontend package boundaries pass. + +Evidence: In pinned runner factorize-proxy-validation-final (Node 24.12.0/npm 11.19.0): skill-definition.test.ts 8 passed; npm run generate passed; npm run check:boundaries 11 passed; API tsc --noEmit passed. + +## 2. [x] Versioned VM, permission, and model presets with team defaults + +Retain VM provider/image/size/region/tags configuration, add permission presets (application scopes, integrations and invocation permissions), and model presets (model account/provider, model and effort). Each preset has name, immutable slug, stable ID and immutable revision. Team settings select one default of each type. Editing creates a revision rather than mutating historical configuration. Block deletion of defaults and presets referenced by skills, returning useful reference details. Enforce tenant isolation and write authorization. Validate referenced integrations/accounts using deterministic fixtures. Acceptance: -- [x] Authenticated local MCP discovery lists reflection, request_api and read_api_response even without proxy:use. -- [x] A fixture client follows reflection's example into request_api and reaches its authorized upstream. -- [x] Missing scope, blocked integration and unavailable credentials produce distinct actionable errors without secrets. -- [x] Local diagnostic/tests distinguish missing client tools from server authorization errors. +- [x] Local database/API tests cover CRUD for all three types, immutable slug validation, per-type/team uniqueness, revision history, and default replacement. +- [x] Tests reject deleting defaults or referenced presets and allow deleting unused presets; historical snapshots/revisions survive deletion. +- [x] Tests reject cross-team IDs/slugs, unavailable connections, unauthorized mutations, and stale writes without leaking secrets. +- [x] New operations are registered in protected-api.ts, documented in OpenAPI, and present in the regenerated public client. -Evidence: pinned-image npm ci completed; AUTH_TEST_DATABASE_URL pointing to isolated loopback PostgreSQL, vitest run test/proxy-discovery.postgres.test.ts: 3 passed, including real MCP discovery/calls, fixture-only HTTP, permission and damaged-credential failures. Backend tsc --noEmit passed; npm run generate completed. External connector refresh is documented, not claimed performed. +Evidence: Pinned runner presets.postgres.test.ts passed: all three kinds, revisions/default replacement, default/reference deletion guards, tenant isolation, stale/invalid writes and unavailable connections. npm run generate and API tsc --noEmit passed. -## 2. Bounded proxy results, retained responses and queries +## 3. [x] Migrate legacy configurations without losing instructions -Stream original upstream bytes into bounded artifact blocks. Default serialized model-facing proxy results to 4 KiB, allowing explicit increases up to a hard 32 KiB ceiling, accounting for encoding and both MCP content representations. Spill large results to storage and return safe status/headers, bounded preview, size, handle, expiry and read instructions. Offer companion tools and optional resource links. Add bounded JMESPath JSON filtering, text line ranges and binary byte ranges; retain range reads when JSON exceeds parser limits. Do not silently discard fields or invent upstream pagination. Temporary handles last 30 minutes and remain scoped to the authenticated OAuth connection or run. +Create/reuse presets for distinct team/skill VM, permission, and model configurations, select team defaults and link skills by slug in SKILL.md. Preserve extra saved prompts in the Markdown body. Preserve auxiliary skill files and Git publication semantics. Disable existing script automation and remove it from future execution; retain historical runs. Make migration resumable/idempotent and avoid external service calls in SQL migrations or test acceptance. Acceptance: -- [x] JSON, Unicode, escaped text and binary fixtures respect default/hard serialized budgets and retain exact original bytes. -- [x] Filtering, line/byte pagination, invalid queries and query/output limits pass local tests. -- [x] Downloads cross storage-block boundaries with bounded buffering. -- [x] Expiry, tenant/connection/run isolation, revocation and integration-epoch rechecks pass deterministic tests. -- [x] Existing REST response/chunk contracts remain compatible; sensitive headers are excluded. +- [x] Local legacy-fixture tests verify distinct configurations become distinct presets and equivalent configurations are reused. +- [x] Team defaults and skill references preserve effective non-script settings, concurrency semantics, prompts and supporting files. +- [x] Repeating/resuming migration neither duplicates presets/instructions nor loses committed content after a simulated failure. +- [x] Legacy script automation cannot create new runs, while historical run details and traces remain readable. -Evidence: pinned-image vitest proxy-results.postgres.test.ts, agent-api.postgres.test.ts and hosted-pi-mcp.postgres.test.ts: 14 passed; discovery/forwarder regression run: 18 passed. Tests cover exact Unicode/control/binary bytes, measured duplicated result budgets, 1 MiB storage blocks and boundary reads, filtering/pagination/parser limits, connection isolation, TTL/epoch/revocation, active-run authorization and legacy 64 KiB REST reads. Backend tsc --noEmit and contract generation passed. +Evidence: Pinned runner preset-migration.postgres.test.ts 2 passed, including local Git publication failure/recovery, idempotence, prompt/configuration/file preservation, disabled legacy script automation and retained run rows. -## 3. Durable HTTP operations and streaming +## 4. [x] Central preset resolution, immutable run snapshots, disabled and concurrency -Use existing scheduling/storage infrastructure for durable slow operations, not request-lifetime waitUntil as a durability guarantee. Fast requests may complete inline; slow/chunked/SSE bodies return handles with poll/read/cancel tools. Clients need no persistent connection, resource subscription or progress support. Provide progress as an optional enhancement. Preserve operations across reconnects and fence recovery; never blindly replay uncertain mutating calls. Fixed limits: request 32 MiB, response 64 MiB, upstream duration 15 minutes. Surface errors, partial-data state and uncertain upstream side effects; no configuration UI. +Resolve skill preset references or team defaults when creating a run, before it queues. Snapshot resolved settings plus preset IDs/slugs/revisions, inheritance flags and skill commit. Never re-resolve queued/existing runs. Apply consistent behavior to direct/manual, automated and MCP launches. Reject all new runs of disabled skills but let existing runs finish. Default skill concurrency to 0/unlimited; positive limits constrain execution. Retire script-based run creation from browser, REST and MCP; preserve historical read contracts and harmless omission compatibility. Keep credentials server-side and authorization ceilings intact. Acceptance: -- [x] Slow/chunked/SSE fixtures expose bounded handles and incremental reads, completing across disconnect/reconnect. -- [x] Restart/recovery and duplicate submissions cannot blindly repeat mutating requests. -- [x] Cancellation, revocation, disconnect/non-2xx and size/time limits surface explicit state and partial-data information. -- [x] Ordinary tool-only clients complete operations; supported progress clients receive optional progress. +- [x] Local integration tests prove explicit/inherited resolution, queued-run freezing and provenance for all three preset types. +- [x] Changing defaults, editing/deleting presets or editing skills cannot change accepted run snapshots or supporting files. +- [x] Disabled skills reject new manual/automated/MCP runs while existing runs can complete; positive concurrency limits and zero/unlimited work with scheduler fixtures. +- [x] Permission tests prove a preset cannot exceed the caller/delegation ceiling or bypass tenant/integration authorization. +- [x] New script requests fail actionably across supported launch paths; historical script runs remain readable. -Evidence: pinned-image proxy-operations.postgres.test.ts: 4 passed, exercising persisted dispatch, reconnect SSE reads, non-2xx status, interrupted-write idempotency, partial disconnect/cancel/timeout states, 32/64 MiB limits and revocation. proxy-discovery.postgres.test.ts plus run-alarm.test.ts: 8 passed, including actual legacy Streamable HTTP progress frames and alarm-object recreation. Backend tsc --noEmit and contract generation passed. +Evidence: Pinned runner preset-runs.postgres.test.ts passed: direct and scheduled admission, inherited/explicit revisions, positive and unlimited concurrency, queued snapshots claimed after edits/disable, permission ceiling rejection and script retirement. API tsc and generated contracts passed. MCP start_run delegates to the same tested service; discovery/call coverage follows in item 10. -## 4. Generic artifacts, staged request bodies and attachments +## 5. [x] Team Settings preset list and dedicated editor pages -Reuse artifact storage with generic temporary payload metadata, preserving image-specific media semantics. Support authorized artifact/response references, streaming integration imports, bounded staged chunks with immutable finalization, and raw/multipart request assembly. OAuth clients need no run. Payloads expire in 30 minutes with connection/run isolation. Add a dedicated ChatGPT attachment import tool with the documented top-level OpenAI file schema and openai/fileParams metadata. Stream temporary download URLs without integration credentials; validate public origins/redirects and exclude signed URLs from logs. Add an authenticated static-frontend upload page and documented upload operations returning a handle for clients without native handoff. Do not depend on the experimental MCP files extension. +VM, Permissions and Models left navigation each open their preset list. Show names/slugs, useful summaries and Default badges. Add opens a dedicated creation page. Each row's accessible ellipsis menu offers Edit, Make team default and Delete. Edit opens a dedicated page; Delete uses an application confirmation modal. Default/reference restrictions are explained. Preserve existing provider/image verification behavior with local fixtures. Team capacity remains a team setting. Acceptance: -- [x] File-parameter fixtures import exact bytes and reject malformed, missing, expired and oversized files with actionable errors. -- [x] Generic uploads, authorized artifacts, retained responses and integration imports become raw/multipart bodies without model-generated base64. -- [x] Staging ordering/idempotency/finalization and rejection of foreign, expired, incomplete or revoked handles pass tests. -- [x] Chromium completes the authenticated upload fallback without a run and rejects unauthorized access. -- [x] SSRF/redirect/isolation fixtures prove imports cannot reach private origins or leak credentials or signed URLs. +- [x] Chromium tests complete list/add/edit/default/delete flows for each type at desktop and mobile widths using local fixtures. +- [x] Add/edit have navigable URLs, Cancel returns to the correct list, and reload preserves routing. +- [x] Ellipsis menus and confirmation modals support keyboard/focus behavior; cancel does not mutate; errors retain input. +- [x] Default deletion is unavailable/rejected and referenced deletion lists blocking references; capacity remains editable. -Evidence: pinned-image proxy-payloads.postgres.test.ts and proxy-discovery.postgres.test.ts: 8 passed (native file schema/metadata, exact binary import, URL/redirect/expiry/oversize failures, staged ordering/idempotency/checksum, raw/multipart bodies, authorized artifact/retained-response/integration sources, browser API authorization, identity expiry/revocation). App build and backend tsc passed. Chromium proxy-upload.browser.test.mjs: 3 passed at 390/1280px plus anonymous redirect, with exact uploaded binary bytes and usable handle. +Evidence: npm run build:app passed in pinned runner; presets.browser.test.mjs 6 passed (all three types at 390/1280px), covering reloadable add/edit routes, immutable slugs, default switching/protection, confirmation cancel/delete, blocking-reference errors, keyboard Escape, cancel navigation and team capacity controls. -## 5. Default MCP Skills publishing with tool fallback +## 6. [x] Structured skill editor and rendered overview -Publish every active authorized team skill through io.modelcontextprotocol/skills by default, preserving existing tools for clients without extension support. Verify manifests/hashes, supporting resources, pagination and library updates. Preserve immutable accepted run packages; publishing does not execute or activate a skill. +Replace literal-file editing with controls for name, description, autocomplete VM/permission/model presets, concurrency and disabled, plus generic text editing of the Markdown body. Save the entire SKILL.md in one conditional revision, preserving unrelated metadata. Use the same editor for new skills. Overview displays a compact three-selector preset box above safely rendered Markdown; inherited values identify the resolved team default. Overview selector changes immediately save/commit only their metadata field with pending/error/conflict feedback. Remove Instructions heading and Start run. Retain the skill directory browser. Acceptance: -- [x] Discovery/list/get/read expose all authorized active packages with correct hashes and sizes. -- [x] Existing skill tools remain visible and usable without extension support. -- [x] Pagination, edits, rename/delete, failed publication, invalid paths and tenant isolation pass tests. -- [x] Pinned run packages and supporting files survive library edits, rename and deletion unchanged. +- [x] Chromium creates/edits a skill via controls and body text, then verifies serialized frontmatter and Markdown rendering. +- [x] Autocomplete supports filtering, keyboard selection, clearing to Team default, and unavailable-reference feedback. +- [x] Overview autosave changes the actual skill file/revision, preserves unrelated metadata/body/files, and handles failed/stale writes without overwriting concurrent edits. +- [x] Markdown links/code/lists render safely; no Instructions heading or overview Start run button remains; directory browsing still works. -Evidence: pinned-image vitest mcp-skills.test.ts, mcp-skills.postgres.test.ts, skill-library.postgres.test.ts and hosted-pi-mcp.postgres.test.ts: 16 passed. Includes extension discovery/pagination, exact per-file digest/size, legacy tool fallback without extension negotiation, scopes/member/tenant/path isolation, edit/rename/delete, Git publication preservation, and immutable pinned run supporting files. Existing default publishing implementation retained. +Evidence: Pinned runner skill-editor.postgres.test.ts passed for actual Git-backed file commits, unknown YAML preservation and stale revision rejection; skills-presets.browser.test.mjs 2 passed at 390/1280px for structured create/edit, Markdown safety/rendering, autocomplete/default clearing, autosave conflict/reload and supporting-file browsing. npm run build:app passed. -## 6. Durable Pi OpenTelemetry/OpenInference capture +## 7. [x] Replace skill Settings with Triggers -Instrument pinned hosted Pi model/agent boundaries using OpenTelemetry and Arize OpenInference conventions; verify rather than assume auto-instrumentor coverage. Persist independently of Phoenix: stable run trace, turn/model/tool spans, assistant/tool content, timings, retries, recovery, compaction, errors, finish reason, model/provider and reported input/output/cache/reasoning usage. Preserve trace IDs across scheduler leases and avoid duplicate accounting. Exclude credentials and temporary URLs; retain large content by reference with bounded reads and existing run retention. +Use Overview, Runs and Triggers subnavigation. Remove General/VM/Permissions settings pages and their controls. Triggers contains only non-manual trigger configuration, including disabled triggers; manual events are legacy implementation details and cannot appear in or be added through the editor. Retain independent manual invocation. Redirect old skill settings URLs to the appropriate replacement. Disabled skill messaging does not erase trigger configuration. Acceptance: -- [x] Deterministic Pi fixture records correlated run/turn/model/tool spans with content, timings and terminal status. -- [x] Model and compaction usage are persisted once; unavailable fields remain unavailable and cache/reasoning counts are not double-counted. -- [x] Retry, recovery, cancellation and failure preserve trace identity without duplicate spans or usage. -- [x] Authorization, tenant isolation, redaction and retention cleanup pass locally. -- [x] Capture works without Phoenix and emits valid OpenInference span attributes. +- [x] Chromium verifies new navigation, legacy URL redirects, empty state, and add/edit/disable/remove non-manual triggers. +- [x] No manual trigger option/row or execution settings form is visible; API tests cover empty and legacy manual-only trigger configurations. +- [x] Editing triggers does not overwrite skill metadata or resolved preset choices, and disabled skills retain trigger configuration. -Evidence: pinned-image pi-telemetry.postgres.test.ts and hosted-pi-mcp.postgres.test.ts: 10 passed, including real five-turn Pi execution with four tools, SDK-generated OTLP spans, reported cache/reasoning usage, stable IDs/idempotent recovery, compaction/retry/error/cancel spans, encrypted bounded Unicode content, secret/URL redaction, tenant isolation and cascading run retention. scripts/hosted-pi-runtime.test.mjs passed in workerd; backend tsc passed. No Phoenix connection used. +Evidence: skill-triggers.browser.test.mjs passed for navigation/legacy redirects, manual-only empty state and add/disable/remove schedule configuration. preset-runs.postgres.test.ts passed again, including empty visible configuration, retained independent manual invocation and unchanged SKILL.md. App build passed. -## 7. Run telemetry UI and cost estimates +## 8. [x] Skills table -Expose authorized paginated telemetry through documented /api/v1 contracts and generated client. Add live run totals and expandable turn/model/tool details with duration, usage, estimated cost and errors. Use a maintained versioned pricing catalog plus per-model overrides. Snapshot source/rates with estimates; unknown prices/usage remain unavailable rather than zero. Do not sum overlapping durations as wall time. +Use the shared table conventions with Skill name, Description, VM preset, Permission preset, Model preset and Triggers columns. Show Yes if any non-manual trigger exists, including disabled triggers; otherwise No. Resolve inherited preset labels. Keep New skill, existing pagination and useful loading/error/empty states. Remove the page title/subtitle, local search and List/Graph toggle. Acceptance: -- [x] API tests verify authorization, pagination, bounded details and usage/cost reconciliation. -- [x] Pricing fixtures cover catalog models, overrides, unknown models, cache/reasoning semantics and immutable historical estimates. -- [x] Desktop/mobile Chromium shows live totals, expandable details, errors/cancellation and unavailable fields. -- [x] Large content uses bounded detail reads; historical runs lacking telemetry remain readable. +- [x] Local API fixtures and Chromium verify all columns, explicit/default labels, description, navigation, pagination and empty/error/loading states. +- [x] Disabled non-manual triggers produce Yes; absent/manual-only triggers produce No. +- [x] Desktop/mobile layouts remain usable and contain no removed title/subtitle/search/toggle. -Evidence: pinned-image model-pricing.test.ts, run-telemetry.postgres.test.ts, pi-telemetry.postgres.test.ts and hosted-pi-mcp.postgres.test.ts: 14 passed. Covers catalog tiers, custom overrides, unknown usage/prices, non-duplicated cache/reasoning charges, immutable pricing snapshots, API scope/404/pagination/content limits and reconciled totals. Four targeted runs.browser.test.mjs Chromium scenarios passed (390/1280px, lazy bounded detail reads, live polling, canceled/error and historical/no-telemetry states). App build, generated contracts and backend tsc passed. +Evidence: skill-table.postgres.test.ts passed for descriptions, body omission, trigger flags and pagination. skills-table.browser.test.mjs 2 passed at 390/1280px for columns, explicit/inherited labels, Yes/No, pagination, empty/error states and removal of title/search/toggle. App build passed. -## 8. Phoenix Cloud integration and reliable export +## 9. [x] Global search for skill names and run names only -Add team-scoped endpoint, encrypted API key and destination project with connection testing. Export newly captured telemetry/content through a durable batched queue independent of execution. Reuse IDs, implement bounded transient retries and visible export state, and verify ingestion with a local receiver; do not promise exactly-once provider ingestion. Store destination/trace identifiers for a precise View in Phoenix link. Disable/disconnect stops future export and keeps keys server-side. Historical backfill is out of scope. +Replace trigger and trace search with skill-name and run-name matching. Do not match descriptions, skill instructions, issue identifiers/titles or message/trace contents independently. Keep useful exact/prefix/fuzzy ranking, highlighting, bounded tenant-scoped results and keyboard navigation. Link skills to their overview and runs to their detail page. Update launcher, dialog and accessibility labels. Acceptance: -- [x] Local API/browser tests configure, test, update, disable and disconnect the integration without exposing its key. -- [x] Local OTLP/Phoenix receiver validates authenticated destination and correlated multi-turn/tool spans. -- [x] Transient/permanent failures, retry, restart and disconnect preserve run success/local telemetry and expose export state. -- [x] Run page links to the fixture destination's exact trace using stored identifiers. -- [x] No integration means no export; tenant isolation and redaction hold. +- [x] Local PostgreSQL tests verify matching/ranking/highlighting of skill and run names, deterministic ordering, isolation and bounded results. +- [x] Negative tests prove trigger names, descriptions, bodies, issue identifiers/titles and trace content alone produce no results. +- [x] Chromium verifies click/keyboard navigation for both result kinds plus empty/loading/error and stale-response states. -Evidence: pinned-image phoenix.postgres.test.ts, run-alarm.test.ts and hosted-pi-mcp.postgres.test.ts: 12 passed. Independent local HTTP receiver decodes actual OTLP protobuf and verifies authentication/project/trace IDs, multi-turn/tool spans and usage. Tests cover accepted-but-failed acknowledgement retries, stale sending leases, eight-attempt cap, permanent errors/key repair, link lookup repair without retransmission, disabling/disconnection, no backfill and tenant isolation. Four Chromium scenarios passed for 390/1280px configuration/test/update/disable/disconnect and exact run trace links/export status. Local telemetry remains independent of export. +Evidence: search.postgres.test.ts + search.test.ts 10 passed for skill/run names, punctuation/typo matching, excluded trigger/issue/body/trace fields, tenant isolation, highlighting, 100-result bound and deterministic ordering. skill-search.browser.test.mjs passed for keyboard/click navigation, stale selection prevention and empty/loading/error states. App build passed. -## 9. Complete validation and handoff +## 10. [x] REST/MCP consistency and documentation + +Expose consistent preset management, default selection and frontmatter-backed skill configuration to external clients. Remove obsolete script/execution-settings mutation paths or return actionable retirement errors without silently accepting ignored fields. Preserve historical read/full-list/detail/trace and conditional-write omission compatibility. Explain defaults, slug references, concurrency, disabled behavior, snapshot timing and provenance in product/API/MCP documentation. Acceptance: -- [x] OpenAPI/client, package boundaries and documentation checks pass. -- [x] Complete root npm test passes after the final code change in the pinned image with isolated databases and deterministic providers. -- [x] Every preceding criterion has recorded local evidence and the final diff has been reviewed; no external service/client action is needed to reproduce acceptance. +- [x] Local MCP discovery/call tests manage presets, edit skill metadata, launch and inspect a preset-backed run with the same semantics as REST/browser. +- [x] Contract/boundary tests verify authorization, validation, retired inputs, omission compatibility and historical run reads. +- [x] npm run generate, contract drift checks, package boundaries and documentation validation pass locally. + +Evidence: preset-mcp.postgres.test.ts passed through real MCP discovery/calls; focused regression run passed 71 tests with one historical-preview fixture subsequently corrected and verified. preset-final-targeted.log: 7 files/17 tests passed. Worker agent-api-runtime.test.mjs: 2 passed including background acceptance. npm run generate, documentation generation/validation, package boundaries and API type checks passed. The final root suite in item 11 rechecks all contracts and historical reads together. -Evidence: complete root npm test exited 0 on 2026-11-20 after the final code change. All backend, browser, proxy and Docker validation steps passed in ghcr.io/generationsoftware/factorize-validation-runner@sha256:1333c4a7bb49c4cbcdd28ca2b57331dfcbff7cf611db1aaeaa4830517aacf6d4, using Node 24.12.0, npm 11.19.0 and isolated loopback PostgreSQL on port 55434. Backend: 140 files, 862 tests passed, five existing optional tests skipped; compiled app/API/PostgreSQL: 40 passed; browser application suite: 128 passed, one skipped; proxy protocol: 32 passed plus four harness checks; Docker: two passed. Contract generation/drift, package boundaries, documentation, builds and Worker-runtime checks all passed. The Worker fixture explicitly verifies synchronous proxy compatibility and the actionable error when durable scheduling is unavailable. Final diff reviewed and git diff --check passed. Full local log: /tmp/factorize-complete-validation-final.log. All preceding items have local evidence; no production deployment, client refresh or live Phoenix ingestion is claimed. +## 11. [x] Complete validation, review and PR handoff preparation + +Acceptance: +- [x] All preceding criteria are checked with reproducible local commands/evidence; no acceptance relies on external deployment or provider availability. +- [x] The complete root npm test passes after the final code change using pinned tooling and isolated databases. +- [x] git diff --check passes; final diff review covers migration failure safety, authorization, accepted-run immutability, and removed UI/routes/contracts. +- [x] A PR title/body describing behavior, migration, test results and limitations is prepared locally for publication. + +Evidence: Complete root suite passed after the final implementation/test change on 2026-11-20 in factorize-proxy-validation-final (pinned runner digest sha256:1333c4a7bb49c4cbcdd28ca2b57331dfcbff7cf611db1aaeaa4830517aacf6d4; Node 24.12.0/npm 11.19.0). Reproduce from the repository root after npm ci and isolated database bootstrap: + +```sh +docker exec -u exedev -w /work \ + -e DATABASE_URL=postgresql://postgres:local-validation-only@127.0.0.1:55434/factorize_presets_validation \ + -e AUTH_TEST_DATABASE_URL=postgresql://postgres:local-validation-only@127.0.0.1:55434/factorize_presets_validation \ + -e QUEUE_TEST_DATABASE_URL=postgresql://postgres:local-validation-only@127.0.0.1:55434/factorize_presets_validation \ + factorize-proxy-validation-final npm test +git diff --check +git diff --cached --check +``` + +Result: every root validation step passed (generated contracts/drift, build, backend, compiled app/API/PostgreSQL integration, functional/browser, portable proxy, Docker). Backend: 147 files, 877 passed/5 existing skips; compiled integration: 40 passed; functional Chromium: 6 passed; app: 139 passed/1 existing skip; proxy protocol: 32 passed plus 4 harness tests; Docker: 2 passed. Worker runtime, docs, package boundaries and type checks passed within the root suite. Local log: /tmp/factorize-presets-root-final.log. Final diff review covered tenant/scope authorization, default/reference deletion guards, immutable run snapshots and queued execution, encrypted/restart-safe migration checkpoints, legacy-route redirects and retired mutations. Runtime fixtures use unique artifact namespaces to avoid local Git socket collisions. Both diff whitespace checks passed. All criteria above are exercised locally without external providers or deployments. + +After every item is complete: commit, push this branch and open a new PR. Record the PR URL in the handoff; report external publication failures honestly without changing local acceptance results. diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index ce20152a..2f4a41f8 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -792,6 +792,84 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/presets": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List team VM, permission and model presets with defaults and immutable revisions + * @description Requires the integrations:read scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + get: operations["get_api_v1_presets"]; + put?: never; + /** + * Create a preset with a team-unique immutable slug + * @description Requires the integrations:write scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + post: operations["post_api_v1_presets"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/presets/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Create a new revision of a preset + * @description Requires the integrations:write scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + put: operations["put_api_v1_presets_id"]; + post?: never; + /** + * Delete an unused, non-default preset while retaining historical revisions + * @description Requires the integrations:write scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + delete: operations["delete_api_v1_presets_id"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/presets/{id}/default": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Select the team default for this preset type + * @description Requires the team:write scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + post: operations["post_api_v1_presets_id_default"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/vm-presets": { parameters: { query?: never; @@ -1676,14 +1754,15 @@ export interface paths { cookie?: never; }; /** - * Read skill execution defaults + * Read effective defaults resolved from skill frontmatter and presets * @description Requires the skills:read scope. * * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ get: operations["get_api_v1_skills_skillId_settings"]; /** - * Save skill execution defaults for future manual and triggered runs + * Retired: update skill frontmatter and presets instead + * @deprecated * @description Requires the skills:write and triggers:write scopes. * * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. @@ -2747,7 +2826,7 @@ export interface paths { put?: never; /** * Start a Team run from an optional skill and prompt, or a script - * @description Supply a skill, a prompt, or both for an agent run, or a script without an agent skill or prompt. Omitted settings use Team defaults. Default scopes, integrations and invocation destinations are bounded by the caller's effective access. Explicit unauthorized permissions fail. Explicit empty selections grant none. + * @description Supply a skill, a prompt, or images for an agent run. Script-based runs are retired. Skill frontmatter selects VM, permission and model presets; omitted selections inherit team defaults. Resolved preset revisions and the skill commit are snapshotted before queueing. Default scopes, integrations and invocation destinations are bounded by the caller's effective access. Explicit unauthorized permissions fail. Explicit empty selections grant none. * * Requires the runs:start scope. * @@ -2768,10 +2847,10 @@ export interface paths { cookie?: never; }; /** - * Search triggers and runs by approximate metadata matches - * @description Search uses PostgreSQL pg_trgm approximate matching over trigger names/slugs and run names, issue titles, and issue identifiers. Identifier matching is whole-field trigram matching; names and titles use word-level trigram matching. Exact identifiers and metadata names rank first, followed by the strongest individual field score. Results are unique, tenant-scoped, deterministically ordered, and limited to 100. Blank or punctuation-only queries return no results. One- and two-character queries may return no results because trigram matching is approximate; this is not ordered-character or substring matching. + * Search skill names and run names + * @description Search skill names and run names only, using case-insensitive substring and PostgreSQL pg_trgm word matching. Exact names rank first, then prefixes, then other matches by similarity with deterministic ties. Results are tenant-scoped and limited to 100. Triggers, descriptions, instruction bodies, issue fields and trace content are excluded. Blank or punctuation-only queries return no results. * - * Requires the triggers:read and runs:read scopes. + * Requires the skills:read and runs:read scopes. * * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ @@ -3533,6 +3612,10 @@ export interface components { requiresVm?: boolean; /** @default */ prompt: string; + /** + * @deprecated + * @description Retired: new script runs are rejected. Historical reads remain supported. + */ script?: string; runNameTemplate?: string; concurrencyLimit?: number; @@ -3767,6 +3850,15 @@ export interface components { "application/json": components["schemas"]["Error"]; }; }; + /** @description Operation retired; use skill frontmatter and team presets */ + Error410: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; }; parameters: never; requestBodies: never; @@ -5647,6 +5739,520 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_presets: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Presets */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + presets: ({ + slug: string; + name: string; + /** @constant */ + kind: "vm"; + settings: ({ + image: string; + region: string; + size: string; + /** @constant */ + provider: "fly"; + } | { + /** @constant */ + provider: "exe"; + connectionId: string; + image: string; + tags: string[]; + }) | { + /** @constant */ + provider: "none"; + }; + /** Format: uuid */ + id: string; + revision: number; + isDefault: boolean; + executionConfigId: string | null; + } | { + slug: string; + name: string; + /** @constant */ + kind: "permission"; + settings: { + /** @description Factorize API scopes for new trigger runs. Omission uses existing scopes on update or read/invoke defaults on create; an empty array grants no application scopes. triggers:write permits configuring triggers and their future run scopes. */ + runScopes?: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + portableIntegrationIds?: string[]; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; + allowedTriggerIds?: string[]; + }; + /** Format: uuid */ + id: string; + revision: number; + isDefault: boolean; + executionConfigId: string | null; + } | { + slug: string; + name: string; + /** @constant */ + kind: "model"; + settings: { + /** Format: uuid */ + modelAccountId?: string; + model?: string; + /** @enum {string} */ + effort?: "" | "minimal" | "low" | "medium" | "high" | "xhigh"; + }; + /** Format: uuid */ + id: string; + revision: number; + isDefault: boolean; + executionConfigId: 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_presets: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + slug: string; + name: string; + expectedRevision?: number; + /** @constant */ + kind: "vm"; + settings: ({ + image: string; + region: string; + size: string; + /** @constant */ + provider: "fly"; + } | { + /** @constant */ + provider: "exe"; + connectionId: string; + image: string; + tags: string[]; + }) | { + /** @constant */ + provider: "none"; + }; + } | { + slug: string; + name: string; + expectedRevision?: number; + /** @constant */ + kind: "permission"; + settings: { + /** @description Factorize API scopes for new trigger runs. Omission uses existing scopes on update or read/invoke defaults on create; an empty array grants no application scopes. triggers:write permits configuring triggers and their future run scopes. */ + runScopes?: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + portableIntegrationIds?: string[]; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; + allowedTriggerIds?: string[]; + }; + } | { + slug: string; + name: string; + expectedRevision?: number; + /** @constant */ + kind: "model"; + settings: { + /** Format: uuid */ + modelAccountId?: string; + model?: string; + /** @enum {string} */ + effort?: "" | "minimal" | "low" | "medium" | "high" | "xhigh"; + }; + }; + }; + }; + responses: { + /** @description Preset */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + preset: { + slug: string; + name: string; + /** @constant */ + kind: "vm"; + settings: ({ + image: string; + region: string; + size: string; + /** @constant */ + provider: "fly"; + } | { + /** @constant */ + provider: "exe"; + connectionId: string; + image: string; + tags: string[]; + }) | { + /** @constant */ + provider: "none"; + }; + /** Format: uuid */ + id: string; + revision: number; + isDefault: boolean; + executionConfigId: string | null; + } | { + slug: string; + name: string; + /** @constant */ + kind: "permission"; + settings: { + /** @description Factorize API scopes for new trigger runs. Omission uses existing scopes on update or read/invoke defaults on create; an empty array grants no application scopes. triggers:write permits configuring triggers and their future run scopes. */ + runScopes?: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + portableIntegrationIds?: string[]; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; + allowedTriggerIds?: string[]; + }; + /** Format: uuid */ + id: string; + revision: number; + isDefault: boolean; + executionConfigId: string | null; + } | { + slug: string; + name: string; + /** @constant */ + kind: "model"; + settings: { + /** Format: uuid */ + modelAccountId?: string; + model?: string; + /** @enum {string} */ + effort?: "" | "minimal" | "low" | "medium" | "high" | "xhigh"; + }; + /** Format: uuid */ + id: string; + revision: number; + isDefault: boolean; + executionConfigId: string | null; + }; + }; + }; + }; + 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"]; + }; + }; + put_api_v1_presets_id: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + slug: string; + name: string; + expectedRevision?: number; + /** @constant */ + kind: "vm"; + settings: ({ + image: string; + region: string; + size: string; + /** @constant */ + provider: "fly"; + } | { + /** @constant */ + provider: "exe"; + connectionId: string; + image: string; + tags: string[]; + }) | { + /** @constant */ + provider: "none"; + }; + } | { + slug: string; + name: string; + expectedRevision?: number; + /** @constant */ + kind: "permission"; + settings: { + /** @description Factorize API scopes for new trigger runs. Omission uses existing scopes on update or read/invoke defaults on create; an empty array grants no application scopes. triggers:write permits configuring triggers and their future run scopes. */ + runScopes?: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + portableIntegrationIds?: string[]; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; + allowedTriggerIds?: string[]; + }; + } | { + slug: string; + name: string; + expectedRevision?: number; + /** @constant */ + kind: "model"; + settings: { + /** Format: uuid */ + modelAccountId?: string; + model?: string; + /** @enum {string} */ + effort?: "" | "minimal" | "low" | "medium" | "high" | "xhigh"; + }; + }; + }; + }; + responses: { + /** @description Preset */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + preset: { + slug: string; + name: string; + /** @constant */ + kind: "vm"; + settings: ({ + image: string; + region: string; + size: string; + /** @constant */ + provider: "fly"; + } | { + /** @constant */ + provider: "exe"; + connectionId: string; + image: string; + tags: string[]; + }) | { + /** @constant */ + provider: "none"; + }; + /** Format: uuid */ + id: string; + revision: number; + isDefault: boolean; + executionConfigId: string | null; + } | { + slug: string; + name: string; + /** @constant */ + kind: "permission"; + settings: { + /** @description Factorize API scopes for new trigger runs. Omission uses existing scopes on update or read/invoke defaults on create; an empty array grants no application scopes. triggers:write permits configuring triggers and their future run scopes. */ + runScopes?: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + portableIntegrationIds?: string[]; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; + allowedTriggerIds?: string[]; + }; + /** Format: uuid */ + id: string; + revision: number; + isDefault: boolean; + executionConfigId: string | null; + } | { + slug: string; + name: string; + /** @constant */ + kind: "model"; + settings: { + /** Format: uuid */ + modelAccountId?: string; + model?: string; + /** @enum {string} */ + effort?: "" | "minimal" | "low" | "medium" | "high" | "xhigh"; + }; + /** Format: uuid */ + id: string; + revision: number; + isDefault: boolean; + executionConfigId: string | null; + }; + }; + }; + }; + 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_presets_id: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Deleted */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + deleted: boolean; + }; + }; + }; + 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_presets_id_default: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Default preset */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + preset: { + slug: string; + name: string; + /** @constant */ + kind: "vm"; + settings: ({ + image: string; + region: string; + size: string; + /** @constant */ + provider: "fly"; + } | { + /** @constant */ + provider: "exe"; + connectionId: string; + image: string; + tags: string[]; + }) | { + /** @constant */ + provider: "none"; + }; + /** Format: uuid */ + id: string; + revision: number; + isDefault: boolean; + executionConfigId: string | null; + } | { + slug: string; + name: string; + /** @constant */ + kind: "permission"; + settings: { + /** @description Factorize API scopes for new trigger runs. Omission uses existing scopes on update or read/invoke defaults on create; an empty array grants no application scopes. triggers:write permits configuring triggers and their future run scopes. */ + runScopes?: ("team:read" | "team:write" | "triggers:read" | "triggers:write" | "runs:read" | "runs:invoke" | "runs:start" | "runs:cancel" | "runs:write" | "integrations:read" | "integrations:write" | "skills:read" | "skills:write")[]; + portableIntegrationIds?: string[]; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; + allowedTriggerIds?: string[]; + }; + /** Format: uuid */ + id: string; + revision: number; + isDefault: boolean; + executionConfigId: string | null; + } | { + slug: string; + name: string; + /** @constant */ + kind: "model"; + settings: { + /** Format: uuid */ + modelAccountId?: string; + model?: string; + /** @enum {string} */ + effort?: "" | "minimal" | "low" | "medium" | "high" | "xhigh"; + }; + /** Format: uuid */ + id: string; + revision: number; + isDefault: boolean; + executionConfigId: 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"]; + }; + }; get_api_v1_vm_presets: { parameters: { query?: never; @@ -7172,6 +7778,11 @@ export interface operations { /** Format: uuid */ id: string; name: string | null; + presetDefaults?: { + vm: string | null; + permission: string | null; + model: string | null; + }; runDefaults: { executionConfigId?: string; requiresVm?: boolean; @@ -8186,6 +8797,8 @@ export interface operations { 403: components["responses"]["Error403"]; 404: components["responses"]["Error404"]; 409: components["responses"]["Error409"]; + /** @description Retired: edit SKILL.md frontmatter and team presets instead */ + 410: components["responses"]["Error410"]; 415: components["responses"]["Error415"]; 429: components["responses"]["Error429"]; 500: components["responses"]["Error500"]; @@ -8220,6 +8833,27 @@ export interface operations { usageCount: number; createdAt: string; updatedAt: string; + /** @default */ + description: string; + /** + * @default { + * "concurrency": 0, + * "disabled": false + * } + */ + factorize: { + "vm-preset"?: string; + "permission-preset"?: string; + "model-preset"?: string; + /** @default 0 */ + concurrency: number; + /** @default false */ + disabled: boolean; + } & { + [key: string]: unknown; + }; + /** @default false */ + hasTriggers: boolean; trigger?: { /** Format: uuid */ id: string; @@ -8252,7 +8886,23 @@ export interface operations { content: { "application/json": { key: string; - body: string; + body?: string; + definition?: { + name: string; + description: string; + factorize: { + "vm-preset"?: string; + "permission-preset"?: string; + "model-preset"?: string; + /** @default 0 */ + concurrency?: number; + /** @default false */ + disabled?: boolean; + } & { + [key: string]: unknown; + }; + markdown: string; + }; }; }; }; @@ -8269,6 +8919,22 @@ export interface operations { key: string; revision: number; body: string; + definition?: { + name: string; + description: string; + factorize: { + "vm-preset"?: string; + "permission-preset"?: string; + "model-preset"?: string; + /** @default 0 */ + concurrency: number; + /** @default false */ + disabled: boolean; + } & { + [key: string]: unknown; + }; + markdown: string; + }; usageCount: number; createdAt: string; updatedAt: string; @@ -8369,6 +9035,22 @@ export interface operations { key: string; revision: number; body: string; + definition?: { + name: string; + description: string; + factorize: { + "vm-preset"?: string; + "permission-preset"?: string; + "model-preset"?: string; + /** @default 0 */ + concurrency: number; + /** @default false */ + disabled: boolean; + } & { + [key: string]: unknown; + }; + markdown: string; + }; usageCount: number; createdAt: string; updatedAt: string; @@ -8399,6 +9081,22 @@ export interface operations { "application/json": { key?: string; body?: string; + definition?: { + name: string; + description: string; + factorize: { + "vm-preset"?: string; + "permission-preset"?: string; + "model-preset"?: string; + /** @default 0 */ + concurrency?: number; + /** @default false */ + disabled?: boolean; + } & { + [key: string]: unknown; + }; + markdown: string; + }; expectedRevision: number; }; }; @@ -8416,6 +9114,22 @@ export interface operations { key: string; revision: number; body: string; + definition?: { + name: string; + description: string; + factorize: { + "vm-preset"?: string; + "permission-preset"?: string; + "model-preset"?: string; + /** @default 0 */ + concurrency: number; + /** @default false */ + disabled: boolean; + } & { + [key: string]: unknown; + }; + markdown: string; + }; usageCount: number; createdAt: string; updatedAt: string; @@ -11023,6 +11737,8 @@ export interface operations { 403: components["responses"]["Error403"]; 404: components["responses"]["Error404"]; 409: components["responses"]["Error409"]; + /** @description Skill-backed triggers use permission presets; update that preset instead */ + 410: components["responses"]["Error410"]; 415: components["responses"]["Error415"]; 429: components["responses"]["Error429"]; 500: components["responses"]["Error500"]; @@ -11351,6 +12067,10 @@ export interface operations { requiresVm?: boolean; /** @default */ prompt?: string; + /** + * @deprecated + * @description Retired: new script runs are rejected. Historical reads remain supported. + */ script?: string; runNameTemplate?: string; concurrencyLimit?: number; @@ -11757,12 +12477,19 @@ export interface operations { requestBody: { content: { "application/json": { + vmPreset?: string; + permissionPreset?: string; + modelPreset?: string; attachments?: { /** Format: uuid */ artifactId: string; }[]; requiresVm?: boolean; prompt?: string; + /** + * @deprecated + * @description Retired: returns scripts_retired. Use an agent skill to execute code. + */ script?: string; skill?: string; name?: string; @@ -11829,14 +12556,14 @@ export interface operations { "application/json": { items: { /** @enum {string} */ - kind: "trigger" | "run" | "trace"; + kind: "skill" | "run"; id: string; title: string; subtitle: string; url: string; source: { /** @enum {string} */ - kind: "trigger" | "run" | "trace"; + kind: "skill" | "run"; label: string; id: string; }; diff --git a/packages/api/migrations/0092_presets.sql b/packages/api/migrations/0092_presets.sql new file mode 100644 index 00000000..dcb9aa4c --- /dev/null +++ b/packages/api/migrations/0092_presets.sql @@ -0,0 +1,46 @@ +CREATE TABLE app.presets ( + tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, + id uuid NOT NULL, + kind text NOT NULL CHECK(kind IN ('vm','permission','model')), + slug text NOT NULL CHECK(slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'), + name text NOT NULL, + revision integer NOT NULL DEFAULT 1, + settings jsonb NOT NULL, + is_default boolean NOT NULL DEFAULT false, + deleted boolean NOT NULL DEFAULT false, + PRIMARY KEY(tenant_id,id), + UNIQUE(tenant_id,kind,slug), + CHECK(NOT (deleted AND is_default)) +); +CREATE UNIQUE INDEX presets_default ON app.presets(tenant_id,kind) WHERE is_default; +CREATE TABLE app.preset_revisions ( + tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, + preset_id uuid NOT NULL, + revision integer NOT NULL, + kind text NOT NULL, + slug text NOT NULL, + name text NOT NULL, + settings jsonb NOT NULL, + PRIMARY KEY(tenant_id,preset_id,revision) +); +CREATE FUNCTION app.record_preset_revision() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP='INSERT' OR NEW.revision<>OLD.revision THEN + INSERT INTO app.preset_revisions VALUES(NEW.tenant_id,NEW.id,NEW.revision,NEW.kind,NEW.slug,NEW.name,NEW.settings); + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER preset_revision AFTER INSERT OR UPDATE ON app.presets FOR EACH ROW EXECUTE FUNCTION app.record_preset_revision(); +ALTER TABLE app.skills ADD COLUMN definition jsonb; +ALTER TABLE app.skills ADD COLUMN preset_migration_pending boolean NOT NULL DEFAULT false; +ALTER TABLE app.skills ADD COLUMN encrypted_preset_migration_body text; +ALTER TABLE app.skills ADD COLUMN preset_migration_source_hash text; +UPDATE app.skills SET preset_migration_pending=true; +INSERT INTO app.schema_migrations(version) VALUES('0092_presets'); +DO $$ DECLARE item record; BEGIN + FOR item IN SELECT conname FROM pg_constraint WHERE conrelid='app.triggers'::regclass AND contype='c' AND pg_get_constraintdef(oid) LIKE '%concurrency_limit%' LOOP + EXECUTE format('ALTER TABLE app.triggers DROP CONSTRAINT %I',item.conname); + END LOOP; +END $$; +ALTER TABLE app.triggers ADD CONSTRAINT triggers_concurrency_nonnegative CHECK(concurrency_limit>=0); +CREATE INDEX skills_key_trigram ON app.skills USING gin(key gin_trgm_ops); diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 221fa4e6..699cae63 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -1,3 +1,4 @@ +import { presetInput, presetResponse, presetList } from "./presets"; import { skillTriggerInput, skillTriggerResponse } from "./skill-trigger"; import { skillSettings, skillSettingsInput } from "./skill-settings"; import { profileInput, profileResponse } from "./usernames"; @@ -441,6 +442,11 @@ export const API_ROUTES: RouteContract[] = [ description: "Owner browser session only. Deletes the tenant's encrypted provisioning token.", responses: { "200": { description: "Deletion result", content: { "application/json": { schema: jsonSchema(z.object({ deleted: z.boolean() }), "output") } } } }, }, service => service.removeFlyConnection(), { ownerSession: true }), + route("GET", "/api/v1/presets", "integrations:read", {summary:"List team VM, permission and model presets with defaults and immutable revisions",responses:{"200":{description:"Presets",content:{"application/json":{schema:jsonSchema(presetList,"output")}}}}},service=>service.listPresets()), + route("POST", "/api/v1/presets", "integrations:write", {summary:"Create a preset with a team-unique immutable slug",responses:{"200":{description:"Preset",content:{"application/json":{schema:jsonSchema(z.object({preset:presetResponse}),"output")}}}}},(service,{body})=>service.savePreset(body),{body:presetInput}), + route("PUT", "/api/v1/presets/{id}", "integrations:write", {summary:"Create a new revision of a preset",responses:{"200":{description:"Preset",content:{"application/json":{schema:jsonSchema(z.object({preset:presetResponse}),"output")}}}}},(service,{body,params})=>service.savePreset(body,params.id),{body:presetInput,parameters:z.object({id:z.uuid()})}), + route("POST", "/api/v1/presets/{id}/default", "team:write", {summary:"Select the team default for this preset type",responses:{"200":{description:"Default preset",content:{"application/json":{schema:jsonSchema(z.object({preset:presetResponse}),"output")}}}}},(service,{params})=>service.defaultPreset(params.id),{parameters:z.object({id:z.uuid()})}), + route("DELETE", "/api/v1/presets/{id}", "integrations:write", {summary:"Delete an unused, non-default preset while retaining historical revisions",responses:{"200":{description:"Deleted",content:{"application/json":{schema:jsonSchema(z.object({deleted:z.boolean()}),"output")}}}}},(service,{params})=>service.deletePreset(params.id),{parameters:z.object({id:z.uuid()})}), route("GET", "/api/v1/vm-presets", "integrations:read", { summary: "List VM presets", responses: { "200": { description: "List VM presets", content: { "application/json": { schema: jsonSchema(z.object({ presets: z.array(vmPreset) }), "output") } } } }, }, service => service.listVmPresets(), { ownerSession: true }), @@ -823,8 +829,8 @@ export const API_ROUTES: RouteContract[] = [ route("GET", "/api/v1/skills/{skillId}/files", "skills:read", {summary:"Browse the published skill directory at its immutable revision",responses:{"200":{description:"Published files, with base64 encoded contents",content:{"application/json":{schema:jsonSchema(skillDirectoryResponse,"output")}}}}},(service,{params})=>service.getSkillDirectory(params.skillId),{parameters:z.object({skillId:z.uuid()})}), route("GET", "/api/v1/skills/{skillId}/trigger", ["skills:read","triggers:read"], {summary:"Read a skill's optional trigger",responses:{"200":{description:"Optional trigger",content:{"application/json":{schema:jsonSchema(skillTriggerResponse,"output")}}}}},(service,{params})=>service.getSkillTrigger(params.skillId),{parameters:z.object({skillId:z.uuid()})}), route("PUT", "/api/v1/skills/{skillId}/trigger", ["skills:write","triggers:write"], {summary:"Configure a skill's event sources and enabled state",responses:{"200":{description:"Saved trigger",content:{"application/json":{schema:jsonSchema(skillTriggerResponse,"output")}}}}},(service,{params,body})=>service.saveSkillTrigger(params.skillId,body),{parameters:z.object({skillId:z.uuid()}),body:skillTriggerInput,maxBodyBytes:1_000_000}), - route("GET", "/api/v1/skills/{skillId}/settings", "skills:read", {summary:"Read skill execution defaults",responses:{"200":{description:"Skill settings",content:{"application/json":{schema:jsonSchema(skillSettings,"output")}}}}},(service,{params})=>service.getSkillSettings(params.skillId),{parameters:z.object({skillId:z.uuid()})}), - route("PUT", "/api/v1/skills/{skillId}/settings", ["skills:write","triggers:write"], {summary:"Save skill execution defaults for future manual and triggered runs",responses:{"200":{description:"Saved skill settings",content:{"application/json":{schema:jsonSchema(skillSettings,"output")}}}}},(service,{params,body})=>service.setSkillSettings(params.skillId,body),{parameters:z.object({skillId:z.uuid()}),body:skillSettingsInput,maxBodyBytes:300_000}), + route("GET", "/api/v1/skills/{skillId}/settings", "skills:read", {summary:"Read effective defaults resolved from skill frontmatter and presets",responses:{"200":{description:"Skill settings",content:{"application/json":{schema:jsonSchema(skillSettings,"output")}}}}},(service,{params})=>service.getSkillSettings(params.skillId),{parameters:z.object({skillId:z.uuid()})}), + route("PUT", "/api/v1/skills/{skillId}/settings", ["skills:write","triggers:write"], {summary:"Retired: update skill frontmatter and presets instead",deprecated:true,responses:{"410":{description:"Retired: edit SKILL.md frontmatter and team presets instead",content:{"application/json":{schema:{$ref:"#/components/schemas/Error"}}}},"200":{description:"Saved skill settings",content:{"application/json":{schema:jsonSchema(skillSettings,"output")}}}}},(service,{params,body})=>service.setSkillSettings(params.skillId,body),{parameters:z.object({skillId:z.uuid()}),body:skillSettingsInput,maxBodyBytes:300_000}), 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/triggers/preview", "skills:read", { summary: "Preview one skill, a literal prompt and optional Event template", responses: { "200": { description: "Prompt preview", content: { "application/json": { schema: jsonSchema(previewPromptResponse, "output") } } } } }, (service, { body }) => service.previewTriggerPrompt(body), { body: previewSkillInput }), @@ -949,7 +955,7 @@ export const API_ROUTES: RouteContract[] = [ service => service.getRuntimeContext()), route("GET", "/api/v1/runtime-integrations", [], { summary: "Discover this run's selected integration endpoints", description: "Requires vendor-verified run identity. Returns only snapshotted selections, safe connection metadata, X OAuth scopes, and current availability, without origins or credentials. X connections use /x/{connectionId}/ for supported API v2 resources; each resource is checked against selected and granted OAuth scopes. Selection authorization is independent of the run's Factorize API scopes.", responses: { "200": { description: "Selected run integrations", content: { "application/json": { schema: jsonSchema(runtimeIntegrationsResponse, "output") } } } } }, service => service.getRuntimeIntegrations()), route("GET", "/api/v1/triggers/{triggerId}/invocation-permissions", "triggers:read", { summary: "List a source trigger's manual invocation destinations", responses: { "200": { description: "Configured destination triggers in the same project", content: { "application/json": { schema: jsonSchema(invocationPermissionsResponse, "output") } } } } }, (service, { params }) => service.getInvocationPermissions(params.triggerId)), - route("PUT", "/api/v1/triggers/{triggerId}/invocation-permissions", "triggers:write", { summary: "Replace a source trigger's manual invocation destinations", description: "Requires an owner session, scoped API key, or authorized OAuth client with triggers:write. Destinations must belong to the source trigger's project; self-invocation is allowed. A run token may invoke a configured destination only while both triggers remain in the same project. 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.triggerId, body.destinationTriggerIds), { body: invocationPermissionsInput }), + route("PUT", "/api/v1/triggers/{triggerId}/invocation-permissions", "triggers:write", { summary: "Replace a source trigger's manual invocation destinations", description: "Requires an owner session, scoped API key, or authorized OAuth client with triggers:write. Destinations must belong to the source trigger's project; self-invocation is allowed. A run token may invoke a configured destination only while both triggers remain in the same project. Lifecycle subscriptions do not create permissions.", responses: { "410": {description:"Skill-backed triggers use permission presets; update that preset instead",content:{"application/json":{schema:{$ref:"#/components/schemas/Error"}}}}, "200": { description: "Saved manual invocation permissions", content: { "application/json": { schema: jsonSchema(invocationPermissionsResponse, "output") } } } } }, (service, { params, body }) => service.setInvocationPermissions(params.triggerId, body.destinationTriggerIds), { body: invocationPermissionsInput }), route( "GET", "/api/v1/triggers/{triggerId}/events", @@ -1016,7 +1022,7 @@ export const API_ROUTES: RouteContract[] = [ ), route("POST","/api/v1/runs","runs:start",{ summary:"Start a Team run from an optional skill and prompt, or a script", - description:"Supply a skill, a prompt, or both for an agent run, or a script without an agent skill or prompt. Omitted settings use Team defaults. Default scopes, integrations and invocation destinations are bounded by the caller's effective access. Explicit unauthorized permissions fail. Explicit empty selections grant none.", + description:"Supply a skill, a prompt, or images for an agent run. Script-based runs are retired. Skill frontmatter selects VM, permission and model presets; omitted selections inherit team defaults. Resolved preset revisions and the skill commit are snapshotted before queueing. Default scopes, integrations and invocation destinations are bounded by the caller's effective access. Explicit unauthorized permissions fail. Explicit empty selections grant none.", responses:{"202":{description:"Accepted run",content:{"application/json":{schema:jsonSchema(startRunReceipt,"output")}}}}, },(service,{body})=>service.startRun(body),{body:startRunInput,maxBodyBytes:256_000}), route( @@ -1043,10 +1049,10 @@ export const API_ROUTES: RouteContract[] = [ route( "GET", "/api/v1/search", - "triggers:read+runs:read", + "skills:read+runs:read", { - summary: "Search triggers and runs by approximate metadata matches", - description: "Search uses PostgreSQL pg_trgm approximate matching over trigger names/slugs and run names, issue titles, and issue identifiers. Identifier matching is whole-field trigram matching; names and titles use word-level trigram matching. Exact identifiers and metadata names rank first, followed by the strongest individual field score. Results are unique, tenant-scoped, deterministically ordered, and limited to 100. Blank or punctuation-only queries return no results. One- and two-character queries may return no results because trigram matching is approximate; this is not ordered-character or substring matching.", + summary: "Search skill names and run names", + description: "Search skill names and run names only, using case-insensitive substring and PostgreSQL pg_trgm word matching. Exact names rank first, then prefixes, then other matches by similarity with deterministic ties. Results are tenant-scoped and limited to 100. Triggers, descriptions, instruction bodies, issue fields and trace content are excluded. Blank or punctuation-only queries return no results.", responses: { "200": { description: "Search results", content: { "application/json": { schema: jsonSchema(searchResponse, "output") } } } }, }, (service, { query }) => service.search(query.q), @@ -1315,6 +1321,7 @@ export function generateOpenApi() { { description, content: errorContent }, ]), ); + errorResponses.Error410={description:"Operation retired; use skill frontmatter and team presets",content:errorContent}; const namedBodies: Record = { TriggerInput: triggerInputSchema, ManualInvocation: manualInvocationSchema, diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/flow-schemas.ts index bb0777e8..579f6e3f 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -1,3 +1,4 @@ +import { presetSlug } from "./skill-definition"; import {mediaRef} from "./media-contracts"; import Mustache from "mustache"; import { z } from "zod"; @@ -68,9 +69,9 @@ export const triggerInputSchema = z.object({ executionType: z.enum(["agent", "code"]).optional(), requiresVm:z.boolean().optional(), prompt: z.string().max(50_000).default(""), - script: z.string().max(50_000).optional(), + script: z.string().max(50_000).optional().describe("Retired: new script runs are rejected. Historical reads remain supported.").meta({deprecated:true}), runNameTemplate: z.string().max(500).optional(), - concurrencyLimit: z.number().int().min(1).max(50).optional(), + concurrencyLimit: z.number().int().nonnegative().max(50).optional(), runScopes: z.array(scopeSchema).max(scopeSchema.options.length).refine(scopes => new Set(scopes).size === scopes.length, "Run scopes must be unique").optional().describe("Factorize API scopes for new trigger runs. Omission uses existing scopes on update or read/invoke defaults on create; an empty array grants no application scopes. triggers:write permits configuring triggers and their future run scopes."), executionConfigId: z.string().min(1).optional(), tags: z.array(z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/)).max(20).optional(), @@ -113,10 +114,11 @@ export type TriggerInput = z.infer; export type ManualInvocationInput = z.infer; export const startRunInput = z.object({ + vmPreset:presetSlug.optional(),permissionPreset:presetSlug.optional(),modelPreset:presetSlug.optional(), attachments:z.array(mediaRef).max(16).optional(), requiresVm:z.boolean().optional(), prompt: z.string().min(1).max(50_000).refine(value => !!value.trim()).optional(), - script: z.string().min(1).max(200_000).refine(value => !!value.trim()).optional(), + script: z.string().min(1).max(200_000).refine(value => !!value.trim()).optional().describe("Retired: returns scripts_retired. Use an agent skill to execute code.").meta({deprecated:true}), skill: z.string().min(1).max(64).optional(), name: z.string().trim().min(1).max(120).optional(), executionConfigId: z.string().min(1).optional(), @@ -140,7 +142,7 @@ export const projectRunDefaults = z.object({ portableIntegrationIds: triggerInputSchema.shape.portableIntegrationIds, githubInstallationIds: triggerInputSchema.shape.githubInstallationIds, linearConnectionId: triggerInputSchema.shape.linearConnectionId, xConnectionIds: triggerInputSchema.shape.xConnectionIds, runScopes: triggerInputSchema.shape.runScopes, capacity: z.number().int().min(1).max(50).default(4), - concurrencyLimit: z.number().int().min(1).max(50).optional(), + concurrencyLimit: z.number().int().nonnegative().optional(), }).strict(); export const storedRunDefaults = projectRunDefaults.extend({vmImage:z.string().optional()}); @@ -150,4 +152,4 @@ export const teamRunDefaults = projectRunDefaults.partial().extend({ capacity: z.number().int().min(1).max(50).optional(), allowedTriggerIds: z.array(z.guid()).max(100).refine(ids => new Set(ids).size === ids.length, "Destination triggers must be unique").optional(), }).strict(); -export const teamResponse = z.object({ id: z.guid(), name: z.string().nullable(), runDefaults: teamRunDefaults.extend({ vmImage: z.string().optional() }) }); +export const teamResponse = z.object({ id: z.guid(), name: z.string().nullable(), presetDefaults:z.object({vm:z.string().nullable(),permission:z.string().nullable(),model:z.string().nullable()}).optional(), runDefaults: teamRunDefaults.extend({ vmImage: z.string().optional() }) }); diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 97e3f120..5a6dcdfe 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -1,3 +1,8 @@ +import { migratePresetSkills } from "./preset-migration"; +import { resolveSkillPresets, assertPresetSnapshot } from "./preset-resolution"; +import { presetInput } from "./presets"; +import { PresetRepository } from "./postgres/preset-repository"; +import { readSkillDefinition, writeSkillDefinition, type SkillDefinition } from "./skill-definition"; import { markdown, validPath } from "./skill-files"; import { PostgresSkillContentCache } from "./postgres/skill-content-cache"; import { skillTriggerInput } from "./skill-trigger"; @@ -105,7 +110,7 @@ export class ApiService { authorizationDuration = 0; constructor(private env: Env, private auth: OAuthProps, private ctx?: ExecutionContext, private flyMetadata: FlyExecutionMetadataLoader = getFlyExecutionMetadata) {} - private triggers() { return new PostgresTriggerRepository(databaseFor(this.env), this.auth.tenantId, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), value => decrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), new SkillContent(this.env.SKILL_ARTIFACTS,new PostgresSkillContentCache(databaseFor(this.env),this.auth.tenantId,this.env.CREDENTIAL_ENCRYPTION_KEY))); } + private triggers() { return new PostgresTriggerRepository(databaseFor(this.env), this.auth.tenantId, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), value => decrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), new SkillContent(this.env.SKILL_ARTIFACTS,new PostgresSkillContentCache(databaseFor(this.env),this.auth.tenantId,this.env.CREDENTIAL_ENCRYPTION_KEY)),this.env); } private connections() { return new ConnectionRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } private flyConnections() { return new FlyConnectionRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } private skills() { return new SkillRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY, undefined, new SkillContent(this.env.SKILL_ARTIFACTS,new PostgresSkillContentCache(databaseFor(this.env),this.auth.tenantId,this.env.CREDENTIAL_ENCRYPTION_KEY))); } @@ -362,7 +367,7 @@ export class ApiService { catch (e) { if (e instanceof SkillConflict) throw new ServiceError(409,"skill_conflict",e.message); throw e; } } async syncSkillLibrary() { await this.authorize("skills:write"); const library=this.library(); await library.sync(); return library.status(); } - 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 listSkills(query: { q: string; limit: number; cursor?: string }) { await this.authorize("skills:read"); await migratePresetSkills(this.env,this.auth.tenantId); return publicValue(skillPage, await this.skills().list(query.q, query.limit, query.cursor)); } private async pinnedSkills() { if(!this.auth.runId)return []; const row=(await databaseFor(this.env).pool.query(`SELECT j.encrypted_skill_snapshot FROM app.trigger_runs j JOIN app.runs r ON r.tenant_id=j.tenant_id AND r.id=j.id @@ -408,7 +413,7 @@ export class ApiService { if(!skill)throw new SkillContentError("Unknown skill resource."); return {contents:[skillResource(this.auth.tenantId,skill,path)],ttlMs:0,cacheScope:"private" as const}; } - 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 getSkill(id: string) { await this.authorize("skills:read"); await migratePresetSkills(this.env,this.auth.tenantId); const value = await this.skills().get(id); if (!value) throw new ServiceError(404, "not_found", "Skill not found"); return publicValue(skillResponse, value); } async getSkillDirectory(id:string){ await this.authorize("skills:read");const skill=await this.skills().get(id); if(!skill)throw new ServiceError(404,"not_found","Skill not found"); @@ -418,50 +423,36 @@ export class ApiService { } async getSkillSettings(id: string) { await this.authorize("skills:read"); return this.readSkillSettings(id); } private async readSkillSettings(id:string) { - const row=(await databaseFor(this.env).pool.query("SELECT run_defaults,encrypted_prompt,encrypted_script,settings_revision FROM app.skills WHERE tenant_id=$1 AND id=$2",[this.auth.tenantId,id])).rows[0]; - if(!row)throw new ServiceError(404,"not_found","Skill not found"); - const legacyScript=!row.encrypted_script && row.run_defaults.executionType==="code" ? (await databaseFor(this.env).pool.query("SELECT execution_config->>'script' script FROM app.triggers t JOIN app.trigger_skills ts ON ts.tenant_id=t.tenant_id AND ts.trigger_id=t.id WHERE ts.tenant_id=$1 AND ts.skill_id=$2",[this.auth.tenantId,id])).rows[0]?.script : undefined; - return {revision:row.settings_revision,defaults:skillDefaults.parse({...row.run_defaults,prompt:row.encrypted_prompt?await decrypt(row.encrypted_prompt,this.env.CREDENTIAL_ENCRYPTION_KEY):"",...(row.encrypted_script?{script:await decrypt(row.encrypted_script,this.env.CREDENTIAL_ENCRYPTION_KEY)}:legacyScript?{script:legacyScript}:{})})}; + await migratePresetSkills(this.env,this.auth.tenantId); + const skill=await this.skills().get(id);if(!skill)throw new ServiceError(404,"not_found","Skill not found."); + const resolved=await resolveSkillPresets(databaseFor(this.env).pool,this.auth.tenantId,skill.definition,skill.version?.commit); + return {revision:skill.revision,defaults:skillDefaults.parse({...resolved.defaults,executionType:"agent",prompt:"",concurrencyLimit:skill.definition?.factorize.concurrency??0})}; } - async setSkillSettings(id:string,request:unknown) { + + async setSkillSettings(id:string,request:unknown):Promise<{revision:number;defaults:z.infer}> { await this.authorize("skills:write"); await this.authorize("triggers:write"); - const input=skillSettingsInput.parse(request), defaults=input.defaults; - const executionType=defaults.executionType; - if(defaults.executionConfigId && defaults.requiresVm===false)throw new ServiceError(400,"invalid_request","A VM configuration requires a VM."); - if(defaults.allowedTriggerIds?.length){const found=await databaseFor(this.env).pool.query("SELECT id FROM app.triggers WHERE tenant_id=$1 AND id=ANY($2::uuid[])",[this.auth.tenantId,defaults.allowedTriggerIds]);if(found.rowCount!==defaults.allowedTriggerIds.length)throw new ServiceError(400,"invalid_request","Destinations must belong to this team.");} - const config=await this.workspaceConfiguration(defaults.executionConfigId,executionType==="code"||Boolean(defaults.requiresVm),executionType,defaults.tags); - const portable=await this.portableSelections(config,executionType,defaults); - const {prompt,script,...stored}=defaults; - const encryptedPrompt=await encrypt(prompt,this.env.CREDENTIAL_ENCRYPTION_KEY),encryptedScript=script?await encrypt(script,this.env.CREDENTIAL_ENCRYPTION_KEY):null; - const projected={...config,...portable,executionType,...(script?{script}:{}),...(defaults.vmImage?{image:canonicalizeVmImage(defaults.vmImage)}:{})}; - await databaseFor(this.env).transaction(async client=>{ - const updated=await client.query("UPDATE app.skills SET run_defaults=$3,encrypted_prompt=$4,encrypted_script=$5,settings_revision=settings_revision+1,updated_at=now() WHERE tenant_id=$1 AND id=$2 AND settings_revision=$6 RETURNING id",[this.auth.tenantId,id,stored,encryptedPrompt,encryptedScript,input.expectedRevision]); - if(!updated.rowCount)throw new ServiceError(409,"stale_skill","Skill settings changed; reload before saving."); - // Trigger execution columns are a projection for existing schedulers and external clients. - await client.query(`UPDATE app.triggers t SET execution_config=$3,encrypted_prompt=$4,model=$5,effort=$6,tags=$7,run_scopes=$8,concurrency_limit=$9,updated_at=now() - FROM app.trigger_skills ts WHERE ts.tenant_id=t.tenant_id AND ts.trigger_id=t.id AND ts.skill_id=$2 AND t.tenant_id=$1`,[this.auth.tenantId,id,projected,encryptedPrompt,executionType==="code"?"":defaults.model??"",defaults.effort??"",JSON.stringify(defaults.tags??[]),JSON.stringify(defaults.runScopes??DEFAULT_RUN_SCOPES),defaults.concurrencyLimit??1]); - if(defaults.allowedTriggerIds!==undefined){ - const linked=(await client.query("SELECT trigger_id FROM app.trigger_skills WHERE tenant_id=$1 AND skill_id=$2",[this.auth.tenantId,id])).rows; - for(const {trigger_id} of linked){await client.query("DELETE FROM app.manual_invocation_permissions WHERE tenant_id=$1 AND source_trigger_id=$2",[this.auth.tenantId,trigger_id]);for(const destination of defaults.allowedTriggerIds)await client.query("INSERT INTO app.manual_invocation_permissions(tenant_id,source_trigger_id,destination_trigger_id) VALUES($1,$2,$3)",[this.auth.tenantId,trigger_id,destination]);} - } - }); - return {revision:input.expectedRevision+1,defaults}; + throw new ServiceError(410,"settings_retired","Edit SKILL.md metadata and team presets instead of skill execution settings."); } - async createSkill(input: unknown) { await this.authorize("skills:write"); const parsed = skillInput.parse(input); try { return publicValue(skillResponse, await this.library().edit(store => store.create(parsed.key,parsed.body))); } catch (e) { if (e instanceof SkillConflict) throw new ServiceError(409,"skill_conflict",e.message); throw e; } } - async updateSkill(id: string, input: unknown) { await this.authorize("skills:write"); try { const value = await this.library().edit(store => store.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; } } + + private async authorizeDefinitionChange(next:SkillDefinition,previous?:SkillDefinition){ + const baseline=previous?.factorize??{concurrency:0,disabled:false}; + if((["vm-preset","permission-preset","model-preset","concurrency","disabled"] as const).some(field=>JSON.stringify(next.factorize[field])!==JSON.stringify(baseline[field])))await this.authorize("triggers:write"); + } + async createSkill(input: unknown) { await this.authorize("skills:write"); const parsed = skillInput.parse(input); await this.authorizeDefinitionChange(parsed.definition??readSkillDefinition(parsed.body??"",parsed.key)); await migratePresetSkills(this.env,this.auth.tenantId); try { return publicValue(skillResponse, await this.library().edit(store => store.create(parsed.key,parsed.definition ? writeSkillDefinition(parsed.body ?? "",parsed.definition) : parsed.body ?? ""))); } catch (e) { if (e instanceof SkillConflict) throw new ServiceError(409,"skill_conflict",e.message); throw e; } } + async updateSkill(id: string, input: unknown) { await this.authorize("skills:write"); await migratePresetSkills(this.env,this.auth.tenantId); try { const value = await this.library().edit(async store => { const parsed=skillUpdateInput.parse(input); if(parsed.definition){const current=await store.get(id); if(!current)return null; parsed.body=writeSkillDefinition(parsed.body??current.body??"",parsed.definition);} if(parsed.body!==undefined){const current=await store.get(id);if(!current)return null;await this.authorizeDefinitionChange(readSkillDefinition(parsed.body,parsed.key??current.key),current.definition);} return store.update(id,parsed); }); 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.library().edit(store => store.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} Triggers: ${e.triggers.map(trigger => trigger.name).join(", ")}`); if (e instanceof SkillConflict) throw new ServiceError(409, "stale_skill", e.message); throw e; } } async getSkillTrigger(id:string){ await this.authorize("skills:read");await this.authorize("triggers:read"); await this.readSkillSettings(id); const linked=await this.skills().triggers(id); const trigger=linked.length?await this.getTrigger(linked[0].id):null; - return {trigger:trigger?{...trigger,name:trigger.skill?.key??trigger.name}:null}; + return {trigger:trigger?{...trigger,events:trigger.events.filter(event=>event.kind!=="manual"),name:trigger.skill?.key??trigger.name}:null}; } async saveSkillTrigger(id:string,request:unknown){ await this.authorize("skills:write");await this.authorize("triggers:write"); const input=skillTriggerInput.parse(request),settings=await this.readSkillSettings(id),linked=await this.skills().triggers(id); const existing=linked.length?await this.triggers().getTrigger(linked[0].id):null; - const fields={...settings.defaults,name:existing?.name??("trigger-"+crypto.randomUUID()),skillId:id,events:input.events,runNameTemplate:existing?.runNameTemplate??""}; + const fields={...settings.defaults,name:existing?.name??("trigger-"+crypto.randomUUID()),skillId:id,events:[...(existing?.events.filter(event=>event.kind==="manual").map(({id,slug,enabled,template})=>({id,slug,enabled,template,kind:"manual" as const,config:{}}))??[{kind:"manual" as const,slug:"manual",enabled:true,config:{}}]),...input.events.filter(event=>event.kind!=="manual")],runNameTemplate:existing?.runNameTemplate??""}; const trigger=existing?await this.updateTrigger(existing.id,{...fields,expectedUpdatedAt:input.expectedUpdatedAt}):await this.createTrigger(fields); if(trigger.enabled!==input.enabled)await this.setTriggerEnabled(trigger.id,input.enabled); return this.getSkillTrigger(id); @@ -647,37 +638,49 @@ export class ApiService { } catch (error) { this.throwFlyAccountError(error); } } async removeFlyConnection() { await this.authorizeOwnerSession("integrations:write"); return { deleted: await this.flyConnections().remove() }; } - private vmPresets() { return new VmPresetRepository(databaseFor(this.env), this.auth.tenantId); } - async listVmPresets() { - await this.authorizeOwnerSession("integrations:read"); - return { presets: await this.vmPresets().list() }; - } - async saveVmPreset(body: unknown, id?: string) { - await this.authorizeOwnerSession("integrations:write"); - const input = vmPresetInput.parse(body); - const settings = input.settings; - if (settings.provider === "fly") { - if (!await this.flyConnections().get()) throw new ServiceError(409, "fly_connection_required", "Connect Fly.io before saving this preset."); - await this.validateFlySize(settings); - } else { - const status = await this.integrations().status(); - const connection = status.exeConnections.find(item => item.connectionId === settings.connectionId); - if (!connection || settings.tags.some(tag => !connection.accountTags.includes(tag))) throw new ServiceError(400, "invalid_vm_preset", "Choose an available exe.dev connection and VM tags."); + private presets() { return new PresetRepository(databaseFor(this.env),this.auth.tenantId); } + async listPresets() { await this.authorize("integrations:read"); await migratePresetSkills(this.env,this.auth.tenantId); return {presets:await this.presets().list()}; } + async savePreset(body:unknown,id?:string) { + await this.authorize("integrations:write"); const input=presetInput.parse(body);if(input.kind==="permission")await this.authorize("triggers:write");let configId:string|undefined; + if(input.kind==="vm" && input.settings.provider!=="none"){ + if(input.settings.provider==="exe"){ + const connectionId=input.settings.connectionId; + const connection=(await this.integrations().status()).exeConnections.find(item=>item.connectionId===connectionId); + if(!connection || input.settings.tags.some(tag=>!connection.accountTags.includes(tag)))throw new ServiceError(400,"invalid_preset","Choose an available exe.dev connection and tags."); + configId=input.settings.connectionId; + } else { + if(!await this.flyConnections().get())throw new ServiceError(409,"fly_connection_required","Connect Fly.io first."); + await this.validateFlySize(input.settings); + const configuration=await this.flyExecutionConfigs().save({name:crypto.randomUUID(),image:input.settings.image,region:input.settings.region,size:input.settings.size}); + configId=configuration.id; + } } - try { - const preset = await this.vmPresets().save(input, id); - if (!preset) throw new ServiceError(404, "not_found", "VM preset not found."); - return { preset }; - } catch (error) { - if ((error as {constraint?: string}).constraint === "vm_presets_name") throw new ServiceError(409, "duplicate_name", "A VM preset already uses this name."); - throw error; + if(input.kind==="permission"||input.kind==="model"){ + const settings=input.settings; + await this.portableSelections({connectionId:""},"agent",settings); + if(input.kind==="permission" && input.settings.allowedTriggerIds?.length){const found=await databaseFor(this.env).pool.query("SELECT id FROM app.triggers WHERE tenant_id=$1 AND id=ANY($2::uuid[])",[this.auth.tenantId,input.settings.allowedTriggerIds]);if(found.rowCount!==input.settings.allowedTriggerIds.length)throw new ServiceError(400,"invalid_preset","Invocation destinations must belong to this team.");} } + return {preset:await this.presets().save(input,id,configId)}; } - async removeVmPreset(id: string) { - await this.authorizeOwnerSession("integrations:write"); - if (!await this.vmPresets().remove(id)) throw new ServiceError(404, "not_found", "VM preset not found."); - return { deleted: true }; - } + async defaultPreset(id:string){await this.authorize("team:write");return {preset:await this.presets().makeDefault(id)};} + async deletePreset(id:string){await this.authorize("integrations:write");return this.presets().remove(id);} + private vmPresets() { return new VmPresetRepository(databaseFor(this.env), this.auth.tenantId); } + async listVmPresets() { + await this.authorizeOwnerSession("integrations:read"); + const presets=(await this.listPresets()).presets.filter(p=>p.kind==="vm"&&p.settings.provider!=="none"); + return {presets:presets.map(p=>({id:p.id,name:p.name,settings:p.settings,executionConfigId:p.executionConfigId??""}))}; + } + async saveVmPreset(body:unknown,id?:string){ + await this.authorizeOwnerSession("integrations:write");const input=vmPresetInput.parse(body); + await migratePresetSkills(this.env,this.auth.tenantId); + const all=(await this.presets().list()).filter(p=>p.kind==="vm"); + if(all.some(p=>p.id!==id&&p.name.toLowerCase()===input.name.toLowerCase()))throw new ServiceError(409,"duplicate_name","A VM preset already uses this name."); + const current=id?all.find(p=>p.id===id):undefined;if(id&&!current)throw new ServiceError(404,"not_found","VM preset not found."); + const slug=current?.slug??(input.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"vm"); + const {preset}=await this.savePreset({kind:"vm",slug,name:input.name,settings:input.settings},id); + return {preset:{id:preset.id,name:preset.name,settings:preset.settings,executionConfigId:preset.executionConfigId??""}}; + } + async removeVmPreset(id:string){await this.authorizeOwnerSession("integrations:write");return this.deletePreset(id);} private async validateFlySize(settings: {region: string; size: string}) { const metadata = await this.flyMetadata(); if (!metadata.regions.includes(settings.region) || !metadata.sizes.includes(settings.size)) throw new ServiceError(400, "invalid_fly_configuration", "The selected Fly region or VM size is unavailable."); @@ -707,7 +710,7 @@ export class ApiService { })); return publicValue(runPageResponse,JSON.parse(JSON.stringify({...page,items}))); } - async search(query: string) { await this.authorize("triggers:read"); await this.authorize("runs:read"); return publicValue(searchResponse, await new OperationsRepository(databaseFor(this.env), this.auth.tenantId).search(query)); } + async search(query: string) { await this.authorize("skills:read"); await this.authorize("runs:read"); return publicValue(searchResponse, await new OperationsRepository(databaseFor(this.env), this.auth.tenantId).search(query)); } async eventContextMetadata() { await this.authorize("triggers:read"); return eventContextCatalog; } async getRunStatus(runId: string) { await this.authorize("runs:read"); const status = await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).status(runId); if (!status) throw new ServiceError(404, "not_found", "Run not found"); return status; } async reportRunError(runId: string, input: unknown) { @@ -960,6 +963,8 @@ export class ApiService { async getWebhookDelivery(deliveryId: string) { await this.authorize("runs:read"); const value = await new OperationsRepository(databaseFor(this.env), this.auth.tenantId).delivery(deliveryId); if (!value) throw new ServiceError(404,"not_found","Webhook delivery not found"); return value; } async testTriggerConditions(input: unknown) { await this.authorize("triggers:write"); const parsed = triggerConditionsTestSchema.parse(input); return evaluateWebhookConditions(parsed.conditions, parsed.webhook); } async createTrigger(request: TriggerInput) { + if(request.executionType==="code"||Boolean(request.script?.trim()))throw new ServiceError(400,"scripts_retired","Script-based runs are retired. Use an agent skill to execute code."); + request={...request,script:undefined}; await this.authorize("triggers:write"); const team = await new TeamRepository(databaseFor(this.env), this.auth.tenantId).get(); if (!team) throw new ServiceError(404, "not_found", "Team not found"); @@ -973,7 +978,7 @@ export class ApiService { ...Object.fromEntries(Object.entries(request).filter(([, value]) => value !== undefined)) as TriggerInput, executionConfigId, concurrencyLimit: request.concurrencyLimit ?? defaults.concurrencyLimit ?? 1, - modelAccountId: request.executionType === "code" ? undefined : request.modelAccountId ?? defaults.modelAccountId, + modelAccountId: request.modelAccountId ?? defaults.modelAccountId, }; const timestamp = new Date().toISOString(), id = crypto.randomUUID(); @@ -1024,6 +1029,8 @@ export class ApiService { } } async updateTrigger(triggerId: string, request: TriggerInput & { expectedUpdatedAt?: string }) { + if(request.executionType==="code"||Boolean(request.script?.trim()))throw new ServiceError(400,"scripts_retired","Script-based runs are retired. Use an agent skill to execute code."); + request={...request,script:undefined}; await this.authorize("triggers:write"); const repository = this.triggers(), current = await repository.getTrigger(triggerId); @@ -1144,7 +1151,9 @@ export class ApiService { await this.authorize("team:read"); const team = await new TeamRepository(databaseFor(this.env), this.auth.tenantId).get(); if (!team) throw new ServiceError(404, "not_found", "Team not found"); - return team; + await migratePresetSkills(this.env,this.auth.tenantId); + const presets=await this.presets().list(); + return {...team,presetDefaults:Object.fromEntries(["vm","permission","model"].map(kind=>[kind,presets.find(p=>p.kind===kind&&p.isDefault)?.slug??null]))}; } async setTeamRunDefaults(input: z.infer) { @@ -1159,9 +1168,30 @@ export class ApiService { await this.validateSelectedCredentials(input); } if (!input.executionConfigId) await this.validateSelectedCredentials(input); + const previous=await new TeamRepository(databaseFor(this.env),this.auth.tenantId).get(); const saved = await new TeamRepository(databaseFor(this.env), this.auth.tenantId).setRunDefaults(input); if (!saved) throw new ServiceError(404, "not_found", "Team not found"); - return {...INITIAL_TEAM_DEFAULTS,...input}; + const merged={...INITIAL_TEAM_DEFAULTS,...input}; + await migratePresetSkills(this.env,this.auth.tenantId); + // Compatibility writes update the referenced team defaults. Capacity-only + // writes leave presets alone; old clients never save ignored settings. + const presets=await this.presets().list(); + for(const kind of ["vm","permission","model"] as const){ + const keys=kind==="vm"?["requiresVm","executionConfigId","vmImage","tags"]:kind==="model"?["modelAccountId","model","effort"]:["runScopes","portableIntegrationIds","githubInstallationIds","linearConnectionId","xConnectionIds","allowedTriggerIds"]; + if(!keys.some(key=>JSON.stringify((previous?.runDefaults as any)?.[key])!==JSON.stringify((merged as any)[key])))continue; + const current=presets.find(p=>p.kind===kind&&p.isDefault);if(!current)continue; + let settings:Record={},configId:string|undefined; + if(kind==="vm"){ + if(!merged.requiresVm)settings={provider:"none"}; + else { + const config=merged.executionConfigId?await this.flyExecutionConfigs().get(merged.executionConfigId):null; + settings=config?{provider:"fly",image:merged.vmImage||config.image,region:config.region,size:config.size}:{provider:"exe",connectionId:merged.executionConfigId??"",image:merged.vmImage??"",tags:merged.tags??[]}; + configId=merged.executionConfigId; + } + }else for(const key of keys)if((merged as any)[key]!==undefined)settings[key]=(merged as any)[key]; + await this.presets().save(presetInput.parse({kind,name:current.name,slug:current.slug,settings,expectedRevision:current.revision}),current.id,configId); + } + return merged; } private async resolveRunDefaults(input: z.infer, executionType: "agent" | "code" = "agent") { @@ -1181,6 +1211,7 @@ export class ApiService { } async startRun(input: z.infer) { + if(input.script!==undefined)throw new ServiceError(400,"scripts_retired","Script-based runs are retired. Use an agent skill to execute code."); await this.authorize("runs:start"); if(input.script && input.skill)throw new ServiceError(400,"invalid_request","Explicit scripts cannot include an agent skill; select the script skill alone to use its saved script."); const db = databaseFor(this.env), @@ -1226,12 +1257,14 @@ export class ApiService { if (prior) return prior; const team = await new TeamRepository(db, auth.tenantId).get(); if (!team) throw new ServiceError(404, "not_found", "Team not found"); + await migratePresetSkills(this.env,auth.tenantId); const skill = input.skill ? await this.skills().get(input.skill) : null; if(input.skill && !skill)throw new ServiceError(404,"not_found","Launch skill not found"); - const skillSettingsSnapshot = skill ? await this.readSkillSettings(skill.id) : undefined; - const owned = skillSettingsSnapshot?.defaults; - if(owned?.executionType==="code" && input.script===undefined)input={...input,script:owned.script}; - const defaults = owned ? {...owned,capacity:team.runDefaults.capacity} : team.runDefaults; + const currentSkill=skill; + const resolvedPresets=await resolveSkillPresets(db.pool,auth.tenantId,{...(currentSkill?.definition??readSkillDefinition("","run")),factorize:{...(currentSkill?.definition?.factorize??{concurrency:0,disabled:false}),...(input.vmPreset?{"vm-preset":input.vmPreset}:{}),...(input.permissionPreset?{"permission-preset":input.permissionPreset}:{}),...(input.modelPreset?{"model-preset":input.modelPreset}:{})}},currentSkill?.version?.commit); + if(currentSkill?.definition?.factorize.disabled)throw new ServiceError(409,"skill_disabled","This skill is disabled."); + const owned=resolvedPresets.defaults; + const defaults={...owned,capacity:team.runDefaults.capacity}; const selectedModelAccountId=input.modelAccountId ?? defaults.modelAccountId; const executionConfigId = input.executionConfigId ?? defaults.executionConfigId; if(input.executionConfigId && input.requiresVm===false)throw new ServiceError(400,"invalid_request","A VM override requires requiresVm=true."); @@ -1283,13 +1316,15 @@ export class ApiService { }, input.script ? "code" : "agent"); const config = { ...resolved, + presetSnapshot:resolvedPresets.snapshot, + skillConcurrencyLimit:skill?.definition?.factorize.concurrency??0, runScopes, - allowedTriggerIds: [] as string[], + allowedTriggerIds: defaults.allowedTriggerIds??[] as string[], ...(inheritConfigured ? {} : {agentIntegrationIds: integrationIds}), inputMediaIds:input.attachments?.map(item=>item.artifactId) ?? [], ...(input.script ? {script: input.script} : {}), }; - const text=[owned?.prompt ?? "",input.prompt ?? "", input.inputs && Object.keys(input.inputs).length ? "Inputs (JSON)\n"+JSON.stringify(input.inputs) : ""].filter(Boolean).join("\n\n"); + const text=[input.prompt ?? "", input.inputs && Object.keys(input.inputs).length ? "Inputs (JSON)\n"+JSON.stringify(input.inputs) : ""].filter(Boolean).join("\n\n"); const prompt = composePrompt(skill && !input.script ? {body:skill.body!} : undefined,text); const encryptedPrompt = await encrypt(prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); const encryptedSkills = skill @@ -1302,7 +1337,8 @@ export class ApiService { : undefined; const result = await db.transaction(async (client) => { const locked = await client.query("SELECT run_defaults IS NOT DISTINCT FROM $2::jsonb matches FROM app.team_settings WHERE tenant_id=$1 FOR UPDATE", [auth.tenantId, team.runDefaults]); - if(skill){const current=(await client.query("SELECT revision,settings_revision FROM app.skills WHERE tenant_id=$1 AND id=$2 FOR SHARE",[auth.tenantId,skill.id])).rows[0];if(!current || current.revision!==skill.revision || current.settings_revision!==skillSettingsSnapshot!.revision)throw new ServiceError(409,"configuration_changed","Skill changed. Retry this request.");} + if(skill){const current=(await client.query("SELECT revision FROM app.skills WHERE tenant_id=$1 AND id=$2 FOR SHARE",[auth.tenantId,skill.id])).rows[0];if(!current || current.revision!==skill.revision)throw new ServiceError(409,"configuration_changed","Skill changed. Retry this request.");} + await assertPresetSnapshot(client,auth.tenantId,resolvedPresets.snapshot); const duplicate = await existing(client); if (duplicate) return duplicate; if (!locked.rows[0]?.matches) @@ -1318,7 +1354,7 @@ export class ApiService { ); if (!active.rowCount) throw new ServiceError(403, "forbidden", "The parent run is no longer active."); const parent=active.rows[0]; - const destinations=parent.trigger_id + const destinations=parent.trigger_id && !parent.execution_config.presetSnapshot ? (await client.query("SELECT destination_trigger_id FROM app.manual_invocation_permissions WHERE tenant_id=$1 AND source_trigger_id=$2 FOR SHARE",[auth.tenantId,parent.trigger_id])).rows.map(row=>row.destination_trigger_id) : parent.execution_config.allowedTriggerIds ?? []; config.allowedTriggerIds=(defaults.allowedTriggerIds ?? []).filter(id=>destinations.includes(id)); @@ -1399,8 +1435,8 @@ export class ApiService { JOIN app.triggers destination ON destination.tenant_id=r.tenant_id AND destination.id=$3 WHERE r.tenant_id=$1 AND r.id=$2 AND r.state IN ('starting','running','blocked') AND ($5::boolean OR EXISTS(SELECT 1 FROM app.vendor_run_identity_bindings b WHERE b.tenant_id=r.tenant_id AND b.run_id=r.id AND b.provider=$4 AND b.revoked_at IS NULL)) - AND ((r.trigger_id IS NULL AND COALESCE(r.execution_config->'allowedTriggerIds','[]'::jsonb) ? $3::text) - OR EXISTS(SELECT 1 FROM app.manual_invocation_permissions p WHERE p.tenant_id=r.tenant_id AND p.source_trigger_id=r.trigger_id AND p.destination_trigger_id=$3))`, [this.auth.tenantId, this.auth.runId, triggerId, this.auth.runIdentityProvider ?? null,this.auth.authMethod==="hosted_pi"]); + AND (COALESCE(r.execution_config->'allowedTriggerIds','[]'::jsonb) ? $3::text + OR (r.execution_config->'presetSnapshot' IS NULL AND r.trigger_id IS NOT NULL AND EXISTS(SELECT 1 FROM app.manual_invocation_permissions p WHERE p.tenant_id=r.tenant_id AND p.source_trigger_id=r.trigger_id AND p.destination_trigger_id=$3)))`, [this.auth.tenantId, this.auth.runId, triggerId, this.auth.runIdentityProvider ?? null,this.auth.authMethod==="hosted_pi"]); if (!permission.rowCount) throw new ServiceError(403, "forbidden", "This run is no longer active or its source trigger is not authorized to invoke the destination."); } const event = trigger.events.find(value => value.kind === "manual" && value.enabled); if (!event) throw new ServiceError(409, "operation_failed", "The manual event is disabled"); @@ -1423,6 +1459,7 @@ export class ApiService { await this.authorize("triggers:write"); // A run with triggers:write still cannot expand its invocation destinations. if (["vendor_identity","hosted_pi"].includes(this.auth.authMethod ?? "")) throw new ServiceError(403, "insufficient_scope", "Run credentials cannot change invocation permissions."); + if((await databaseFor(this.env).pool.query("SELECT 1 FROM app.trigger_skills WHERE tenant_id=$1 AND trigger_id=$2 LIMIT 1",[this.auth.tenantId,sourceTriggerId])).rowCount)throw new ServiceError(410,"permissions_retired","Update the skill permission preset instead of trigger invocation permissions."); const unique = [...new Set(destinationTriggerIds)]; if (unique.length !== destinationTriggerIds.length) throw new ServiceError(400, "invalid_request", "Destination triggers must be unique."); const db = databaseFor(this.env); diff --git a/packages/api/src/job-domain.ts b/packages/api/src/job-domain.ts index 669fd3d9..f95c0fd4 100644 --- a/packages/api/src/job-domain.ts +++ b/packages/api/src/job-domain.ts @@ -1,3 +1,4 @@ +import { readSkillDefinition } from "./skill-definition"; import {runPromptPreview} from "./run-prompt"; import Mustache from "mustache"; import { renderTextTemplate } from "./text-template"; @@ -7,6 +8,9 @@ export type InvocationSource = "manual" | EventKind; export type TriggerRunState = "queued" | "reserved" | "running" | "succeeded" | "failed" | "stopped"; export interface ExecutionConfig { + presetSnapshot?:import("./preset-resolution").PresetSnapshot; + skillConcurrencyLimit?:number; + skillDisabled?:boolean; executionType?: "agent" | "code"; requiresVm?:boolean; skillId?: string; @@ -100,6 +104,7 @@ export interface Invocation { } export interface TriggerRun { + executionConfig?:ExecutionConfig & Record; id: string; triggerId: string; invocationId: string; @@ -145,7 +150,7 @@ export function eventRenderingContext(trigger: Pick, context: export function composeTriggerContext(prompt:string, template:string|undefined, eventData:Record, instructions="", skill?:{body:string}) { try { const eventText=template ? renderTextTemplate(template,eventData) : ""; - return {eventText,prompt:[skill?.body ?? "",prompt,eventText,instructions].filter(text=>text.trim()).join("\n\n")}; + return {eventText,prompt:[skill ? readSkillDefinition(skill.body,"skill").markdown : "",prompt,eventText,instructions].filter(text=>text.trim()).join("\n\n")}; } catch { throw new InvocationError("invalid_template","The Event template is not valid Mustache."); } @@ -189,15 +194,17 @@ export class InvocationService { if (existing) return { ...existing, duplicate: true }; if (!input.eventId || !input.context || typeof input.context !== "object" || Array.isArray(input.context)) throw new InvocationError("invalid_invocation", "A event and structured context are required."); + if(trigger.executionType==="code")throw new InvocationError("invalid_invocation","Script-based runs are retired. Use an agent skill."); + if(trigger.executionConfig.skillDisabled)throw new InvocationError("trigger_disabled","This skill is disabled."); const createdAt = this.clock(); const invocation: Invocation = { id: this.makeId(), triggerId, source: input.source, claimKey: input.claimKey, eventId: input.eventId, context: input.context, ...(input.sourceTriggerId ? { sourceTriggerId: input.sourceTriggerId } : {}), ...(input.sourceRunId ? { sourceRunId: input.sourceRunId } : {}), ...(input.occurrence ? { occurrence: input.occurrence } : {}), createdAt }; const selectedSkills = promptSkills(trigger); const event=trigger.events.find(event=>event.id===input.eventId); if (!event || !event.enabled) throw new InvocationError("invalid_invocation","The Event is missing or disabled."); const effectivePrompt=renderTriggerPrompt(trigger,input.context,input.eventId,input.source === "manual" ? undefined : ""); - if (trigger.executionType !== "code" && !trigger.skill && !effectivePrompt.trim()) throw new InvocationError("invalid_invocation","Choose a skill or provide a prompt, Event template, or manual instructions before starting a run."); - const contextPrompt=trigger.executionType==="code"?trigger.script??"":renderTriggerPrompt({...trigger,skill:undefined},input.context,input.eventId,input.source==="manual"?undefined:""); - const run: TriggerRun = { id: this.makeId(), triggerId, invocationId: invocation.id, state: "queued", skill: trigger.skill, encryptedPrompt: await this.encryptPrompt(effectivePrompt),encryptedPromptPreview:await this.encryptPrompt(runPromptPreview(contextPrompt)),encryptedContextPrompt:await this.encryptPrompt(contextPrompt), encryptedSkillSnapshot: selectedSkills.length ? await this.encryptSnapshot(JSON.stringify(selectedSkills.map((skill,order) => ({ id: skill.id, key: skill.key, revision: skill.revision, body: skill.body, version: skill.version, order })))) : undefined, runName: (input.source === "manual" ? input.name?.trim() : undefined) || renderRunName(trigger.runNameTemplate ?? "", eventRenderingContext(trigger,input.context,input.eventId).values, trigger.skill && /^trigger-[a-f0-9-]{36}$/.test(trigger.name) ? trigger.skill.key : trigger.name), createdAt, updatedAt: createdAt }; + if (!trigger.skill && !effectivePrompt.trim()) throw new InvocationError("invalid_invocation","Choose a skill or provide a prompt, Event template, or manual instructions before starting a run."); + const contextPrompt=renderTriggerPrompt({...trigger,skill:undefined},input.context,input.eventId,input.source==="manual"?undefined:""); + const run: TriggerRun = { executionConfig:{...trigger.executionConfig,model:trigger.model,effort:trigger.effort,tags:trigger.tags,runScopes:trigger.runScopes}, id: this.makeId(), triggerId, invocationId: invocation.id, state: "queued", skill: trigger.skill, encryptedPrompt: await this.encryptPrompt(effectivePrompt),encryptedPromptPreview:await this.encryptPrompt(runPromptPreview(contextPrompt)),encryptedContextPrompt:await this.encryptPrompt(contextPrompt), encryptedSkillSnapshot: selectedSkills.length ? await this.encryptSnapshot(JSON.stringify(selectedSkills.map((skill,order) => ({ id: skill.id, key: skill.key, revision: skill.revision, body: skill.body, version: skill.version, order })))) : undefined, runName: (input.source === "manual" ? input.name?.trim() : undefined) || renderRunName(trigger.runNameTemplate ?? "", eventRenderingContext(trigger,input.context,input.eventId).values, trigger.skill && /^trigger-[a-f0-9-]{36}$/.test(trigger.name) ? trigger.skill.key : trigger.name), createdAt, updatedAt: createdAt }; if (!await this.repository.insertInvocationAndRun(invocation, run)) { const winner = await this.repository.findInvocation(triggerId, input.claimKey); if (!winner) throw new Error("Invocation claim was lost without a persisted winner."); @@ -209,7 +216,7 @@ export class InvocationService { async startIfCapacity(run: TriggerRun): Promise { const trigger = await this.repository.getTrigger(run.triggerId); if (!trigger || !trigger.enabled || run.state !== "queued") return null; - if (await this.repository.countActiveRuns(trigger.id) >= trigger.concurrencyLimit) return null; + if (trigger.concurrencyLimit>0 && await this.repository.countActiveRuns(trigger.id) >= trigger.concurrencyLimit) return null; return this.repository.markRunRunning(run.id, this.clock()); } } diff --git a/packages/api/src/mcp-skills.ts b/packages/api/src/mcp-skills.ts index b4f66573..a7912393 100644 --- a/packages/api/src/mcp-skills.ts +++ b/packages/api/src/mcp-skills.ts @@ -18,7 +18,7 @@ export function skillDocument(key:string,body:string|undefined):{frontmatter:Ski frontmatter=value;instructions=body.slice(header[0].length); } // Names are authoritative in the shared Team namespace, including migrated/renamed skills. - frontmatter={...frontmatter,name:key,description:frontmatter.description ?? `Instructions for the ${key} team skill.`}; + frontmatter={...frontmatter,name:key,description:frontmatter.description || `Instructions for the ${key} team skill.`}; if(typeof frontmatter.description!=="string" || !frontmatter.description.trim() || frontmatter.description.length>1024)throw new SkillContentError("Skill description must contain 1 to 1024 characters."); return {frontmatter:frontmatter as SkillFrontmatter,text:`---\n${stringify(frontmatter)}---\n${instructions}`}; } diff --git a/packages/api/src/postgres/automation-scheduler.ts b/packages/api/src/postgres/automation-scheduler.ts index f44a44c8..c64f79fd 100644 --- a/packages/api/src/postgres/automation-scheduler.ts +++ b/packages/api/src/postgres/automation-scheduler.ts @@ -11,7 +11,7 @@ import { adaptWebhook, type WebhookEventConfig } from "../webhook-trigger"; import { evaluateWebhookConditions } from "../webhook-conditions"; function skipFullQueue(error: unknown): void { - if (!(error instanceof InvocationError) || error.code !== "queue_full") throw error; + if (!(error instanceof InvocationError) || !["queue_full","trigger_disabled"].includes(error.code)) throw error; } const DEFAULT_LIFECYCLE_BATCH_SIZE = 100; @@ -22,7 +22,7 @@ export class AutomationScheduler { if (!Number.isSafeInteger(lifecycleBatchSize) || lifecycleBatchSize < 1) throw new RangeError("Lifecycle batch size must be a positive integer"); } async process(): Promise { await this.githubVerifications(); await this.schedules(); await this.triggerEdits(); await this.lifecycle(); await this.triggerIdle(); } - private repository(tenantId: string) { return new PostgresTriggerRepository(this.database, tenantId, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), value => decrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), new SkillContent(this.env.SKILL_ARTIFACTS,new PostgresSkillContentCache(this.database,tenantId,this.env.CREDENTIAL_ENCRYPTION_KEY))); } + private repository(tenantId: string) { return new PostgresTriggerRepository(this.database, tenantId, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), value => decrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), new SkillContent(this.env.SKILL_ARTIFACTS,new PostgresSkillContentCache(this.database,tenantId,this.env.CREDENTIAL_ENCRYPTION_KEY)),this.env); } private async schedules() { for (let count = 0; count < 50; count++) { const due = await this.database.transaction(async client => { @@ -53,7 +53,7 @@ export class AutomationScheduler { await new InvocationService(this.repository(row.tenant_id), value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)).invoke(row.trigger_id, { source: "triggerLifecycle", eventId: row.event_id, claimKey: `trigger-edited:${row.event_id}:${row.delivery_id}`, context: { [row.slug]: context }, occurrence: { occurredAt: context.edited_at, externalId: row.delivery_id, metadata: context }, - }); + }).catch(skipFullQueue); await this.database.pool.query("DELETE FROM app.trigger_edit_deliveries WHERE tenant_id=$1 AND delivery_id=$2 AND event_id=$3", [row.tenant_id, row.delivery_id, row.event_id]); } } @@ -162,6 +162,7 @@ export class AutomationScheduler { const result = await new InvocationService(this.repository(row.tenant_id), value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)).invoke(row.trigger_id, { source: "webhook", eventId: row.event_id, claimKey: `webhook:${row.event_id}:${invocation.claimKey}`, context: { [row.event_slug]: context }, occurrence: { ...invocation.occurrence, metadata: { ...invocation.occurrence.metadata, eventId: row.event_id, mergeable: false } } }); await finish(result.duplicate ? "duplicate" : "accepted", result.duplicate ? "Verified occurrence was already claimed." : "Merge-conflicted pull request queued through canonical trigger invocation."); } catch (error) { + if(error instanceof InvocationError && error.code==="trigger_disabled"){await finish("ignored","Skill is disabled; occurrence skipped.");continue;} if (error instanceof InvocationError && error.code === "queue_full") { await finish("queue_full", "Trigger has no free execution slot and already has a waiting run; occurrence skipped."); continue; } const attempt = Number(row.attempt) + 1, detail = error instanceof Error ? error.message : "GitHub verification failed"; if (attempt >= 8) await finish("verification_failed", detail); else await this.database.pool.query("UPDATE app.pending_verifications SET attempt=$3,next_attempt_at=now()+make_interval(secs=>least(60,5*$3)) WHERE tenant_id=$1 AND id=$2", [row.tenant_id, row.id, attempt]); diff --git a/packages/api/src/postgres/job-repository.ts b/packages/api/src/postgres/job-repository.ts index 543dd125..f9296efd 100644 --- a/packages/api/src/postgres/job-repository.ts +++ b/packages/api/src/postgres/job-repository.ts @@ -1,3 +1,7 @@ +import type { Env } from "../types"; +import { migratePresetSkills } from "../preset-migration"; +import { readSkillDefinition } from "../skill-definition"; +import { resolveSkillPresets, presetExecution, assertPresetSnapshot } from "../preset-resolution"; import { SkillContent } from "../skill-content"; import { DEFAULT_RUN_SCOPES } from "../run-scopes"; import { submitRun } from "./run-submission"; @@ -16,7 +20,8 @@ type TriggerRow = typeof triggers.$inferSelect; type EventRow = typeof events.$inferSelect; export class PostgresTriggerRepository implements TriggerRepository { - constructor(private database: Database, private tenantId: string, private encrypt: Crypt, private decrypt: Crypt, private content = new SkillContent()) { + private readiness?:Promise; + constructor(private database: Database, private tenantId: string, private encrypt: Crypt, private decrypt: Crypt, private content = new SkillContent(),private env?:Env) { if (!tenantId) throw new Error("tenantId is required"); } @@ -50,11 +55,19 @@ export class PostgresTriggerRepository implements TriggerRepository { const skills = await Promise.all(skillRows.map(async skill => ({ id:skill.id, key:skill.key, revision:skill.revision, position:skill.position, ...await this.content.read(skill, this.decrypt), }))); - const skill = skills[0]; // The unique relational selection is authoritative. + const skill = skills[0]; + if(skill && (await this.database.pool.query("SELECT 1 FROM app.presets WHERE tenant_id=$1 AND is_default LIMIT 1",[this.tenantId])).rowCount){ + const definition=readSkillDefinition(skill.body,skill.key); + const resolved=await resolveSkillPresets(this.database.pool,this.tenantId,definition,skill.version?.commit); + const projected=presetExecution(resolved); + Object.assign(row,{executionConfig:{...projected,skillId:skill.id},model:resolved.defaults.model??"",effort:resolved.defaults.effort??"",tags:resolved.defaults.tags??[],runScopes:resolved.defaults.runScopes??[],concurrencyLimit:definition.factorize.concurrency}); + } + // // The unique relational selection is authoritative. return { id: row.id, requiresVm:row.executionConfig.requiresVm ?? (row.executionConfig.executionType==="code" || Boolean(row.executionConfig.connectionId)), runScopes: row.runScopes ?? [...DEFAULT_RUN_SCOPES], name: row.name, description: row.description ?? "", slug: row.slug, prompt: row.encryptedPrompt ? await this.decrypt(row.encryptedPrompt) : "", executionType: row.executionConfig.executionType ?? "agent", script: row.executionConfig.script, runNameTemplate: row.encryptedRunNameTemplate ? await (row.contextVersion<2 ? this.decryptTemplate(row.encryptedRunNameTemplate,eventRows) : this.decrypt(row.encryptedRunNameTemplate)) : "", tags: row.tags ?? [], model: row.model, ...(row.effort ? { effort: row.effort } : {}), executionConfig: row.executionConfig, portableIntegrationIds: row.executionConfig.portableIntegrationIds ?? [], modelAccess: row.executionConfig.modelAccess ?? "native", modelAccountId: row.executionConfig.modelAccountId, githubInstallationIds: row.executionConfig.githubInstallationIds ?? [], linearConnectionId: row.executionConfig.linearConnectionId, xConnectionIds: row.executionConfig.xConnectionIds ?? [], concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, events: await Promise.all(eventRows.map(value => this.event(value,eventRows))), skill, contextReviewRequired:row.contextReviewRequired, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; } async getTrigger(id: string): Promise { + if(this.env)await (this.readiness??=migratePresetSkills({...this.env,DATABASE:this.database},this.tenantId)); const row = (await this.database.orm.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.id, id))).limit(1))[0]; return row ? this.mapped(row) : null; } @@ -180,6 +193,8 @@ export class PostgresTriggerRepository implements TriggerRepository { } async insertInvocationAndRun(invocation: Invocation, run: TriggerRun): Promise { return this.database.transaction(async client => { + if(run.executionConfig?.presetSnapshot)await assertPresetSnapshot(client,this.tenantId,run.executionConfig.presetSnapshot); + if(run.skill){const row=(await client.query("SELECT revision,definition FROM app.skills WHERE tenant_id=$1 AND id=$2 FOR SHARE",[this.tenantId,run.skill.id])).rows[0];if(!row||row.revision!==run.skill.revision||row.definition?.factorize?.disabled)throw new Error("Skill changed or is disabled; retry invocation.");} const concurrencyLimit = await lockTriggerQueue(client, this.tenantId, invocation.triggerId); const inserted = await client.query("INSERT INTO app.invocations(tenant_id,id,trigger_id,source,claim_key,event_id,context,occurrence,source_trigger_id,source_run_id,created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) ON CONFLICT (tenant_id,trigger_id,claim_key) DO NOTHING", [this.tenantId, invocation.id, invocation.triggerId, invocation.source, invocation.claimKey, invocation.eventId, invocation.context, invocation.occurrence ?? null, invocation.sourceTriggerId ?? null, invocation.sourceRunId ?? null, invocation.createdAt]); if (!inserted.rowCount) return false; @@ -187,8 +202,8 @@ export class PostgresTriggerRepository implements TriggerRepository { run.state = await submitRun(client, this.tenantId, { id: run.id, triggerId: invocation.triggerId, invocationId: invocation.id, name: run.runName ?? "", source: invocation.source, claim: invocation.claimKey, encryptedPrompt: run.encryptedPrompt, encryptedSkills: run.encryptedSkillSnapshot,encryptedPromptPreview:run.encryptedPromptPreview,encryptedContextPrompt:run.encryptedContextPrompt, - skill: run.skill, workspaceName: trigger.slug, triggerLimit: concurrencyLimit, createdAt: run.createdAt, - config: {...trigger.execution_config, model: trigger.model, effort: trigger.effort, tags: trigger.tags, inputContext: invocation.context, runScopes: trigger.run_scopes}, + skill: run.skill, workspaceName: trigger.slug, triggerLimit: run.executionConfig?.presetSnapshot?0:concurrencyLimit, createdAt: run.createdAt, + config: {...(run.executionConfig??{...trigger.execution_config,model:trigger.model,effort:trigger.effort,tags:trigger.tags,runScopes:trigger.run_scopes}),inputContext:invocation.context}, }); return true; }); diff --git a/packages/api/src/postgres/operations-repository.ts b/packages/api/src/postgres/operations-repository.ts index c6a76dc1..e8367ef5 100644 --- a/packages/api/src/postgres/operations-repository.ts +++ b/packages/api/src/postgres/operations-repository.ts @@ -1,26 +1,6 @@ import type { Database } from "./database"; import { rankField, searchMatches } from "../search"; -const HIGHLIGHT_START = "<<>>"; -const HIGHLIGHT_END = "<<>>"; - -function markedMatch(value: string, fallback: string, query: string) { - const text = value || fallback, ranges: { start: number; end: number }[] = []; - let output = "", cursor = 0, start = text.indexOf(HIGHLIGHT_START); - while (start >= 0) { - const end = text.indexOf(HIGHLIGHT_END, start + HIGHLIGHT_START.length); - if (end < 0) break; - output += text.slice(cursor, start); - const matchStart = output.length; - output += text.slice(start + HIGHLIGHT_START.length, end); - ranges.push({ start: matchStart, end: output.length }); - cursor = end + HIGHLIGHT_END.length; - start = text.indexOf(HIGHLIGHT_START, cursor); - } - output += text.slice(cursor); - return { text: output || fallback, ranges: ranges.length ? ranges : searchMatches(output || fallback, query) }; -} - export class OperationsRepository { constructor(private database: Database, private tenantId: string) {} async triggerEvents(triggerId: string, limit: number) { return (await this.database.pool.query(`SELECT id,provider,delivery_id "deliveryId",outcome,detail,received_at "receivedAt" FROM app.trigger_events WHERE tenant_id=$1 AND trigger_id=$2 ORDER BY received_at DESC,id DESC LIMIT $3`, [this.tenantId, triggerId, limit])).rows; } @@ -40,33 +20,17 @@ export class OperationsRepository { async search(query: string) { const needle = query.trim(); if (!needle || !/[\p{L}\p{N}]/u.test(needle)) return { items: [] }; const rows = await this.database.pool.query(`SELECT * FROM ( - SELECT 'trigger' kind,j.id::text id,j.name title,j.slug subtitle,'/triggers/'||j.id url,j.id::text source_id,j.name source_label, - CASE WHEN word_similarity($2,j.name) >= word_similarity($2,j.slug) THEN j.name ELSE j.slug END match_text, - GREATEST(word_similarity($2,j.name),word_similarity($2,j.slug)) score, - CASE WHEN lower(j.name)=$2 OR lower(j.slug)=$2 THEN 1 ELSE 2 END category,j.id::text stable_key,NULL match_excerpt - FROM app.triggers j WHERE j.tenant_id=$1 AND ($2 <% j.name OR $2 <% j.slug) - UNION ALL - SELECT 'run',r.id::text,coalesce(nullif(r.run_name,''),nullif(r.issue_title,''),'Run '||left(r.id::text,8)),r.state,'/runs/'||r.id,r.id::text, - coalesce(nullif(r.run_name,''),nullif(r.issue_title,''),'Run '||left(r.id::text,8)), - CASE WHEN r.issue_id % $2 THEN r.issue_id - WHEN word_similarity($2,r.run_name) >= word_similarity($2,r.issue_title) THEN coalesce(nullif(r.run_name,''),r.issue_id) - ELSE coalesce(nullif(r.issue_title,''),r.issue_id) END match_text, - GREATEST(similarity(r.issue_id,$2),word_similarity($2,r.run_name),word_similarity($2,r.issue_title)) score, - CASE WHEN lower(r.issue_id)=$2 THEN 0 WHEN lower(r.run_name)=$2 OR lower(r.issue_title)=$2 THEN 1 ELSE 2 END category,r.id::text stable_key,NULL match_excerpt - FROM app.runs r WHERE r.tenant_id=$1 AND (r.issue_id % $2 OR $2 <% r.run_name OR $2 <% r.issue_title) + SELECT 'skill' kind,s.id::text id,s.key title,'' subtitle,'/skills/'||s.id url,s.id::text source_id,s.key source_label,s.key match_text, + GREATEST(word_similarity($2,s.key),similarity($2,s.key)) score,CASE WHEN lower(s.key)=$2 THEN 0 WHEN starts_with(lower(s.key),$2) THEN 1 ELSE 2 END category,s.id::text stable_key + FROM app.skills s WHERE s.tenant_id=$1 AND (strpos(lower(s.key),$2)>0 OR $2 <% s.key OR similarity($2,s.key)>0.3 OR strpos(regexp_replace(lower(s.key),'[^[:alnum:]]','','g'),regexp_replace($2,'[^[:alnum:]]','','g'))>0) UNION ALL - SELECT 'trace',e.id,e.title,left(e.preview_text,120),'/runs/'||e.run_id,e.run_id::text, - coalesce(nullif(r.run_name,''),nullif(r.issue_title,''),'Run '||left(r.id::text,8)),e.title, - ts_rank(e.search_vector,websearch_to_tsquery('english',$2)),2,e.run_id::text||':'||e.sequence, - ts_headline('english',e.title||' '||e.preview_text,websearch_to_tsquery('english',$2), - 'StartSel=<<>>,StopSel=<<>>,MaxFragments=1,MaxWords=32,MinWords=8') - FROM app.run_trace_events e JOIN app.runs r ON r.tenant_id=e.tenant_id AND r.id=e.run_id - WHERE e.tenant_id=$1 AND e.search_vector @@ websearch_to_tsquery('english',$2) + SELECT 'run',r.id::text,r.run_name,r.state,'/runs/'||r.id,r.id::text,r.run_name,r.run_name, + GREATEST(word_similarity($2,r.run_name),similarity($2,r.run_name)),CASE WHEN lower(r.run_name)=$2 THEN 0 WHEN starts_with(lower(r.run_name),$2) THEN 1 ELSE 2 END,r.id::text + FROM app.runs r WHERE r.tenant_id=$1 AND (strpos(lower(r.run_name),$2)>0 OR $2 <% r.run_name OR similarity($2,r.run_name)>0.3 OR strpos(regexp_replace(lower(r.run_name),'[^[:alnum:]]','','g'),regexp_replace($2,'[^[:alnum:]]','','g'))>0) ) found ORDER BY category,score DESC,kind,stable_key LIMIT 100`, [this.tenantId, needle.toLowerCase()]); return { items: rows.rows.map(row => { - const ranked = row.kind === "trace" ? null : rankField(row.match_text, needle, row.kind === "trigger" ? "trigger" : "run"); - const match = row.kind === "trace" ? markedMatch(row.match_excerpt, row.title, needle) : { text: row.match_text, ranges: ranked?.range ? [ranked.range] : searchMatches(row.match_text, needle) }; - return { kind: row.kind, id: row.id, title: row.title, subtitle: row.subtitle, url: row.url, source: { kind: row.kind, label: row.source_label, id: row.source_id }, match }; + const ranked=rankField(row.match_text,needle,row.kind); + return {kind:row.kind,id:row.id,title:row.title,subtitle:row.subtitle,url:row.url,source:{kind:row.kind,label:row.source_label,id:row.source_id},match:{text:row.match_text,ranges:ranked?.range?[ranked.range]:searchMatches(row.match_text,needle)}}; }) }; } } diff --git a/packages/api/src/postgres/preset-repository.ts b/packages/api/src/postgres/preset-repository.ts new file mode 100644 index 00000000..f4ee8a97 --- /dev/null +++ b/packages/api/src/postgres/preset-repository.ts @@ -0,0 +1,34 @@ +import type { Database, DatabaseClient } from "./database"; +import { presetResponse, type PresetInput, type Preset, type PresetKind } from "../presets"; + +const columns='id,kind,slug,name,revision,settings,is_default AS "isDefault",settings->>\'executionConfigId\' AS "executionConfigId"'; +export class PresetError extends Error { constructor(public status:number,public code:string,message:string){super(message);} } +export class PresetRepository { + constructor(private db:Database,private tenant:string){} + async list(client:Pick=this.db.pool as Pick):Promise{return (await client.query(`SELECT ${columns} FROM app.presets WHERE tenant_id=$1 AND NOT deleted ORDER BY kind,lower(name),slug`,[this.tenant])).rows.map(this.map);} + private map(row:any):Preset { const {executionConfigId,...settings}=row.settings;return presetResponse.parse({...row,settings,executionConfigId:executionConfigId??null}); } + async save(input:PresetInput,id?:string,configId?:string){ + try{return await this.db.transaction(async client=>{ + await this.lock(client); + const old=id?(await client.query("SELECT * FROM app.presets WHERE tenant_id=$1 AND id=$2 AND NOT deleted FOR UPDATE",[this.tenant,id])).rows[0]:undefined; + if(id&&!old)throw new PresetError(404,"not_found","Preset not found."); + if(old&&(old.slug!==input.slug||old.kind!==input.kind))throw new PresetError(400,"immutable_slug","Preset slugs and types cannot change."); + if(old&&input.expectedRevision!==undefined&&old.revision!==input.expectedRevision)throw new PresetError(409,"stale_preset","Preset changed; reload before saving."); + const settings={...input.settings,...(configId?{executionConfigId:configId}:{})}; + const presetId=id??crypto.randomUUID(); + if(old)await client.query("UPDATE app.presets SET name=$3,settings=$4,revision=revision+1 WHERE tenant_id=$1 AND id=$2",[this.tenant,presetId,input.name,settings]); + else await client.query("INSERT INTO app.presets(tenant_id,id,kind,slug,name,settings,is_default) VALUES($1,$2,$3,$4,$5,$6,NOT EXISTS(SELECT 1 FROM app.presets WHERE tenant_id=$1 AND kind=$3 AND is_default))",[this.tenant,presetId,input.kind,input.slug,input.name,settings]); + return (await this.list(client)).find(preset=>preset.id===presetId)!; + });}catch(error:any){if(error.code==="23505")throw new PresetError(409,"duplicate_slug","A preset of this type already uses this slug, including retained historical presets.");throw error;} + } + async makeDefault(id:string){return this.db.transaction(async client=>{await this.lock(client);const preset=(await this.list(client)).find(p=>p.id===id);if(!preset)throw new PresetError(404,"not_found","Preset not found.");await client.query("UPDATE app.presets SET is_default=false WHERE tenant_id=$1 AND kind=$2 AND is_default",[this.tenant,preset.kind]);await client.query("UPDATE app.presets SET is_default=true WHERE tenant_id=$1 AND id=$2",[this.tenant,id]);return {...preset,isDefault:true};});} + async remove(id:string){return this.db.transaction(async client=>{ + await this.lock(client);const preset=(await this.list(client)).find(p=>p.id===id);if(!preset)throw new PresetError(404,"not_found","Preset not found."); + if(preset.isDefault)throw new PresetError(409,"default_preset","Choose another team default before deleting this preset."); + if((await client.query("SELECT 1 FROM app.skills WHERE tenant_id=$1 AND (definition IS NULL OR preset_migration_pending) LIMIT 1",[this.tenant])).rowCount)throw new PresetError(409,"migration_pending","Complete the skill preset migration before deleting presets."); + const refs=(await client.query("SELECT key FROM app.skills WHERE tenant_id=$1 AND definition->'factorize'->>$2=$3 ORDER BY key",[this.tenant,`${preset.kind}-preset`,preset.slug])).rows; + if(refs.length)throw new PresetError(409,"preset_referenced",`Used by skills: ${refs.map(row=>row.key).join(", ")}. Change their preset selections before deleting.`); + await client.query("UPDATE app.presets SET deleted=true WHERE tenant_id=$1 AND id=$2",[this.tenant,id]);return {deleted:true}; + });} + private async lock(client:DatabaseClient){await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1,1))",[this.tenant]);} +} diff --git a/packages/api/src/postgres/queue-admission.ts b/packages/api/src/postgres/queue-admission.ts index a06fd851..9728e6d9 100644 --- a/packages/api/src/postgres/queue-admission.ts +++ b/packages/api/src/postgres/queue-admission.ts @@ -9,6 +9,7 @@ export async function lockTriggerQueue(client: DatabaseClient, tenantId: string, /** Check after claiming the occurrence so duplicate retries still return their original run. */ export async function reserveExecutionSlot(client: DatabaseClient, tenantId: string, triggerId: string, run: { state: string }, concurrencyLimit: number, available = Number.POSITIVE_INFINITY): Promise { + if(concurrencyLimit===0)concurrencyLimit=Number.POSITIVE_INFINITY; const activeStates = "('reserved','starting','running','blocked','stopping')"; // A newly free slot belongs to the oldest waiter before it belongs to a new arrival. diff --git a/packages/api/src/postgres/run-repository.ts b/packages/api/src/postgres/run-repository.ts index 4160aaac..cf17e93d 100644 --- a/packages/api/src/postgres/run-repository.ts +++ b/packages/api/src/postgres/run-repository.ts @@ -51,7 +51,9 @@ export class RunRepository { OR r.state='reserved' OR (r.state='queued' AND (p.run_defaults->>'capacity' IS NULL OR (SELECT count(*) FROM app.runs a JOIN app.trigger_runs ar ON ar.tenant_id=a.tenant_id AND ar.id=a.id WHERE a.tenant_id=p.tenant_id AND ar.state IN ('reserved','starting','running','blocked','stopping')) < (p.run_defaults->>'capacity')::int) - AND (r.trigger_id IS NULL OR (SELECT count(*) FROM app.trigger_runs active WHERE active.tenant_id=r.tenant_id AND active.trigger_id=r.trigger_id AND active.state IN ('reserved','starting','running','blocked','stopping')) < j.concurrency_limit)))`; + AND (x.launch_skill_id IS NULL OR coalesce((x.execution_config->>'skillConcurrencyLimit')::int,0)=0 OR + (SELECT count(*) FROM app.runs a WHERE a.tenant_id=x.tenant_id AND a.launch_skill_id=x.launch_skill_id AND a.state IN ('reserved','starting','running','blocked','stopping')) < (x.execution_config->>'skillConcurrencyLimit')::int) + AND (x.execution_config ? 'presetSnapshot' OR r.trigger_id IS NULL OR j.concurrency_limit=0 OR (SELECT count(*) FROM app.trigger_runs active WHERE active.tenant_id=r.tenant_id AND active.trigger_id=r.trigger_id AND active.state IN ('reserved','starting','running','blocked','stopping')) < j.concurrency_limit)))`; const candidate = (await client.query(`SELECT p.tenant_id ${eligible} ORDER BY r.created_at,r.id FOR UPDATE OF p SKIP LOCKED LIMIT 1`)).rows[0]; if (!candidate) return null; diff --git a/packages/api/src/postgres/run-submission.ts b/packages/api/src/postgres/run-submission.ts index d86b3df1..09845147 100644 --- a/packages/api/src/postgres/run-submission.ts +++ b/packages/api/src/postgres/run-submission.ts @@ -28,7 +28,7 @@ export async function submitRun(client: DatabaseClient, tenant: string, run: Sub ).rows[0]; if (!team) throw new Error("Run team is unavailable"); const capacity = team.run_defaults?.capacity; - let available = Number.POSITIVE_INFINITY; + let available = Number.POSITIVE_INFINITY, waiting = 0; if (capacity) { const { rows } = await client.query( `SELECT count(*) FILTER (WHERE jr.state IN ('reserved','starting','running','blocked','stopping'))::int active, @@ -37,9 +37,14 @@ export async function submitRun(client: DatabaseClient, tenant: string, run: Sub [tenant], ); available = Math.max(0, capacity - rows[0].active); - if (!available && rows[0].waiting >= capacity) - throw new InvocationError("queue_full", "The team's run queue is full."); + waiting=rows[0].waiting; } + const skillLimit=Number(run.config.skillConcurrencyLimit??0); + if(run.skill && skillLimit>0){ + const active=(await client.query("SELECT count(*)::int n FROM app.runs WHERE tenant_id=$1 AND launch_skill_id=$2 AND state IN ('reserved','starting','running','blocked','stopping')",[tenant,run.skill.id])).rows[0].n; + if(active>=skillLimit)available=0; + } + if(!available && capacity && waiting>=capacity)throw new InvocationError("queue_full","The team's run queue is full."); const reservation = { state: available ? "reserved" : "queued" }; if (run.triggerId) await reserveExecutionSlot(client, tenant, run.triggerId, reservation, run.triggerLimit ?? 1, available); diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index ccfdae00..ecfdef93 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -110,7 +110,7 @@ export const userRunDefaults = app.table("user_run_defaults", { tenantId: uuid(" export const triggers = app.table("triggers", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), projectId: uuid("project_id"), name: text("name").notNull(), description: text("description").notNull().default(""), slug: text("slug").notNull(), runScopes: jsonb("run_scopes").$type().notNull().default([...DEFAULT_RUN_SCOPES]), encryptedPrompt: text("encrypted_prompt"), contextVersion:integer("context_version").notNull().default(2), contextReviewRequired:boolean("context_review_required").notNull().default(false), 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("triggers_tenant_project_updated").on(t.tenantId, t.projectId, t.updatedAt), check("triggers_concurrency_limit_check", sql`${t.concurrencyLimit} >= 1`)]); +}, 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("triggers_tenant_project_updated").on(t.tenantId, t.projectId, t.updatedAt), check("triggers_concurrency_nonnegative", sql`${t.concurrencyLimit} >= 0`)]); export const vmImageVerifications = app.table("vm_image_verifications", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), triggerId: uuid("trigger_id"), status: text("status").notNull(), phase: text("phase").notNull(), config: jsonb("config").$type>().notNull(), errorKind: text("error_kind"), error: text("error"), vmName: text("vm_name"), createdAt: createdAt(), updatedAt: updatedAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), check("vm_image_verifications_status_check", sql`${t.status} IN ('queued','creating','checking_ssh','checking_agent','cleaning_up','succeeded','failed','cleanup_failed')`), index("vm_image_verifications_status_idx").on(t.status, t.updatedAt), index("vm_image_verifications_retention").on(t.createdAt,t.tenantId,t.id).where(sql`${t.status} IN ('succeeded','failed')`)]); diff --git a/packages/api/src/postgres/skill-repository.ts b/packages/api/src/postgres/skill-repository.ts index 19036276..6c52642c 100644 --- a/packages/api/src/postgres/skill-repository.ts +++ b/packages/api/src/postgres/skill-repository.ts @@ -1,14 +1,17 @@ import { SkillContent, type SkillContentRow } from "../skill-content"; import type { Database, DatabaseClient } from "./database"; +import { readSkillDefinition } from "../skill-definition"; import { decrypt } from "../crypto"; export class SkillConflict extends Error {} export class SkillReferenced extends Error { constructor(public triggers: { id: string; name: string; slug: string; enabled: boolean }[]) { super("Skill is referenced by saved triggers."); } } -type SkillRow = SkillContentRow & { id: string; key: string; revision: number; created_at: Date; updated_at: Date; trigger?:{id:string;enabled:boolean}|null; last_run_state?:string|null }; +type SkillRow = SkillContentRow & { id: string; key: string; revision: number; created_at: Date; updated_at: Date; trigger?:{id:string;enabled:boolean}|null; last_run_state?:string|null;definition?:any;has_triggers?:boolean }; export class SkillRepository { constructor(private db: Database, private tenantId: string, private encryptionKey: string, private client?: DatabaseClient, private content = new SkillContent(), private edits?: Map) {} private get sql() { return this.client ?? this.db.pool; } - private async map(row: SkillRow, usageCount = 0, body = false) { return { id: row.id, key: row.key, revision: row.revision, ...(body ? await this.content.read(row, value => decrypt(value, this.encryptionKey), this.edits?.get(row.id)) : {}), usageCount, ...(row.trigger!==undefined?{trigger:row.trigger,lastRunState:row.last_run_state??null}:{}), createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }; } - async list(q = "", limit = 30, cursor?: string) { const result = await this.sql.query(`SELECT s.id,s.key,s.revision,s.created_at,s.updated_at, count(js.trigger_id)::text usage_count, + private async map(row: SkillRow, usageCount = 0, body = false) { return { id: row.id, key: row.key, revision: row.revision, ...(body ? await this.readDefinition(row) : {body:undefined,version:undefined,definition:undefined,description:row.definition?.description??"",factorize:row.definition?.factorize??{concurrency:0,disabled:false},hasTriggers:row.has_triggers??false}), usageCount, ...(row.trigger!==undefined?{trigger:row.trigger,lastRunState:row.last_run_state??null}:{}), createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }; } + private async readDefinition(row: SkillRow) { const content = await this.content.read(row, value => decrypt(value, this.encryptionKey), this.edits?.get(row.id)); return { ...content, definition: readSkillDefinition(content.body, row.key) }; } + async list(q = "", limit = 30, cursor?: string) { const result = await this.sql.query(`SELECT s.id,s.key,s.revision,s.definition,s.created_at,s.updated_at, count(js.trigger_id)::text usage_count, + EXISTS(SELECT 1 FROM app.trigger_skills ts JOIN app.events e ON e.tenant_id=ts.tenant_id AND e.trigger_id=ts.trigger_id WHERE ts.tenant_id=s.tenant_id AND ts.skill_id=s.id AND e.kind<>'manual' AND e.removed_at IS NULL) has_triggers, (SELECT jsonb_build_object('id',t.id,'enabled',t.enabled) FROM app.trigger_skills ts JOIN app.triggers t ON t.tenant_id=ts.tenant_id AND t.id=ts.trigger_id WHERE ts.tenant_id=s.tenant_id AND ts.skill_id=s.id LIMIT 1) trigger, (SELECT r.state FROM app.runs r WHERE r.tenant_id=s.tenant_id AND (r.launch_skill_id=s.id OR r.trigger_id IN (SELECT trigger_id FROM app.trigger_skills WHERE tenant_id=s.tenant_id AND skill_id=s.id)) ORDER BY r.created_at DESC,r.id DESC LIMIT 1) last_run_state FROM app.skills s LEFT JOIN app.trigger_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.tenant_id, 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) { diff --git a/packages/api/src/postgres/webhook-service.ts b/packages/api/src/postgres/webhook-service.ts index d935a166..dae097bd 100644 --- a/packages/api/src/postgres/webhook-service.ts +++ b/packages/api/src/postgres/webhook-service.ts @@ -16,7 +16,7 @@ export class WebhookService { private triggers: PostgresTriggerRepository; constructor(private database: Database, private env: Env, private tenantId: string) { this.connections = new ConnectionRepository(database, tenantId, env.CREDENTIAL_ENCRYPTION_KEY); - this.triggers = new PostgresTriggerRepository(database, tenantId, value => encrypt(value, env.CREDENTIAL_ENCRYPTION_KEY), value => decrypt(value, env.CREDENTIAL_ENCRYPTION_KEY), new SkillContent(env.SKILL_ARTIFACTS,new PostgresSkillContentCache(database,tenantId,env.CREDENTIAL_ENCRYPTION_KEY))); + this.triggers = new PostgresTriggerRepository(database, tenantId, value => encrypt(value, env.CREDENTIAL_ENCRYPTION_KEY), value => decrypt(value, env.CREDENTIAL_ENCRYPTION_KEY), new SkillContent(env.SKILL_ARTIFACTS,new PostgresSkillContentCache(database,tenantId,env.CREDENTIAL_ENCRYPTION_KEY)),env); } private async candidates(provider: WebhookProvider): Promise> { const rows = await this.database.pool.query(`SELECT j.*,t.id event_id,t.slug event_slug,t.config event_config FROM app.triggers j JOIN app.events t ON t.tenant_id=j.tenant_id AND t.trigger_id=j.id WHERE j.tenant_id=$1 AND j.enabled AND t.enabled AND t.removed_at IS NULL AND t.kind='webhook' AND t.config->>'provider'=$2`, [this.tenantId, provider]); @@ -52,6 +52,7 @@ export class WebhookService { const result = await service.invoke(candidate.trigger.id, { source: "webhook", eventId: candidate.eventId, claimKey: `webhook:${candidate.eventId}:${invocation.claimKey}`, context: { [candidate.eventSlug]: context }, occurrence: { ...invocation.occurrence, metadata: { ...invocation.occurrence?.metadata, eventId: candidate.eventId } } }); await this.event(deliveryPk, candidate.trigger.id, provider, deliveryId, result.duplicate ? "duplicate" : "accepted", result.duplicate ? "Webhook occurrence was already claimed." : "Webhook occurrence queued through canonical trigger invocation."); } catch (error) { + if(error instanceof InvocationError && error.code==="trigger_disabled"){await this.event(deliveryPk,candidate.trigger.id,provider,deliveryId,"ignored","Skill is disabled; occurrence skipped.");continue;} if (!(error instanceof InvocationError) || error.code !== "queue_full") throw error; await this.event(deliveryPk, candidate.trigger.id, provider, deliveryId, "queue_full", "Trigger has no free execution slot and already has a waiting run; occurrence skipped."); } diff --git a/packages/api/src/preset-migration.ts b/packages/api/src/preset-migration.ts new file mode 100644 index 00000000..c001b49a --- /dev/null +++ b/packages/api/src/preset-migration.ts @@ -0,0 +1,95 @@ +import { databaseFor, type DatabaseClient } from "./postgres/database"; +import { SkillLibrary } from "./skill-library"; +import { SkillContent } from "./skill-content"; +import { decrypt, encrypt } from "./crypto"; +import { readSkillDefinition, writeSkillDefinition,skillDefinitionIndex } from "./skill-definition"; +import { markdown, type SkillVersion } from "./skill-files"; +import type { Env } from "./types"; + +/** Restart-safe: preset creation is committed first; the file and its migration + * marker commit together. Git writes use the library's existing recovery gate. */ +export async function migratePresetSkills(env:Env,tenant:string){ + const db=databaseFor(env); + const state=(await db.pool.query(`SELECT + EXISTS(SELECT 1 FROM app.skills WHERE tenant_id=$1 AND (definition IS NULL OR preset_migration_pending)) pending, + (SELECT count(*)::int FROM app.presets WHERE tenant_id=$1 AND is_default) defaults, + EXISTS(SELECT 1 FROM app.vm_presets v WHERE v.tenant_id=$1 AND NOT EXISTS(SELECT 1 FROM app.presets p WHERE p.tenant_id=v.tenant_id AND p.id=v.id)) old_presets, + EXISTS(SELECT 1 FROM app.triggers WHERE tenant_id=$1 AND enabled AND execution_config->>'executionType'='code') scripts`,[tenant])).rows[0]; + if(!state.pending&&state.defaults===3&&!state.old_presets&&!state.scripts)return; + const plans=await db.transaction(async client=>{ + await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1,1))",[tenant]); + await client.query("UPDATE app.triggers SET enabled=false WHERE tenant_id=$1 AND execution_config->>'executionType'='code' AND enabled",[tenant]); + const team=(await client.query("SELECT run_defaults FROM app.team_settings WHERE tenant_id=$1",[tenant])).rows[0]?.run_defaults??{}; + async function selection(raw:Record,teamDefault=false){ + const references:Record={}; + for(const kind of ["vm","permission","model"] as const){ + let settings:Record={}; + if(kind==="vm"){ + if(raw.requiresVm===false||(!raw.requiresVm&&!raw.executionConfigId))settings={provider:"none"}; + else { + const config=raw.executionConfigId?(await client.query("SELECT * FROM app.fly_execution_configurations WHERE tenant_id=$1 AND id::text=$2",[tenant,raw.executionConfigId])).rows[0]:null; + settings=config?{provider:"fly",image:raw.vmImage||config.image,region:config.region,size:config.size,executionConfigId:config.id}:{provider:"exe",connectionId:raw.executionConfigId??"local",executionConfigId:raw.executionConfigId??"local",image:raw.vmImage??"",tags:raw.tags??[]}; + } + }else for(const field of kind==="model"?["modelAccountId","model","effort"]:["runScopes","portableIntegrationIds","githubInstallationIds","linearConnectionId","xConnectionIds","allowedTriggerIds"]){if(raw[field]!==undefined)settings[field]=raw[field];} + const existing=(await client.query("SELECT id,slug FROM app.presets WHERE tenant_id=$1 AND kind=$2 AND settings=$3 AND NOT deleted ORDER BY is_default DESC,slug LIMIT 1",[tenant,kind,settings])).rows[0]; + let preset=existing; + if(!preset){ + const base=teamDefault?"team-default":"migrated";let suffix=1,slug=base; + while((await client.query("SELECT 1 FROM app.presets WHERE tenant_id=$1 AND kind=$2 AND slug=$3",[tenant,kind,slug])).rowCount)slug=`${base}-${++suffix}`; + preset={id:crypto.randomUUID(),slug}; + await client.query("INSERT INTO app.presets(tenant_id,id,kind,slug,name,settings) VALUES($1,$2,$3,$4,$5,$6)",[tenant,preset.id,kind,slug,teamDefault?"Team default":`Migrated ${kind} ${suffix}`,settings]); + } + if(teamDefault)await client.query("UPDATE app.presets SET is_default=true WHERE tenant_id=$1 AND id=$2 AND NOT EXISTS(SELECT 1 FROM app.presets WHERE tenant_id=$1 AND kind=$3 AND is_default)",[tenant,preset.id,kind]); + references[`${kind}-preset`]=preset.slug; + } + return references; + } + const legacyPresets=(await client.query("SELECT * FROM app.vm_presets WHERE tenant_id=$1 ORDER BY name,id",[tenant])).rows; + for(const old of legacyPresets){ + if((await client.query("SELECT 1 FROM app.presets WHERE tenant_id=$1 AND id=$2",[tenant,old.id])).rowCount)continue; + const base=old.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,100)||"vm";let slug=base,n=1; + while((await client.query("SELECT 1 FROM app.presets WHERE tenant_id=$1 AND kind='vm' AND slug=$2",[tenant,slug])).rowCount)slug=`${base}-${++n}`; + await client.query("INSERT INTO app.presets(tenant_id,id,kind,slug,name,settings) VALUES($1,$2,'vm',$3,$4,$5)",[tenant,old.id,slug,old.name,{...old.settings,executionConfigId:old.execution_config_id}]); + } + await selection(team,true); + const rows=(await client.query("SELECT * FROM app.skills WHERE tenant_id=$1 AND (definition IS NULL OR preset_migration_pending) ORDER BY key",[tenant])).rows; + const plans=[]; + const content=new SkillContent(env.SKILL_ARTIFACTS); + for(const row of rows){ + const loaded=await content.read(row,value=>decrypt(value,env.CREDENTIAL_ENCRYPTION_KEY)); + const definition=readSkillDefinition(loaded.body,row.key); + const refs=await selection(row.run_defaults??team); + const prompt=row.encrypted_prompt?await decrypt(row.encrypted_prompt,env.CREDENTIAL_ENCRYPTION_KEY):""; + const isScript=row.run_defaults?.executionType==="code"||Boolean(row.encrypted_script); + let body=writeSkillDefinition(loaded.body,{...definition,markdown:[definition.markdown,prompt].filter(Boolean).join("\n\n"),factorize:{...refs,...definition.factorize,concurrency:row.run_defaults?.concurrencyLimit??0,disabled:definition.factorize.disabled||isScript}}); + const hash=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(loaded.body))),n=>n.toString(16).padStart(2,"0")).join(""); + if(row.encrypted_preset_migration_body){ + const prepared=await decrypt(row.encrypted_preset_migration_body,env.CREDENTIAL_ENCRYPTION_KEY); + if(loaded.body!==prepared&&hash!==row.preset_migration_source_hash)throw new Error("Skill changed during preset migration. Sync and review its content before retrying."); + body=prepared; + } + await client.query("UPDATE app.skills SET preset_migration_pending=true,encrypted_preset_migration_body=COALESCE(encrypted_preset_migration_body,$3),preset_migration_source_hash=COALESCE(preset_migration_source_hash,$4) WHERE tenant_id=$1 AND id=$2",[tenant,row.id,await encrypt(body,env.CREDENTIAL_ENCRYPTION_KEY),hash]); + plans.push({row,loaded,body}); + if(isScript)await client.query("UPDATE app.triggers SET enabled=false WHERE tenant_id=$1 AND id IN(SELECT trigger_id FROM app.trigger_skills WHERE tenant_id=$1 AND skill_id=$2)",[tenant,row.id]); + } + return plans; + }); + if(!plans.length)return; + if(env.SKILL_ARTIFACTS){ + await new SkillLibrary(env,tenant).edit(async store=>{ + for(const plan of plans){const current=await store.get(plan.row.id);if(!current)continue; + if(current.body===plan.body)continue; + if(current.revision!==plan.row.revision)throw new Error("Skill changed during preset migration; retry after refreshing."); + await store.update(plan.row.id,{expectedRevision:current.revision,body:plan.body}); + } + return true; + }); + }else await db.transaction(async client=>{ + await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1,1))",[tenant]); + for(const {row,loaded,body} of plans){ + if(row.artifact_version)throw new Error("Skill Artifacts binding required to migrate published skills."); + const version:SkillVersion|undefined=loaded.version?{...loaded.version,files:loaded.version.files.map(file=>file.path==="SKILL.md"?{...markdown(body),executable:file.executable}:file)}:undefined; + await client.query("UPDATE app.skills SET encrypted_body=$3,encrypted_directory=$4,definition=$5,preset_migration_pending=false,encrypted_preset_migration_body=NULL,preset_migration_source_hash=NULL,revision=revision+1 WHERE tenant_id=$1 AND id=$2 AND (definition IS NULL OR preset_migration_pending) AND revision=$6",[tenant,row.id,await encrypt(body,env.CREDENTIAL_ENCRYPTION_KEY),version?await encrypt(JSON.stringify(version),env.CREDENTIAL_ENCRYPTION_KEY):null,skillDefinitionIndex(readSkillDefinition(body,row.key)),row.revision]); + } + }); +} diff --git a/packages/api/src/preset-resolution.ts b/packages/api/src/preset-resolution.ts new file mode 100644 index 00000000..38138030 --- /dev/null +++ b/packages/api/src/preset-resolution.ts @@ -0,0 +1,37 @@ +import type { DatabaseClient } from "./postgres/database"; +import { PresetError } from "./postgres/preset-repository"; +import { readSkillDefinition, type SkillDefinition } from "./skill-definition"; +import type { teamRunDefaults } from "./flow-schemas"; +import type { z } from "zod"; +export type ResolvedDefaults=z.infer; +export type PresetSnapshot={skillCommit:string|null;presets:Record}>}; +/** Resolve once for admission. The returned settings contain references, never secrets. */ +export async function resolveSkillPresets(client:DatabaseClient,tenant:string,definition?:SkillDefinition,commit?:string){ + const rows=(await client.query("SELECT * FROM app.presets WHERE tenant_id=$1 AND NOT deleted",[tenant])).rows; + const defaults:ResolvedDefaults={}; + const snapshot:PresetSnapshot={skillCommit:commit??null,presets:{}}; + for(const kind of ["vm","permission","model"] as const){ + const slug=definition?.factorize[`${kind}-preset`]; + const preset=rows.find(row=>row.kind===kind&&(slug?row.slug===slug:row.is_default)); + if(!preset)throw new PresetError(409,"preset_unavailable",slug?`The ${kind} preset '${slug}' is unavailable.`:`Select a team default ${kind} preset.`); + const settings=preset.settings; + snapshot.presets[kind]={id:preset.id,slug:preset.slug,revision:preset.revision,inherited:!slug,settings:structuredClone(settings)}; + if(kind==="vm")Object.assign(defaults,settings.provider==="none"?{requiresVm:false}:{requiresVm:true,executionConfigId:settings.executionConfigId??settings.connectionId,vmImage:settings.image,tags:settings.tags??[]}); + else Object.assign(defaults,settings); + } + return {defaults,snapshot,definition}; +} +export function presetExecution(resolved:Awaited>){ + const d=resolved.defaults,vm=resolved.snapshot.presets.vm.settings; + return {agentKind:"pi",executionType:"agent",requiresVm:d.requiresVm??false,connectionId:d.executionConfigId??"",targetId:d.executionConfigId, + workspace:vm.provider==="exe"?"ephemeral":"",cwd:vm.provider==="exe"?"/home/exedev/workspace":"",executionProvider:vm.provider==="none"?undefined:vm.provider, + image:d.vmImage,region:vm.region,size:vm.size,tags:d.tags??[],model:d.model??"",effort:d.effort??"",modelAccountId:d.modelAccountId,modelAccess:"portable", + portableIntegrationIds:d.portableIntegrationIds??[],githubInstallationIds:d.githubInstallationIds??[],linearConnectionId:d.linearConnectionId??undefined,xConnectionIds:d.xConnectionIds??[],runScopes:d.runScopes??[],allowedTriggerIds:d.allowedTriggerIds??[], + presetSnapshot:resolved.snapshot,skillConcurrencyLimit:resolved.definition?.factorize.concurrency??0,skillDisabled:resolved.definition?.factorize.disabled??false}; +} +export async function assertPresetSnapshot(client:DatabaseClient,tenant:string,snapshot:PresetSnapshot){ + for(const [kind,preset] of Object.entries(snapshot.presets)){ + const row=(await client.query("SELECT revision,is_default,deleted FROM app.presets WHERE tenant_id=$1 AND id=$2 FOR SHARE",[tenant,preset.id])).rows[0]; + if(!row||row.deleted||row.revision!==preset.revision||(preset.inherited&&!row.is_default))throw new PresetError(409,"configuration_changed",`${kind} preset changed. Retry this request.`); + } +} diff --git a/packages/api/src/presets.ts b/packages/api/src/presets.ts new file mode 100644 index 00000000..fac80057 --- /dev/null +++ b/packages/api/src/presets.ts @@ -0,0 +1,25 @@ +import { z } from "zod"; +import { presetSlug } from "./skill-definition"; +import { teamRunDefaults } from "./flow-schemas"; +import { vmPresetSettings } from "./vm-presets"; + +export const presetKind = z.enum(["vm", "permission", "model"]); +export type PresetKind = z.infer; +export const permissionPresetSettings = teamRunDefaults.pick({ runScopes:true, portableIntegrationIds:true, githubInstallationIds:true, linearConnectionId:true, xConnectionIds:true, allowedTriggerIds:true }); +export const modelPresetSettings = teamRunDefaults.pick({ modelAccountId:true, model:true, effort:true }); +export const vmSettings = z.union([vmPresetSettings, z.object({provider:z.literal("none")}).strict()]); +const common = {slug:presetSlug,name:z.string().trim().min(1).max(120),expectedRevision:z.number().int().positive().optional()}; +export const presetInput = z.discriminatedUnion("kind",[ + z.object({...common,kind:z.literal("vm"),settings:vmSettings}).strict(), + z.object({...common,kind:z.literal("permission"),settings:permissionPresetSettings}).strict(), + z.object({...common,kind:z.literal("model"),settings:modelPresetSettings}).strict(), +]); +const output={id:z.uuid(),revision:z.number().int().positive(),isDefault:z.boolean(),executionConfigId:z.string().nullable()}; +export const presetResponse=z.discriminatedUnion("kind",[ + presetInput.options[0].omit({expectedRevision:true}).extend(output), + presetInput.options[1].omit({expectedRevision:true}).extend(output), + presetInput.options[2].omit({expectedRevision:true}).extend(output), +]); +export type Preset=z.infer; +export type PresetInput=z.infer; +export const presetList=z.object({presets:z.array(presetResponse)}); diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index e923e5b6..6ba0741b 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -1,3 +1,7 @@ +import { presetInput } from "./presets"; +import { skillTriggerInput } from "./skill-trigger"; +import { skillInput,skillUpdateInput } from "./skills"; +import { PresetError } from "./postgres/preset-repository"; import {createPayloadInput,appendPayloadInput,finalizePayloadInput,attachmentInput} from "./proxy-payloads"; import {operationRef,operationRead} from "./proxy-operations"; import {proxyToolResult} from "./proxy-result"; @@ -30,6 +34,7 @@ import { matchApiOperation } from "./api-contract"; import { normalizeScopes } from "./access-tokens"; function errorResponse(error: unknown, origin?: string): Response { + if (error instanceof PresetError) return Response.json({error:{code:error.code,message:error.message}},{status:error.status}); if (error instanceof SkillContentError) return Response.json({ error: { code: "invalid_skill_directory", message: error.message } }, {status:409}); if (error instanceof AgentApiError) return Response.json({error: {code: error.code, message: error.message}}, {status: error.status, headers: error.code === "insufficient_scope" ? {"WWW-Authenticate": `Bearer error="insufficient_scope", scope="${error.scope}", resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"`} : undefined}); if (error instanceof ExeIntegrationError) return Response.json({ error: { code: "invalid_request", message: error.message } }, { status: 400 }); @@ -207,11 +212,18 @@ function createMcpServer(service: ApiService, subscriptions = true): McpServer { tool("list_triggers", "List triggers with their current run count and maximum concurrency", z.object({}), () => service.listTriggers()); tool("list_skills", "List searchable team skill metadata. Shared edits affect every trigger 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 team skill by stable ID or key. Shared edits affect every trigger using it.", z.object({ skillId: z.string().min(1) }), ({ skillId }: any) => service.getSkill(skillId)); - tool("create_skill", "Create a reusable literal team skill body.", z.object({ key: z.string().min(1), body: z.string() }), (input: any) => service.createSkill(input)); - tool("update_skill", "Update a shared team skill with optimistic concurrency; the change affects all referencing triggers.", 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("create_skill", "Create a SKILL.md with literal Markdown and frontmatter configuration. Supply body or a structured definition; omitted preset slugs inherit team defaults.", skillInput, (input: any) => service.createSkill(input)); + tool("update_skill", "Update a shared team skill with optimistic concurrency; the change affects all referencing triggers.", skillUpdateInput.extend({skillId:z.string().min(1)}), ({ skillId, ...input }: any) => service.updateSkill(skillId, input)); tool("delete_skill", "Delete an unused team skill; referenced triggers block deletion.", z.object({ skillId: z.string().min(1), expectedRevision: z.number().int().positive() }), ({ skillId, expectedRevision }: any) => service.deleteSkill(skillId, expectedRevision)); tool("list_skill_triggers", "List enabled and disabled triggers affected by a shared skill.", z.object({ skillId: z.string().min(1) }), ({ skillId }: any) => service.listSkillTriggers(skillId)); tool("preview_trigger_prompt", "Preview one skill, literal prompt, Event template and manual instructions without saving or executing.", previewSkillInput, (input: any) => service.previewTriggerPrompt(input)); + tool("list_presets","List team VM, permission and model presets, defaults, immutable slugs and revisions.",z.object({}),()=>service.listPresets()); + tool("create_preset","Create a team preset. Slugs are immutable and unique within preset type/team.",presetInput,(input:any)=>service.savePreset(input)); + tool("update_preset","Update a preset by creating an immutable revision; existing runs retain snapshots.",z.object({presetId:z.uuid(),preset:presetInput}),({presetId,preset}:any)=>service.savePreset(preset,presetId)); + tool("set_default_preset","Select the team default for the preset's type. Future inherited runs use it.",z.object({presetId:z.uuid()}),({presetId}:any)=>service.defaultPreset(presetId)); + tool("delete_preset","Delete an unused non-default preset; historical revisions and accepted runs remain.",z.object({presetId:z.uuid()}),({presetId}:any)=>service.deletePreset(presetId)); + tool("get_skill_trigger","Read a skill's automatic trigger configuration. Legacy manual events are hidden.",z.object({skillId:z.uuid()}),({skillId}:any)=>service.getSkillTrigger(skillId)); + tool("save_skill_trigger","Save only non-manual automation for a skill. SKILL.md owns all execution configuration.",z.object({skillId:z.uuid(),trigger:skillTriggerInput}),({skillId,trigger}:any)=>service.saveSkillTrigger(skillId,trigger)); tool("get_team", "Inspect the current team and its run defaults", z.object({}), () => service.getTeam()); tool("get_trigger", "Get a trigger with its current run count and maximum concurrency", triggerIdSchema, ({ triggerId }: any) => service.getTrigger(triggerId)); tool("create_trigger", "Create a trigger using a saved execution integration ID. Credentials are never accepted or returned.", triggerInputSchema, (input: any) => service.createTrigger(input)); @@ -219,7 +231,7 @@ function createMcpServer(service: ApiService, subscriptions = true): McpServer { tool("delete_trigger", "Delete a saved trigger and its events, retaining its runs", triggerIdSchema, ({ triggerId }: any) => service.deleteTrigger(triggerId)); tool("enable_trigger", "Enable a trigger", triggerIdSchema, ({ triggerId }: any) => service.setTriggerEnabled(triggerId, true)); tool("disable_trigger", "Disable a trigger", triggerIdSchema, ({ triggerId }: any) => service.setTriggerEnabled(triggerId, false)); - tool("start_run","Start a detached team run with optional skill and prompt, or a shell script. Agent VMs are optional; scripts require a VM. Omitted execution settings use Team defaults. Omitted integrationIds inherit this MCP client's effective integration access; explicit IDs select a subset, including an empty set. Omitted runScopes inherit this MCP client's effective Factorize permissions. Subscribe to the returned outcome URI.",startRunInput,(input:any)=>service.startRun(input)); + tool("start_run","Start an agent run with optional skill, prompt and images. Skill frontmatter selects VM, permission and model presets; omitted selections inherit team defaults. Freeze resolved preset revisions and skill commit before queueing. Disabled skills cannot start, concurrency 0 is unlimited, and scripts are retired. Caller permissions bound direct run access. Subscribe to the returned outcome URI.",startRunInput,(input:any)=>service.startRun(input)); tool("invoke_trigger", "Invoke a trigger's manual event with an optional display name, prompt, and JSON data exposed beneath that event's stable slug. Manual invocations are never coalesced; a full trigger queue returns queue_full. idempotencyKey is a client value and must not include the internal manual: claim-key prefix; reuse invocation.idempotency_key from get_run.", manualInvocationSchema.extend({ triggerId: z.string().min(1) }), ({ triggerId, ...input }: any) => service.invokeTrigger(triggerId, input)); tool("get_trigger_invocation_permissions", "List the destinations a source trigger may manually invoke.", triggerIdSchema, ({ triggerId }: any) => service.getInvocationPermissions(triggerId)); tool("set_trigger_invocation_permissions", "Replace manual invocation destinations for a source trigger. Requires an owner session, scoped API key, or authorized OAuth client with triggers:write; destination IDs must belong to the same tenant.", z.object({ triggerId: z.string().min(1), destinationTriggerIds: z.array(z.string().uuid()).max(1000) }).strict(), ({ triggerId, destinationTriggerIds }: any) => service.setInvocationPermissions(triggerId, destinationTriggerIds)); diff --git a/packages/api/src/search-contracts.ts b/packages/api/src/search-contracts.ts index 829c7eb3..796dcb74 100644 --- a/packages/api/src/search-contracts.ts +++ b/packages/api/src/search-contracts.ts @@ -2,7 +2,7 @@ import { z } from "zod"; export const searchRange = z.object({ start: z.number().int().nonnegative(), end: z.number().int().nonnegative() }); export const searchResponse = z.object({ items: z.array(z.object({ - kind: z.enum(["trigger", "run", "trace"]), id: z.string(), title: z.string(), subtitle: z.string(), url: z.string(), - source: z.object({ kind: z.enum(["trigger", "run", "trace"]), label: z.string(), id: z.string() }), + kind: z.enum(["skill", "run"]), id: z.string(), title: z.string(), subtitle: z.string(), url: z.string(), + source: z.object({ kind: z.enum(["skill", "run"]), label: z.string(), id: z.string() }), match: z.object({ text: z.string(), ranges: z.array(searchRange) }), })) }); diff --git a/packages/api/src/skill-definition.ts b/packages/api/src/skill-definition.ts new file mode 100644 index 00000000..3a59d1e9 --- /dev/null +++ b/packages/api/src/skill-definition.ts @@ -0,0 +1,54 @@ +import { parseDocument } from "yaml"; +import { z } from "zod"; + +export const presetSlug = z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).max(120); +export const factorizeMetadata = z.object({ + "vm-preset": presetSlug.optional(), + "permission-preset": presetSlug.optional(), + "model-preset": presetSlug.optional(), + concurrency: z.number().int().nonnegative().max(2147483647).default(0), + disabled: z.boolean().default(false), +}).passthrough(); +export const skillDefinition = z.object({ + name: presetSlug.max(64).refine(name=>name!=="manual","The name manual is reserved."), + description: z.string().max(1024), + factorize: factorizeMetadata, + markdown: z.string().max(100_000), +}); +export type SkillDefinition = z.infer; + +function invalid(message:string):never { throw new z.ZodError([{code:"custom",path:["body"],message}]); } +function split(source: string) { + const header = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(source); + if(/^---\r?\n/.test(source)&&!header)invalid("SKILL.md frontmatter is missing its closing delimiter."); + const doc = parseDocument(header?.[1] ?? "{}"); + let raw:Record; + try{raw=doc.toJS({maxAliasCount:100});}catch{invalid("SKILL.md frontmatter contains invalid or excessive aliases.");} + if(doc.errors.length||!raw||typeof raw!=="object"||Array.isArray(raw))invalid("SKILL.md frontmatter must be a valid YAML mapping."); + return {doc,raw,markdown:header?source.slice(header[0].length):source}; +} +export function readSkillDefinition(source: string, key: string): SkillDefinition { + const { raw, markdown } = split(source); + if (raw.metadata !== undefined && (!raw.metadata || typeof raw.metadata !== "object" || Array.isArray(raw.metadata))) invalid("Skill metadata must be a mapping."); + return skillDefinition.parse({ name: raw.name ?? key, description: raw.description ?? "", factorize: raw.metadata?.factorize ?? {}, markdown }); +} +/** Patch only managed keys, retaining unknown fields and YAML comments. */ +export function writeSkillDefinition(source: string, value: SkillDefinition): string { + const parsed = skillDefinition.parse(value), { doc } = split(source); + doc.set("name", parsed.name); + doc.set("description", parsed.description); + const metadata = doc.get("metadata"); + if (metadata !== undefined && (!metadata || !doc.getIn(["metadata"]) || Array.isArray(doc.toJS().metadata) || typeof doc.toJS().metadata !== "object")) invalid("Skill metadata must be a mapping."); + for (const field of ["vm-preset", "permission-preset", "model-preset", "concurrency", "disabled"] as const) { + if (parsed.factorize[field] === undefined) { if(doc.hasIn(["metadata", "factorize", field]))doc.deleteIn(["metadata", "factorize", field]); } + else doc.setIn(["metadata", "factorize", field], parsed.factorize[field]); + } + return `---\n${doc.toString()}---\n${parsed.markdown}`; +} + +/** Public list/deletion index only. Never duplicate Markdown or arbitrary + * frontmatter into unencrypted database metadata. */ +export function skillDefinitionIndex(value:SkillDefinition){ + const fields=["vm-preset","permission-preset","model-preset","concurrency","disabled"] as const; + return {name:value.name,description:value.description,factorize:Object.fromEntries(fields.filter(field=>value.factorize[field]!==undefined).map(field=>[field,value.factorize[field]]))}; +} diff --git a/packages/api/src/skill-library.ts b/packages/api/src/skill-library.ts index 87fcf7dd..f80187b1 100644 --- a/packages/api/src/skill-library.ts +++ b/packages/api/src/skill-library.ts @@ -1,3 +1,4 @@ +import { readSkillDefinition,skillDefinitionIndex } from "./skill-definition"; import { PostgresSkillContentCache } from "./postgres/skill-content-cache"; import {publishedFiles} from "./mcp-skills"; import { SkillContent, repositoryToken, type ArtifactVersion } from "./skill-content"; @@ -250,10 +251,10 @@ export class SkillLibrary { continue; const pointer: ArtifactVersion = { repo: row.repo, remote: row.remote, commit, key: dir.key }; await client.query( - `INSERT INTO app.skills(tenant_id,id,key,artifact_version) VALUES($1,$2,$3,$4) - ON CONFLICT(tenant_id,key) DO UPDATE SET encrypted_body=NULL,encrypted_directory=NULL,artifact_version=excluded.artifact_version,legacy_context='[]'::jsonb, + `INSERT INTO app.skills(tenant_id,id,key,artifact_version,definition) VALUES($1,$2,$3,$4,$6) + ON CONFLICT(tenant_id,key) DO UPDATE SET encrypted_body=NULL,encrypted_directory=NULL,artifact_version=excluded.artifact_version,legacy_context='[]'::jsonb,definition=excluded.definition, revision=app.skills.revision+$5,updated_at=CASE WHEN $5=0 THEN app.skills.updated_at ELSE now() END`, - [this.tenant, previous?.id ?? crypto.randomUUID(), dir.key, pointer, same ? 0 : 1], + [this.tenant, previous?.id ?? crypto.randomUUID(), dir.key, pointer, same ? 0 : 1, skillDefinitionIndex(readSkillDefinition(bodyOf(dir),dir.key))], ); } await client.query( @@ -265,6 +266,14 @@ export class SkillLibrary { private async validateNames(client: DatabaseClient, directories: Directory[]) { validateLibrary(directories); for(const directory of directories)publishedFiles({key:directory.key,body:bodyOf(directory),version:{commit:"candidate",files:directory.files}}); + for(const directory of directories){ + const definition=readSkillDefinition(bodyOf(directory),directory.key); + for(const kind of ["vm","permission","model"] as const){ + const slug=definition.factorize[`${kind}-preset`];if(!slug)continue; + const found=await client.query("SELECT 1 FROM app.presets WHERE tenant_id=$1 AND kind=$2 AND slug=$3 AND NOT deleted",[this.tenant,kind,slug]); + if(!found.rowCount)throw new SkillConflict(`Unknown ${kind} preset: ${slug}`); + } + } const collisions = await client.query<{name: string}>( "SELECT name FROM app.resource_names WHERE tenant_id=$1 AND kind='trigger' AND name=ANY($2::text[])", [this.tenant, directories.map(directory => directory.key)], @@ -417,8 +426,8 @@ export class SkillLibrary { for (const dir of after) { const pointer: ArtifactVersion = { repo: row.repo, remote: row.remote, commit, key: dir.key }; await client.query( - "UPDATE app.skills SET artifact_version=$3,encrypted_directory=NULL,encrypted_body=NULL,legacy_context='[]'::jsonb,migration_pending=false WHERE tenant_id=$1 AND id=$2", - [this.tenant, dir.id, pointer], + "UPDATE app.skills SET artifact_version=$3,encrypted_directory=NULL,encrypted_body=NULL,legacy_context='[]'::jsonb,migration_pending=false,preset_migration_pending=false,encrypted_preset_migration_body=NULL,preset_migration_source_hash=NULL,definition=$4 WHERE tenant_id=$1 AND id=$2", + [this.tenant, dir.id, pointer, skillDefinitionIndex(readSkillDefinition(dir.body,dir.key))], ); } await client.query( diff --git a/packages/api/src/skills.ts b/packages/api/src/skills.ts index 438658c6..985e8f51 100644 --- a/packages/api/src/skills.ts +++ b/packages/api/src/skills.ts @@ -1,12 +1,13 @@ import { z } from "zod"; +import { skillDefinition, readSkillDefinition, factorizeMetadata } from "./skill-definition"; import { RESOURCE_NAME, resourceName } from "./resource-names"; export const SKILL_KEY = RESOURCE_NAME; export const SKILL_BODY_LIMIT = 100_000; -export const skillInput = z.object({ key: resourceName, body: z.string().max(SKILL_BODY_LIMIT) }).strict(); -export const skillUpdateInput = z.object({ key: resourceName.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 }).extend({trigger:z.object({id:z.guid(),enabled:z.boolean()}).nullable().optional(),lastRunState:z.string().nullable().optional()}); +export const skillInput = z.object({ key: resourceName, body: z.string().max(SKILL_BODY_LIMIT).optional(), definition: skillDefinition.optional() }).strict().refine(value => value.body !== undefined || value.definition !== undefined, "Supply a skill body or definition."); +export const skillUpdateInput = z.object({ key: resourceName.optional(), body: z.string().max(SKILL_BODY_LIMIT).optional(), definition: skillDefinition.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(), definition: skillDefinition.optional(), usageCount: z.number().int().nonnegative(), createdAt: z.string(), updatedAt: z.string() }); +export const skillMetadata = skillResponse.omit({ body: true,definition:true }).extend({description:z.string().default(""),factorize:factorizeMetadata.default({concurrency:0,disabled:false}),hasTriggers:z.boolean().default(false),trigger:z.object({id:z.guid(),enabled:z.boolean()}).nullable().optional(),lastRunState:z.string().nullable().optional()}); export const skillPage = z.object({ items: z.array(skillMetadata), nextCursor: z.guid().nullable() }); export const skillTriggersResponse = z.object({ skillId: z.guid(), triggers: z.array(z.object({ id: z.guid(), name: z.string(), enabled: z.boolean() })) }); export const previewSkillInput = z.object({ @@ -17,7 +18,7 @@ export const previewPromptResponse=z.object({prompt:z.string(),eventText:z.strin export type Skill = z.infer; /** Skill instructions and caller prompt text remain literal. */ export function composePrompt(skill: {body:string}|undefined, prompt:string):string { - return [skill?.body ?? "",prompt].filter(text=>text.trim()).join("\n\n"); + return [skill ? readSkillDefinition(skill.body,"skill").markdown : "",prompt].filter(text=>text.trim()).join("\n\n"); } export const skillDirectoryResponse=z.object({revision:z.number().int().positive(),commit:z.string().nullable(),files:z.array(z.object({path:z.string(),content:z.string(),executable:z.boolean()}))}); diff --git a/packages/api/test/direct-run-defaults.postgres.test.ts b/packages/api/test/direct-run-defaults.postgres.test.ts index 0a44ed00..63d47a07 100644 --- a/packages/api/test/direct-run-defaults.postgres.test.ts +++ b/packages/api/test/direct-run-defaults.postgres.test.ts @@ -10,36 +10,45 @@ vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, const url = process.env.AUTH_TEST_DATABASE_URL; const defaults = (vmImage: string) => ({ executionConfigId: "local", model: "", effort: "", vmImage, tags: [], portableIntegrationIds: [], githubInstallationIds: [], xConnectionIds: [], runScopes: [] }); +async function modelFixture(f:Awaited>){ + const repository=new CredentialRepository(f.db,f.tenantId,f.env.CREDENTIAL_ENCRYPTION_KEY),id=crypto.randomUUID(); + await repository.write({id,kind:"model",name:"Fixture model",origin:null,description:null,expectedRevision:await repository.revision(),idempotencyKey:crypto.randomUUID(),operation:"upsert",managedModelPayload:JSON.stringify({providerUrl:"https://models.example/v1"})}); + await f.db.pool.query("UPDATE app.agent_integrations SET policy='baseline' WHERE tenant_id=$1 AND credential_id=$2",[f.tenantId,id]); + const integration=(await f.db.pool.query("SELECT id FROM app.agent_integrations WHERE tenant_id=$1 AND credential_id=$2",[f.tenantId,id])).rows[0].id; + return {id,integration}; +} + describe.skipIf(!url)("direct run defaults and integration access", { timeout: 30_000 }, () => { it("uses team defaults and inherits or narrows effective integrations", async () => { const f = await loadingFixture(url!); try { + const model=await modelFixture(f); const credentialId = crypto.randomUUID(); - await f.db.pool.query("INSERT INTO app.integration_collections(tenant_id) VALUES($1)", [f.tenantId]); + await f.db.pool.query("INSERT INTO app.integration_collections(tenant_id) VALUES($1) ON CONFLICT DO NOTHING", [f.tenantId]); const encryptedPayload = await encrypt(`${MANAGED_BEARER_PREFIX}test-only-secret`, f.env.CREDENTIAL_ENCRYPTION_KEY); await f.db.pool.query("INSERT INTO app.integration_records(tenant_id,id,kind,name,origin,revision,encrypted_payload) VALUES($1,$2,'bearer','Direct test','https://upstream.test',1,$3)", [f.tenantId, credentialId, encryptedPayload]); await f.db.pool.query("UPDATE app.agent_integrations SET policy='baseline' WHERE tenant_id=$1 AND kind='bearer' AND credential_id=$2", [f.tenantId, credentialId]); const integrationRow = await f.db.pool.query("SELECT id FROM app.agent_integrations WHERE tenant_id=$1 AND kind='bearer' AND credential_id=$2", [f.tenantId, credentialId]); const effectiveIntegrationId = integrationRow.rows[0].id as string; - await f.db.pool.query("UPDATE app.team_settings SET run_defaults=$2 WHERE tenant_id=$1", [f.tenantId, {...defaults("ghcr.io/factorize/direct-run:test"), portableIntegrationIds:[credentialId]}]); + await f.db.pool.query("UPDATE app.team_settings SET run_defaults=$2 WHERE tenant_id=$1", [f.tenantId, {...defaults("ghcr.io/factorize/direct-run:test"),modelAccountId:model.id,model:"fixture-model", portableIntegrationIds:[credentialId]}]); const service = new ApiService(f.env, { ...f.auth, authMethod: "oauth", oauthGrantId: "test-grant", oauthClientId: "test-client", oauthExpiresAt: Math.floor(Date.now() / 1000) + 3600, scopes: ["runs:start", "team:read", "integrations:read", "proxy:use"] }); - const inherited = await service.startRun({ script: "echo inherited defaults", idempotencyKey: "inherit" }); + const inherited = await service.startRun({ prompt: "Inherited defaults", idempotencyKey: "inherit" }); const inheritedConfig = (await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, inherited.runId])).rows[0].execution_config; expect(inheritedConfig.image).toBe("ghcr.io/factorize/direct-run:test"); expect(inheritedConfig.portableIntegrationIds).toEqual([credentialId]); - expect(inheritedConfig.agentIntegrationIds).toEqual([effectiveIntegrationId]); + expect(inheritedConfig.agentIntegrationIds).toEqual(expect.arrayContaining([effectiveIntegrationId,model.integration])); - const empty = await service.startRun({ script: "echo direct", integrationIds: [], idempotencyKey: "empty" }); + const empty = await service.startRun({ prompt: "Direct", integrationIds: [model.integration], idempotencyKey: "empty" }); const emptyConfig = (await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, empty.runId])).rows[0].execution_config; - expect(emptyConfig.executionType).toBe("code"); - expect(emptyConfig.agentIntegrationIds).toEqual([]); + expect(emptyConfig.executionType).toBe("agent"); + expect(emptyConfig.agentIntegrationIds).toEqual([model.integration]); expect(emptyConfig.portableIntegrationIds).toEqual([]); - const narrowed = await service.startRun({ script: "echo narrowed", integrationIds: [effectiveIntegrationId], runScopes: ["team:read"] }); + const narrowed = await service.startRun({ prompt: "Narrowed", integrationIds: [effectiveIntegrationId,model.integration], runScopes: ["team:read"] }); const narrowedConfig = (await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, narrowed.runId])).rows[0].execution_config; - expect(narrowedConfig).toMatchObject({agentIntegrationIds: [effectiveIntegrationId], runScopes: ["team:read"]}); + expect(narrowedConfig).toMatchObject({agentIntegrationIds: [effectiveIntegrationId,model.integration], runScopes: ["team:read"]}); const withoutProxy = new ApiService(f.env, { ...f.auth, authMethod: "oauth", oauthGrantId: "narrow", oauthClientId: "client", oauthExpiresAt: Math.floor(Date.now() / 1000) + 3600, scopes: ["runs:start"] }); await expect(withoutProxy.startRun({ prompt: "narrowed token", integrationIds: [effectiveIntegrationId] })).rejects.toMatchObject({ status: 403 }); const denied = crypto.randomUUID(); @@ -48,32 +57,34 @@ describe.skipIf(!url)("direct run defaults and integration access", { timeout: 3 } finally { await f.cleanup(); } }); - it("uses explicit execution settings before team defaults and preserves intentional empty models", async () => { + it("uses explicit execution settings before presets and rejects empty agent models", async () => { const f = await loadingFixture(url!); try { - await f.db.pool.query("UPDATE app.team_settings SET run_defaults=$2 WHERE tenant_id=$1", [f.tenantId, { ...defaults("ghcr.io/factorize/team-default:test"), capacity: 4 }]); + const model=await modelFixture(f); + await f.db.pool.query("UPDATE app.team_settings SET run_defaults=$2 WHERE tenant_id=$1", [f.tenantId, { ...defaults("ghcr.io/factorize/team-default:test"),modelAccountId:model.id,model:"fixture-model", capacity: 4 }]); const service = new ApiService(f.env, { ...f.auth, authMethod: "oauth", oauthGrantId: "test-grant", oauthClientId: "test-client", oauthExpiresAt: Math.floor(Date.now() / 1000) + 3600, scopes: ["runs:start", "team:read", "integrations:read", "proxy:use"] }); await expect(service.startRun({prompt:"Empty model",model:"",integrationIds:[]})).rejects.toMatchObject({status:409,code:"model_configuration_required"}); - const run = await service.startRun({ script: "echo explicit wins", vmImage: "alpine:3.22", integrationIds: [], idempotencyKey: "explicit-first" }); + const run = await service.startRun({ prompt: "Explicit settings", vmImage: "alpine:3.22", integrationIds: [model.integration], idempotencyKey: "explicit-first" }); const config = (await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, run.runId])).rows[0].execution_config; expect(config.image).toBe("alpine:3.22"); - expect(config.model).toBe(""); + expect(config.model).toBe("fixture-model"); } finally { await f.cleanup(); } }); it("inherits effective MCP scopes, accepts an empty subset, and rejects disabled scopes", async () => { const f = await loadingFixture(url!); try { - await f.db.pool.query("UPDATE app.team_settings SET run_defaults=$2 WHERE tenant_id=$1", [f.tenantId, {...defaults("ghcr.io/factorize/direct-run:test"),runScopes:["runs:start","team:read","triggers:write"]}]); + const model=await modelFixture(f); + await f.db.pool.query("UPDATE app.team_settings SET run_defaults=$2 WHERE tenant_id=$1", [f.tenantId, {...defaults("ghcr.io/factorize/direct-run:test"),modelAccountId:model.id,model:"fixture-model",runScopes:["runs:start","team:read","triggers:write"]}]); await f.db.pool.query("INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version,disabled_scopes) VALUES($1,'oauth','test-grant',$2,$3,$4)", [f.tenantId, f.userId, f.auth.sessionVersion, ["triggers:write"]]); - const service = new ApiService(f.env, { ...f.auth, authMethod: "oauth", oauthGrantId: "test-grant", oauthClientId: "test-client", oauthExpiresAt: Math.floor(Date.now() / 1000) + 3600, scopes: ["runs:start", "team:read", "integrations:read", "triggers:write"] }); + const service = new ApiService(f.env, { ...f.auth, authMethod: "oauth", oauthGrantId: "test-grant", oauthClientId: "test-client", oauthExpiresAt: Math.floor(Date.now() / 1000) + 3600, scopes: ["runs:start", "team:read", "integrations:read", "triggers:write","proxy:use"] }); - const inherited = await service.startRun({ script: "echo inherited access", idempotencyKey: "effective-scopes" }); + const inherited = await service.startRun({ prompt: "Inherited access", idempotencyKey: "effective-scopes" }); const inheritedConfig = (await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, inherited.runId])).rows[0].execution_config; expect(inheritedConfig.runScopes).toContain("runs:start"); expect(inheritedConfig.runScopes).not.toContain("triggers:write"); - const empty = await service.startRun({ script: "echo no permissions", integrationIds: [], runScopes: [], idempotencyKey: "empty-scopes" }); + const empty = await service.startRun({ prompt: "No application permissions", integrationIds: [model.integration], runScopes: [], idempotencyKey: "empty-scopes" }); const emptyConfig = (await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, empty.runId])).rows[0].execution_config; expect(emptyConfig.runScopes).toEqual([]); diff --git a/packages/api/test/docker-code-job.e2e.test.ts b/packages/api/test/docker-code-job.e2e.test.ts index c774de0d..9c01d12d 100644 --- a/packages/api/test/docker-code-job.e2e.test.ts +++ b/packages/api/test/docker-code-job.e2e.test.ts @@ -1,3 +1,6 @@ +import { DEFAULT_RUN_SCOPES } from "../src/run-scopes"; +import { submitRun } from "../src/postgres/run-submission"; +import { encrypt } from "../src/crypto"; import {expect,it,vi} from "vitest"; import {execFileSync} from "node:child_process"; import {generateKeyPairSync,randomUUID} from "node:crypto"; @@ -22,7 +25,7 @@ const wait=(ms:number)=>new Promise(r=>setTimeout(r,ms)); // Signed provider fixtures exercise the production verifier, helper, backend and // scheduler. They are test-local, and do not constitute live Fly verification. -it("runs saved code through vendor identity, selected backend egress, artifacts and cleanup",async()=>{ +it("continues historical script runs through vendor identity, selected backend egress, artifacts and cleanup",async()=>{ const url=process.env.AUTH_TEST_DATABASE_URL!,tls=process.env.FACTORIZE_E2E_TLS_DIR!,namespace=process.env.FACTORIZE_E2E_NAMESPACE!; if(!url||!tls||!namespace)throw new Error("Use npm run test:docker"); const databaseName=process.env.FACTORIZE_E2E_DATABASE!; @@ -77,8 +80,16 @@ while(!fs.existsSync('/tmp/finish-test'))await new Promise(r=>setTimeout(r,100)) fs.writeFileSync(process.env.FACTORIZE_RESULT_PATH,JSON.stringify({status:'succeeded',outputs:{marker:${JSON.stringify(marker)}}})); JS `; - const trigger=await json("/triggers","POST",{name:"docker-code",executionType:"code",script,executionConfigId:"docker",portableIntegrationIds:[integrationId],events:[{kind:"manual",slug:"event-1",config:{}}]}); - const invoked=await json(`/triggers/${trigger.id}/invocations`,"POST",{}),runId=invoked.runId; + const retired=await request("/triggers","POST",{name:"docker-code",executionType:"code",script,executionConfigId:"docker"});expect(retired.status).toBe(400); + const trigger=await json("/triggers","POST",{name:"docker-history",prompt:"Historical compatibility fixture",events:[{kind:"manual",slug:"event-1",config:{}}]}); + // Seed a run accepted before script retirement. Its execution and cleanup + // must remain compatible even though no public API can create another one. + const runId=randomUUID(),invocationId=randomUUID(); + await db.transaction(async client=>{ + const event=(await client.query("SELECT id FROM app.events WHERE tenant_id=$1 AND trigger_id=$2 LIMIT 1",[tenantId,trigger.id])).rows[0]; + await client.query("INSERT INTO app.invocations(tenant_id,id,trigger_id,source,claim_key,event_id,context) VALUES($1,$2,$3,'manual','historical',$4,'{}')",[tenantId,invocationId,trigger.id,event.id]); + await submitRun(client,tenantId,{id:runId,triggerId:trigger.id,invocationId,name:"Historical Docker run",source:"manual",claim:"historical",workspaceName:"",createdAt:new Date().toISOString(),encryptedPrompt:await encrypt("",env.CREDENTIAL_ENCRYPTION_KEY),config:{targetId:"docker",connectionId:"docker",workspace:"",cwd:"",agentKind:"code",tags:[],requiresVm:true,executionProvider:"docker",image:env.TEST_DOCKER_EXECUTION!.image,executionType:"code",script,portableIntegrationIds:[integrationId],modelAccess:"native",runScopes:[...DEFAULT_RUN_SCOPES],inputContext:{}}}); + }); const infrastructure=createDockerTriggerInfrastructure({testMode:true,namespace:app,network,beforeDestroy:async id=>{ const r=(await db.pool.query("SELECT trigger_result,artifact_state FROM app.runs WHERE tenant_id=$1 AND id=$2",[tenantId,runId])).rows[0];destructionEvidence={marker:r.trigger_result?.outputs?.marker,artifactState:r.artifact_state}; }}); @@ -123,12 +134,15 @@ JS const artifacts=(await db.pool.query("SELECT object_key FROM app.run_artifacts WHERE tenant_id=$1 AND run_id=$2",[tenantId,runId])).rows;expect(artifacts.length).toBeGreaterThan(0); for(const artifact of artifacts){const object=await env.RUN_ARTIFACTS!.get(artifact.object_key);expect(await object!.text()).not.toContain(secret);} - const direct = await json("/runs", "POST", { - executionConfigId: "docker", integrationIds: [], runScopes: [], - script: `#!/bin/bash + const directScript=`#!/bin/bash set -eu printf '%s' '{"status":"succeeded","outputs":{"mode":"direct"}}' > "$FACTORIZE_RESULT_PATH" -`, +`; + expect((await request("/runs","POST",{script:directScript,executionConfigId:"docker"})).status).toBe(400); + const direct={runId:randomUUID()},directInvocation=randomUUID(); + await db.transaction(async client=>{ + await client.query("INSERT INTO app.invocations(tenant_id,id,source,claim_key,context) VALUES($1,$2,'direct','historical-direct','{}')",[tenantId,directInvocation]); + await submitRun(client,tenantId,{id:direct.runId,triggerId:null,invocationId:directInvocation,name:"Historical direct script",source:"direct",claim:"historical-direct",workspaceName:"",createdAt:new Date().toISOString(),encryptedPrompt:await encrypt("",env.CREDENTIAL_ENCRYPTION_KEY),config:{targetId:"docker",connectionId:"docker",workspace:"",cwd:"",agentKind:"code",tags:[],requiresVm:true,executionProvider:"docker",image:env.TEST_DOCKER_EXECUTION!.image,executionType:"code",script:directScript,portableIntegrationIds:[],modelAccess:"native",runScopes:[],inputContext:{}}}); }); let directRun; const directDeadline = Date.now() + 60_000; diff --git a/packages/api/test/hosted-workflow.postgres.test.ts b/packages/api/test/hosted-workflow.postgres.test.ts index 481c5a41..83576df2 100644 --- a/packages/api/test/hosted-workflow.postgres.test.ts +++ b/packages/api/test/hosted-workflow.postgres.test.ts @@ -69,6 +69,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("complete local hosted work const receipt=await json("POST",`/api/v1/triggers/${trigger.id}/invocations`,{data:{detail:"event data"},idempotencyKey:"workflow-event"},202);runId=receipt.runId;expect(modelRequests).toHaveLength(0); expect((await json("POST",`/api/v1/triggers/${trigger.id}/invocations`,{data:{detail:"event data"},idempotencyKey:"workflow-event"},202)).runId).toBe(runId); const runs=new RunRepository(f.db);expect((await runs.claimNext())!.id).toBe(runId);await new RunScheduler(f.db,f.env).processHosted(owner.tenantId,runId);expect(modelRequests).toHaveLength(0); + expect((await runs.find(owner.tenantId,runId))?.state,JSON.stringify((await json("GET","/api/v1/runs/"+runId)).failure)).toBe("running"); for(let index=0;index<4;index++){const run=(await runs.find(owner.tenantId,runId))!;await new HostedPi(f.db,f.env,(run,lease)=>createPiMcpTools(f.env,run,lease)).advance(run);} const detail=await json("GET","/api/v1/runs/"+runId);expect(detail).toMatchObject({state:"succeeded",source:"workflow-trigger",context_prompt:"Complete the workflow\n\nSelected event data",trigger_result:{summary:"Workflow completed"}}); expect(JSON.stringify(modelRequests[1])).toContain('factorize');expect(JSON.stringify(modelRequests[1])).toContain('exe.dev');expect(JSON.stringify(modelRequests[1])).toContain('workflow-guide'); diff --git a/packages/api/test/job-lifecycle.postgres.test.ts b/packages/api/test/job-lifecycle.postgres.test.ts index e375ed00..a3ad2f4a 100644 --- a/packages/api/test/job-lifecycle.postgres.test.ts +++ b/packages/api/test/job-lifecycle.postgres.test.ts @@ -1,3 +1,4 @@ +import { submitRun } from "../src/postgres/run-submission"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { readFile, readdir } from "node:fs/promises"; import { Database } from "../src/postgres/database"; @@ -244,11 +245,17 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("trigger lifecycle delivery expect((await database.pool.query("SELECT * FROM app.lifecycle_events WHERE tenant_id=$1 AND event_id=$2", [a, replacement.id])).rows).toHaveLength(1); }); - it("snapshots a code script and structured event context when queued", async () => { + it("retains historical code snapshots and rejects new script invocations", async () => { const a = await tenant(), id = crypto.randomUUID(), timestamp = new Date().toISOString(); const event: Event = { id: crypto.randomUUID(), triggerId: id, kind: "manual", slug: "event-1", enabled: true, config: {}, createdAt: timestamp, updatedAt: timestamp }; const code = await repository(a).create({ id, runScopes: ["triggers:write"], name: `code-${id}`, slug: `code-${id}`, executionType: "code", script: "echo original", prompt: "", runNameTemplate: "", model: "", executionConfig: { connectionId: "exe", agentKind: "codex", executionType: "code", script: "echo original" }, concurrencyLimit: 1, enabled: true, events: [event], createdAt: timestamp, updatedAt: timestamp } as Trigger); - const invocation = await new InvocationService(repository(a), value => encrypt(value, key)).invoke(id, { source: "manual", eventId: event.id, claimKey: crypto.randomUUID(), context: { "event-1": { outputs: { count: 3 } } } }); + await expect(new InvocationService(repository(a), value => encrypt(value,key)).invoke(id,{source:"manual",eventId:event.id,claimKey:"retired",context:{}})).rejects.toMatchObject({code:"invalid_invocation"}); + const runId=crypto.randomUUID(),invocationId=crypto.randomUUID(); + await database.transaction(async client=>{ + await client.query("INSERT INTO app.invocations(tenant_id,id,trigger_id,source,claim_key,event_id,context) VALUES($1,$2,$3,'manual','historical',$4,$5)",[a,invocationId,id,event.id,{"event-1":{outputs:{count:3}}}]); + await submitRun(client,a,{id:runId,invocationId,triggerId:id,name:"Historical script",source:"manual",claim:"historical",encryptedPrompt:await encrypt("",key),config:{...code.executionConfig,runScopes:["triggers:write"],inputContext:{"event-1":{outputs:{count:3}}}},workspaceName:"",createdAt:timestamp}); + }); + const invocation={run:{id:runId}}; const snapshot = await database.pool.query<{ execution_config: any; result_protocol_version: number }>("SELECT execution_config,result_protocol_version FROM app.runs WHERE tenant_id=$1 AND id=$2", [a, invocation.run.id]); expect(snapshot.rows[0]).toMatchObject({ execution_config: { runScopes: ["triggers:write"], executionType: "code", script: "echo original", inputContext: { "event-1": { outputs: { count: 3 } } } }, result_protocol_version: 1 }); await repository(a).update({ ...code, runScopes: [], script: "echo edited", executionConfig: { ...code.executionConfig, script: "echo edited" }, updatedAt: new Date().toISOString() }); diff --git a/packages/api/test/loading.postgres.test.ts b/packages/api/test/loading.postgres.test.ts index fd249b86..7658cd4e 100644 --- a/packages/api/test/loading.postgres.test.ts +++ b/packages/api/test/loading.postgres.test.ts @@ -144,8 +144,7 @@ describe.skipIf(!url)("request loading with PostgreSQL", () => { const omitted = await service.updateTrigger(trigger.id, { ...base }); expect(omitted).toMatchObject({ portableIntegrationIds: [bearerB], modelAccountId: accountB }); await expect(service.createTrigger({ ...base, portableIntegrationIds: [foreignAccount] })).rejects.toMatchObject({ status: 400 }); - const code = await service.createTrigger({ ...base, name: `code-${crypto.randomUUID().slice(0, 8)}`, executionType: "code", script: "echo ok" }); - expect(code).toMatchObject({ portableIntegrationIds: [] }); + await expect(service.createTrigger({ ...base, name: `code-${crypto.randomUUID().slice(0, 8)}`, executionType:"code",script:"echo ok" })).rejects.toMatchObject({code:"scripts_retired"}); expect(await service.createTrigger({...base,name:`need-${crypto.randomUUID().slice(0,8)}`})).not.toHaveProperty("modelAccess"); } finally { await db.pool.query("DELETE FROM app.triggers WHERE tenant_id=$1 AND (slug LIKE 'portable-%' OR slug LIKE 'code-%' OR slug LIKE 'need-%')", [tenantId]); diff --git a/packages/api/test/manual-invocation-permissions.test.ts b/packages/api/test/manual-invocation-permissions.test.ts index b070622e..59fbd4a0 100644 --- a/packages/api/test/manual-invocation-permissions.test.ts +++ b/packages/api/test/manual-invocation-permissions.test.ts @@ -17,6 +17,7 @@ function fixture(options: { member?: boolean; activeToken?: boolean } = {}) { const query = async (sql: string, values: unknown[] = []) => { if (sql.includes("SELECT m.user_id,m.email")) return { rows: options.member === false ? [] : [{ user_id: "owner", email: "owner@example.com", role: "owner", session_version: 1 }], rowCount: options.member === false ? 0 : 1 }; if (sql.includes("SELECT 1 FROM app.access_tokens")) return { rows: options.activeToken === false ? [] : [{ ok: 1 }], rowCount: options.activeToken === false ? 0 : 1 }; + if (sql.includes("SELECT 1 FROM app.trigger_skills")) return {rows:[],rowCount:0}; if (sql.includes("SELECT id FROM app.triggers") && sql.includes("FOR UPDATE")) return { rows: values[1] === sourceId ? [{ id: sourceId }] : [], rowCount: values[1] === sourceId ? 1 : 0 }; if (sql.includes("SELECT id FROM app.triggers")) { const ids = (values[1] as string[]).filter(id => id === destinationId || id === sourceId || id === crossProjectId); diff --git a/packages/api/test/mcp-skills.postgres.test.ts b/packages/api/test/mcp-skills.postgres.test.ts index a343a04e..1f8e92c0 100644 --- a/packages/api/test/mcp-skills.postgres.test.ts +++ b/packages/api/test/mcp-skills.postgres.test.ts @@ -43,7 +43,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("authorized MCP Skills exte it("keeps legacy skill tools visible and usable without extension negotiation",async()=>{ const tools=await rpc("tools/list");expect(tools.result.tools.map((tool:any)=>tool.name)).toEqual(expect.arrayContaining(["list_skills","get_skill"])); const list=await rpc("tools/call",{name:"list_skills",arguments:{}});expect(list.result.isError).not.toBe(true);expect(JSON.stringify(list.result)).toContain("guide"); - const skill=await rpc("tools/call",{name:"get_skill",arguments:{skillId:id}});expect(skill.result.isError).not.toBe(true);expect(skill.result.structuredContent.body).toBe(body); + const skill=await rpc("tools/call",{name:"get_skill",arguments:{skillId:id}});expect(skill.result.isError).not.toBe(true);expect(skill.result.structuredContent.definition.markdown).toBe("Reflect, then read references/example.txt.");expect(skill.result.structuredContent.body).toContain("author: local"); }); it("enforces scopes, membership, canonical paths and Team isolation on every method",async()=>{ for(const method of ["skills/list","skills/get","resources/read"]){ diff --git a/packages/api/test/pages-smoke.e2e.test.ts b/packages/api/test/pages-smoke.e2e.test.ts index ed076d29..242d4636 100644 --- a/packages/api/test/pages-smoke.e2e.test.ts +++ b/packages/api/test/pages-smoke.e2e.test.ts @@ -72,16 +72,16 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("every page E2E smoke", () "run info": { path: () => run() + "/info", ready: info }, "legacy run context": { path: () => run() + "/context", destination: () => run() + "/info", ready: info }, "legacy run settings": { path: () => run() + "/settings", destination: () => run() + "/info", ready: info }, - "settings": { path: () => "/settings", destination: () => "/settings/vm", ready: heading("VM settings") }, - "VM presets": { path: () => "/settings/vm-presets", ready: heading("VM presets") }, + "settings": { path: () => "/settings", destination: () => "/settings/vm", ready: heading("VM presets") }, + "VM presets": { path: () => "/settings/vm-presets", destination: () => "/settings/vm", ready: heading("VM presets") }, "legacy integrations": { path: () => "/settings/integrations", destination: () => "/integrations", ready: heading("Available integrations") }, "integrations": { path: () => "/integrations", ready: heading("Available integrations") }, "API keys": { path: () => "/settings/api-keys", ready: heading("API keys") }, "create API key": { path: () => "/settings/api-keys/new", ready: label("Key name") }, "authorized clients": { path: () => "/settings/authorized-clients", ready: heading("Authorized clients") }, "password": { path: () => "/settings/password", ready: label("Current password") }, - "skills": { path: () => "/skills", ready: heading("smoke-skill") }, - "skill": { path: () => `/skills/${skillId}`, ready: heading("Instructions") }, + "skills": { path: () => "/skills", ready: page => page.getByRole("link", { name: "smoke-skill", exact: true }).waitFor() }, + "skill": { path: () => `/skills/${skillId}`, ready: page => page.getByText("Smoke test instructions", { exact: true }).waitFor() }, "login": { path: () => "/auth/login", ready: label("Password"), anonymous: true }, "signup": { path: () => "/auth/signup", ready: label("New password"), anonymous: true }, "password reset request": { path: () => "/auth/password-reset", ready: label("Email"), anonymous: true }, diff --git a/packages/api/test/preset-mcp.postgres.test.ts b/packages/api/test/preset-mcp.postgres.test.ts new file mode 100644 index 00000000..c7aa0277 --- /dev/null +++ b/packages/api/test/preset-mcp.postgres.test.ts @@ -0,0 +1,40 @@ +import { expect,it,vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { installSkillArtifacts } from "./helpers/memory-skill-git"; +import { SkillLibrary } from "../src/skill-library"; +import { protectedApiFetch } from "../src/protected-api"; +import { CredentialRepository } from "../src/postgres/credential-repository"; +vi.mock("../src/skill-git",()=>({withSkillGit:vi.fn()})); +vi.mock("cloudflare:workers",()=>({WorkerEntrypoint:class{},DurableObject:class{}})); +vi.mock("@cloudflare/workers-oauth-provider",()=>({OAuthProvider:class{},AuthorizationError:class extends Error{},getOAuthApi:vi.fn()})); +const meta={"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{name:"preset-fixture",version:"1"},"io.modelcontextprotocol/clientCapabilities":{}}; +it.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP manages referenced presets and skill definitions with the same run snapshot and authorization semantics as REST",async()=>{ + const f=await loadingFixture(process.env.AUTH_TEST_DATABASE_URL!); + try{ + installSkillArtifacts(f.env);await new SkillLibrary(f.env,f.tenantId).configure({kind:"managed"}); + const auth={...f.auth,scopes:[...f.auth.scopes,"skills:read","skills:write","runs:start"]}; + async function rpc(method:string,params:Record={}){ + const response=await protectedApiFetch(new Request(f.env.APP_ORIGIN+"/mcp",{method:"POST",headers:{"Mcp-Method":method,...(method==="tools/call"?{"Mcp-Name":String(params.name)}:{}),Host:"factorize.test","Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:1,method,params:{_meta:meta,...params}})}),f.env,auth,{} as any); + const text=await response.text();expect(response.status,text).toBe(200);return JSON.parse(text.startsWith("{")?text:text.split("\n").find(line=>line.startsWith("data: "))!.slice(6)); + } + async function call(name:string,args:Record={}){const response=await rpc("tools/call",{name,arguments:args});expect(response.error,JSON.stringify(response)).toBeUndefined();expect(response.result.isError,JSON.stringify(response)).not.toBe(true);return response.result.structuredContent;} + const catalog=await rpc("tools/list");expect(catalog.result.tools.map((t:any)=>t.name)).toEqual(expect.arrayContaining(["list_presets","create_preset","update_preset","set_default_preset","delete_preset","get_skill_trigger","save_skill_trigger"])); + expect((await call("list_presets")).presets.filter((p:any)=>p.isDefault)).toHaveLength(3); + const modelId=crypto.randomUUID();await new CredentialRepository(f.db,f.tenantId,f.env.CREDENTIAL_ENCRYPTION_KEY).write({id:modelId,kind:"model",name:"Fixture",origin:null,description:null,expectedRevision:0,idempotencyKey:crypto.randomUUID(),operation:"upsert",managedModelPayload:JSON.stringify({providerUrl:"https://fixture.invalid/v1"})}); + const model={kind:"model",name:"Careful",slug:"careful",settings:{modelAccountId:modelId,model:"fixture-model",effort:"high"}}; + const created=(await call("create_preset",model)).preset;await call("set_default_preset",{presetId:created.id}); + const definition={name:"mcp-skill",description:"MCP fixture",markdown:"# Instructions",factorize:{concurrency:0,disabled:false,"model-preset":"careful"}}; + const skill=await call("create_skill",{key:"mcp-skill",definition});expect(skill.definition.factorize["model-preset"]).toBe("careful"); + const updated=await call("update_skill",{skillId:skill.id,expectedRevision:skill.revision,definition:{...definition,description:"Updated"}}); + const run=await call("start_run",{skill:skill.id,idempotencyKey:"mcp-preset-run"});expect(run.runId).toBeTruthy(); + const detail=await call("get_run",{runId:run.runId});expect(detail.execution_configuration.presetSnapshot.presets.model).toMatchObject({slug:"careful",revision:1,inherited:false}); + await call("update_preset",{presetId:created.id,preset:{...model,expectedRevision:1,settings:{...model.settings,model:"next-model"}}}); + expect((await call("get_run",{runId:run.runId})).execution_configuration.model).toBe("fixture-model"); + await call("save_skill_trigger",{skillId:skill.id,trigger:{enabled:true,events:[]}});expect((await call("get_skill_trigger",{skillId:skill.id})).trigger.events).toEqual([]); + await call("update_skill",{skillId:skill.id,expectedRevision:updated.revision,definition:{...definition,factorize:{...definition.factorize,disabled:true}}}); + const disabled=await rpc("tools/call",{name:"start_run",arguments:{skill:skill.id}});expect(JSON.stringify(disabled)).toContain("skill_disabled"); + const retired=await rpc("tools/call",{name:"start_run",arguments:{script:"echo retired"}});expect(JSON.stringify(retired)).toContain("scripts_retired"); + const current=await call("get_skill",{skillId:skill.id});expect(current.definition.factorize.disabled).toBe(true); + const response=await protectedApiFetch(new Request(f.env.APP_ORIGIN+`/api/v1/skills/${skill.id}/settings`,{method:"PUT",headers:{Origin:f.env.APP_ORIGIN,"Content-Type":"application/json"},body:JSON.stringify({expectedRevision:1,defaults:{}})}),f.env,auth,{} as any);expect(response.status).toBe(410); + }finally{await f.cleanup();} +}); diff --git a/packages/api/test/preset-migration.postgres.test.ts b/packages/api/test/preset-migration.postgres.test.ts new file mode 100644 index 00000000..60f4a88f --- /dev/null +++ b/packages/api/test/preset-migration.postgres.test.ts @@ -0,0 +1,73 @@ +import { SkillContent } from "../src/skill-content"; +import { expect,it,vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { migratePresetSkills } from "../src/preset-migration"; +import { encrypt,decrypt } from "../src/crypto"; +import { readSkillDefinition } from "../src/skill-definition"; +import { installSkillArtifacts } from "./helpers/memory-skill-git"; +import { withSkillGit } from "../src/skill-git"; +import { SkillLibrary } from "../src/skill-library"; +import { markdown } from "../src/skill-files"; +vi.mock("../src/skill-git",()=>({withSkillGit:vi.fn()})); +vi.mock("cloudflare:workers",()=>({WorkerEntrypoint:class{},DurableObject:class{}})); +vi.mock("@cloudflare/workers-oauth-provider",()=>({OAuthProvider:class{},AuthorizationError:class extends Error{},getOAuthApi:vi.fn()})); +it.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("migrates distinct settings once, preserves prompts/files/history and disables script skills",async()=>{ + const f=await loadingFixture(process.env.AUTH_TEST_DATABASE_URL!); + try{ + const ids=[]; + for(const [i,model] of ["one","one","two"].entries()){ + const id=crypto.randomUUID();ids.push(id); + const body="# Instructions\n"; + await f.db.pool.query("INSERT INTO app.skills(tenant_id,id,key,encrypted_body,encrypted_directory,encrypted_prompt,run_defaults) VALUES($1,$2,$3,$4,$5,$6,$7)",[f.tenantId,id,`legacy-${i}`,await encrypt(body,f.env.CREDENTIAL_ENCRYPTION_KEY),await encrypt(JSON.stringify({commit:"legacy",files:[markdown(body),{path:"helper.txt",content:btoa("preserved"),executable:false}]}),f.env.CREDENTIAL_ENCRYPTION_KEY),await encrypt("Extra prompt",f.env.CREDENTIAL_ENCRYPTION_KEY),{requiresVm:false,model,concurrencyLimit:2,...(i===2?{executionType:"code"}:{})}]); + } + await f.db.pool.query("INSERT INTO app.trigger_skills(tenant_id,trigger_id,skill_id,position) VALUES($1,$2,$3,0)",[f.tenantId,f.triggerIds[0],ids[2]]); + await migratePresetSkills(f.env,f.tenantId); + const rows=(await f.db.pool.query("SELECT * FROM app.skills WHERE tenant_id=$1 ORDER BY key",[f.tenantId])).rows; + const first=readSkillDefinition(await decrypt(rows[0].encrypted_body,f.env.CREDENTIAL_ENCRYPTION_KEY),rows[0].key); + const second=rows[1].definition,third=rows[2].definition; + expect(first.factorize["model-preset"]).toBe(second.factorize["model-preset"]); + expect(third.factorize["model-preset"]).not.toBe(first.factorize["model-preset"]); + expect(first.factorize.concurrency).toBe(2);expect(third.factorize.disabled).toBe(true); + expect(first.markdown).toBe("# Instructions\n\n\nExtra prompt"); + expect(JSON.parse(await decrypt(rows[0].encrypted_directory,f.env.CREDENTIAL_ENCRYPTION_KEY)).files[1].content).toBe(btoa("preserved")); + expect((await f.db.pool.query("SELECT enabled FROM app.triggers WHERE tenant_id=$1 AND id=$2",[f.tenantId,f.triggerIds[0]])).rows[0].enabled).toBe(false); + const count=(await f.db.pool.query("SELECT count(*) n FROM app.presets WHERE tenant_id=$1",[f.tenantId])).rows[0].n; + await migratePresetSkills(f.env,f.tenantId); + expect((await f.db.pool.query("SELECT count(*) n FROM app.presets WHERE tenant_id=$1",[f.tenantId])).rows[0].n).toBe(count); + expect((await f.db.pool.query("SELECT revision FROM app.skills WHERE tenant_id=$1 ORDER BY key",[f.tenantId])).rows).toEqual(rows.map(row=>({revision:row.revision}))); + expect((await f.db.pool.query("SELECT count(*) n FROM app.presets WHERE tenant_id=$1 AND is_default",[f.tenantId])).rows[0].n).toBe("3"); + expect((await f.db.pool.query("SELECT count(*) n FROM app.runs WHERE tenant_id=$1",[f.tenantId])).rows[0].n).toBe("3"); + }finally{await f.cleanup();} +}); + +it.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("resumes after a failed Git publication without duplicating migrated instructions",async()=>{ + const f=await loadingFixture(process.env.AUTH_TEST_DATABASE_URL!); + try{ + installSkillArtifacts(f.env); + const id=crypto.randomUUID(); + await f.db.pool.query("INSERT INTO app.skills(tenant_id,id,key,encrypted_body,encrypted_prompt) VALUES($1,$2,'recovery',$3,$4)",[f.tenantId,id,await encrypt("Body",f.env.CREDENTIAL_ENCRYPTION_KEY),await encrypt("Extra",f.env.CREDENTIAL_ENCRYPTION_KEY)]); + await new SkillLibrary(f.env,f.tenantId).configure({kind:"managed"}); + await f.db.pool.query("UPDATE app.skills SET definition=NULL WHERE tenant_id=$1 AND id=$2",[f.tenantId,id]); + const original=vi.mocked(withSkillGit).getMockImplementation()!; + vi.mocked(withSkillGit).mockImplementation((remote,work)=>original(remote,repo=>work({...repo,write:async()=>{throw new Error("fixture publication failure");}} as any))); + await expect(migratePresetSkills(f.env,f.tenantId)).rejects.toThrow(); + expect((await f.db.pool.query("SELECT preset_migration_pending FROM app.skills WHERE tenant_id=$1 AND id=$2",[f.tenantId,id])).rows[0].preset_migration_pending).toBe(true); + vi.mocked(withSkillGit).mockImplementation(original); + await migratePresetSkills(f.env,f.tenantId); + // A write accepted by Git but whose response is lost must not append again. + const before=(await f.db.pool.query("SELECT artifact_version FROM app.skills WHERE tenant_id=$1 AND id=$2",[f.tenantId,id])).rows[0]; + await f.db.pool.query("UPDATE app.skills SET preset_migration_pending=true,encrypted_prompt=$3 WHERE tenant_id=$1 AND id=$2",[f.tenantId,id,await encrypt("Second prompt",f.env.CREDENTIAL_ENCRYPTION_KEY)]); + vi.mocked(withSkillGit).mockImplementation((remote,work)=>original(remote,repo=>work({...repo,write:async(...args:any[])=>{await (repo.write as any)(...args);throw new Error("lost Git acknowledgement");}} as any))); + await expect(migratePresetSkills(f.env,f.tenantId)).rejects.toThrow(); + vi.mocked(withSkillGit).mockImplementation(original); + await new SkillLibrary(f.env,f.tenantId).sync(); + await migratePresetSkills(f.env,f.tenantId); + const row=(await f.db.pool.query("SELECT definition,artifact_version FROM app.skills WHERE tenant_id=$1 AND id=$2",[f.tenantId,id])).rows[0]; + expect(row.definition).not.toHaveProperty("markdown"); + const loaded=await new SkillContent(f.env.SKILL_ARTIFACTS).read(row,value=>decrypt(value,f.env.CREDENTIAL_ENCRYPTION_KEY)); + expect(readSkillDefinition(loaded.body,"recovery").markdown).toBe("Body\n\nExtra\n\nSecond prompt"); + expect(row.artifact_version.commit).toBeTruthy(); + await migratePresetSkills(f.env,f.tenantId); + expect((await f.db.pool.query("SELECT definition FROM app.skills WHERE tenant_id=$1 AND id=$2",[f.tenantId,id])).rows[0].definition).toEqual(row.definition); + }finally{await f.cleanup();} +}); diff --git a/packages/api/test/preset-runs.postgres.test.ts b/packages/api/test/preset-runs.postgres.test.ts new file mode 100644 index 00000000..42ad15a7 --- /dev/null +++ b/packages/api/test/preset-runs.postgres.test.ts @@ -0,0 +1,93 @@ +import { AutomationScheduler } from "../src/postgres/automation-scheduler"; +import { expect,it,vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { ApiService } from "../src/flow-service"; +import { CredentialRepository } from "../src/postgres/credential-repository"; +import { encrypt } from "../src/crypto"; +import { writeSkillDefinition,readSkillDefinition } from "../src/skill-definition"; +import { RunRepository } from "../src/postgres/run-repository"; +import { InvocationService } from "../src/job-domain"; +import { PostgresTriggerRepository } from "../src/postgres/job-repository"; +import { decrypt } from "../src/crypto"; +vi.mock("cloudflare:workers",()=>({WorkerEntrypoint:class{},DurableObject:class{}})); +vi.mock("@cloudflare/workers-oauth-provider",()=>({OAuthProvider:class{},AuthorizationError:class extends Error{},getOAuthApi:vi.fn()})); +it.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("freezes inherited/explicit presets before queueing, enforces skill disabled/concurrency and preserves accepted runs",async()=>{ + const f=await loadingFixture(process.env.AUTH_TEST_DATABASE_URL!); + try{ + const service=new ApiService(f.env,{...f.auth,scopes:[...f.auth.scopes,"skills:read","skills:write","runs:start"]}); + await service.listPresets(); + const account=crypto.randomUUID(); + await new CredentialRepository(f.db,f.tenantId,f.env.CREDENTIAL_ENCRYPTION_KEY).write({id:account,kind:"model",name:"Fixture model",origin:null,description:null,expectedRevision:0,idempotencyKey:crypto.randomUUID(),operation:"upsert",managedModelPayload:JSON.stringify({providerUrl:"https://models.example/v1"})}); + const model=(await service.savePreset({kind:"model",slug:"careful",name:"Careful",settings:{modelAccountId:account,model:"fixture-model",effort:"high"}})).preset; + await service.defaultPreset(model.id); + const skillId=crypto.randomUUID();let def=readSkillDefinition("# Instructions", "snapshot");def.factorize.concurrency=1; + const body=writeSkillDefinition("",def); + await f.db.pool.query("INSERT INTO app.skills(tenant_id,id,key,encrypted_body,definition,encrypted_directory) VALUES($1,$2,'snapshot',$3,$4,$5)",[f.tenantId,skillId,await encrypt(body,f.env.CREDENTIAL_ENCRYPTION_KEY),def,await encrypt(JSON.stringify({commit:"fixture-commit",files:[]}),f.env.CREDENTIAL_ENCRYPTION_KEY)]); + const first=await service.startRun({skill:"snapshot"}); + const second=await service.startRun({skill:"snapshot"}); + const row=async(id:string)=>(await f.db.pool.query("SELECT state,execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2",[f.tenantId,id])).rows[0]; + expect((await row(first.runId)).state).toBe("reserved");expect((await row(second.runId)).state).toBe("queued"); + expect((await row(second.runId)).execution_config.presetSnapshot).toMatchObject({skillCommit:"fixture-commit",presets:{model:{slug:"careful",revision:1,inherited:true},vm:{inherited:true},permission:{inherited:true}}}); + await service.savePreset({kind:"model",slug:"careful",name:"Careful",settings:{modelAccountId:account,model:"new-model"},expectedRevision:1},model.id); + def.factorize={...def.factorize,concurrency:0,"model-preset":"careful"}; + await f.db.pool.query("UPDATE app.skills SET encrypted_body=$3,definition=$4,revision=revision+1 WHERE tenant_id=$1 AND id=$2",[f.tenantId,skillId,await encrypt(writeSkillDefinition("",def),f.env.CREDENTIAL_ENCRYPTION_KEY),def]); + const third=await service.startRun({skill:"snapshot"}); + expect((await row(third.runId))).toMatchObject({state:"reserved",execution_config:{model:"new-model",presetSnapshot:{presets:{model:{revision:2,inherited:false}}}}}); + expect((await row(second.runId)).execution_config.model).toBe("fixture-model"); + const trigger=await service.saveSkillTrigger(skillId,{enabled:true,events:[{kind:"schedule",slug:"hourly",enabled:true,config:{cron:"0 * * * *",timezone:"UTC"}}]}); + const repository=new PostgresTriggerRepository(f.db,f.tenantId,value=>encrypt(value,f.env.CREDENTIAL_ENCRYPTION_KEY),value=>decrypt(value,f.env.CREDENTIAL_ENCRYPTION_KEY)); + const invoker=new InvocationService(repository,value=>encrypt(value,f.env.CREDENTIAL_ENCRYPTION_KEY)); + const event=trigger.trigger!.events[0]; + const automated=await invoker.invoke(trigger.trigger!.id,{source:"schedule",claimKey:"first",eventId:event.id,context:{hourly:{}}}); + expect((await row(automated.run.id)).execution_config.presetSnapshot.presets.model.revision).toBe(2); + const beforeTriggerEdit=(await service.getSkill(skillId)).body; + const cleared=await service.saveSkillTrigger(skillId,{enabled:true,expectedUpdatedAt:trigger.trigger!.updatedAt,events:[]}); + expect(cleared.trigger?.events).toEqual([]); + await service.invokeTrigger(trigger.trigger!.id,{prompt:"",idempotencyKey:"independent-manual"}); + expect((await service.getSkill(skillId)).body).toBe(beforeTriggerEdit); + def.factorize.disabled=true; + await f.db.pool.query("UPDATE app.skills SET encrypted_body=$3,definition=$4,revision=revision+1 WHERE tenant_id=$1 AND id=$2",[f.tenantId,skillId,await encrypt(writeSkillDefinition("",def),f.env.CREDENTIAL_ENCRYPTION_KEY),def]); + await expect(service.startRun({skill:"snapshot"})).rejects.toMatchObject({code:"skill_disabled"}); + await expect(invoker.invoke(trigger.trigger!.id,{source:"schedule",claimKey:"disabled",eventId:event.id,context:{hourly:{}}})).rejects.toMatchObject({code:"trigger_disabled"}); + await f.db.pool.query("UPDATE app.runs SET state='succeeded' WHERE tenant_id=$1 AND id=$2",[f.tenantId,first.runId]); + expect((await row(first.runId)).state).toBe("succeeded"); + await expect(service.startRun({script:"echo retired"})).rejects.toMatchObject({code:"scripts_retired"}); + await expect(service.createTrigger({name:"retired",executionType:"code",script:"echo retired",prompt:"",events:[]})).rejects.toMatchObject({code:"scripts_retired"}); + expect((await service.createTrigger({name:"empty-script-agent",executionType:"agent",script:"",prompt:"Agent instructions",events:[]})).executionType).toBe("agent"); + await f.db.pool.query("UPDATE app.runs SET state='succeeded' WHERE tenant_id=$1 AND id<>$2",[f.tenantId,second.runId]); + await f.db.pool.query("UPDATE app.trigger_runs SET state='succeeded' WHERE tenant_id=$1 AND id<>$2",[f.tenantId,second.runId]); + const claimed=await new RunRepository(f.db).claimNext(); + expect(claimed?.id).toBe(second.runId); + expect(claimed?.executionConfig.model).toBe("fixture-model"); + const limited=new ApiService(f.env,{...f.auth,scopes:["runs:start","runs:read"]}); + await expect(limited.startRun({prompt:"Test",runScopes:["team:write"]})).rejects.toMatchObject({status:403}); + def.factorize.disabled=false;def.factorize.concurrency=1; + await f.db.pool.query("UPDATE app.skills SET encrypted_body=$3,definition=$4,revision=revision+1 WHERE tenant_id=$1 AND id=$2",[f.tenantId,skillId,await encrypt(writeSkillDefinition("",def),f.env.CREDENTIAL_ENCRYPTION_KEY),def]); + await f.db.pool.query("UPDATE app.team_settings SET run_defaults=run_defaults||'{\"capacity\":2}'::jsonb WHERE tenant_id=$1",[f.tenantId]); + for(let i=0;i<2;i++)expect((await row((await service.startRun({skill:"snapshot"})).runId)).state).toBe("queued"); + await expect(service.startRun({skill:"snapshot"})).rejects.toMatchObject({code:"queue_full"}); + }finally{await f.cleanup();} +}); + +it.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("migrates on the first automatic invocation without a prior UI read and skips disabled occurrences",async()=>{ + const f=await loadingFixture(process.env.AUTH_TEST_DATABASE_URL!); + try{ + const modelId=crypto.randomUUID();await new CredentialRepository(f.db,f.tenantId,f.env.CREDENTIAL_ENCRYPTION_KEY).write({id:modelId,kind:"model",name:"Fixture",origin:null,description:null,expectedRevision:0,idempotencyKey:crypto.randomUUID(),operation:"upsert",managedModelPayload:JSON.stringify({providerUrl:"https://fixture.invalid/v1"})}); + await f.db.pool.query("UPDATE app.team_settings SET run_defaults=run_defaults||$2::jsonb WHERE tenant_id=$1",[f.tenantId,{modelAccountId:modelId,model:"fixture",requiresVm:false}]); + const id=crypto.randomUUID(),triggerId=f.triggerIds[4]; + await f.db.pool.query("INSERT INTO app.skills(tenant_id,id,key,encrypted_body) VALUES($1,$2,'automatic-first',$3)",[f.tenantId,id,await encrypt("Automatic instructions",f.env.CREDENTIAL_ENCRYPTION_KEY)]); + await f.db.pool.query("INSERT INTO app.trigger_skills(tenant_id,trigger_id,skill_id,position) VALUES($1,$2,$3,0)",[f.tenantId,triggerId,id]); + const event=(await f.db.pool.query("SELECT id FROM app.events WHERE tenant_id=$1 AND trigger_id=$2 AND kind='schedule'",[f.tenantId,triggerId])).rows[0]; + await f.db.pool.query("INSERT INTO app.schedule_state(tenant_id,event_id,trigger_id,next_run_at) VALUES($1,$2,$3,date_trunc('hour',now())-interval '1 hour')",[f.tenantId,event.id,triggerId]); + expect((await f.db.pool.query("SELECT count(*)::int n FROM app.presets WHERE tenant_id=$1",[f.tenantId])).rows[0].n).toBe(0); + await new AutomationScheduler(f.db,f.env).process(); + const runs=(await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND launch_skill_id=$2",[f.tenantId,id])).rows; + expect(runs).toHaveLength(1);expect(runs[0].execution_config.presetSnapshot.presets.model).toMatchObject({slug:"team-default",inherited:false}); + const row=(await f.db.pool.query("SELECT encrypted_body FROM app.skills WHERE tenant_id=$1 AND id=$2",[f.tenantId,id])).rows[0]; + const source=await decrypt(row.encrypted_body,f.env.CREDENTIAL_ENCRYPTION_KEY),definition=readSkillDefinition(source,"automatic-first");definition.factorize.disabled=true; + await f.db.pool.query("UPDATE app.skills SET encrypted_body=$3,definition=$4,revision=revision+1 WHERE tenant_id=$1 AND id=$2",[f.tenantId,id,await encrypt(writeSkillDefinition(source,definition),f.env.CREDENTIAL_ENCRYPTION_KEY),definition]); + await f.db.pool.query("UPDATE app.schedule_state SET next_run_at=date_trunc('hour',now())-interval '1 hour' WHERE tenant_id=$1 AND event_id=$2",[f.tenantId,event.id]); + await new AutomationScheduler(f.db,f.env).process(); + expect((await f.db.pool.query("SELECT count(*)::int n FROM app.runs WHERE tenant_id=$1 AND launch_skill_id=$2",[f.tenantId,id])).rows[0].n).toBe(1); + }finally{await f.cleanup();} +}); diff --git a/packages/api/test/presets.postgres.test.ts b/packages/api/test/presets.postgres.test.ts new file mode 100644 index 00000000..1abc4b5c --- /dev/null +++ b/packages/api/test/presets.postgres.test.ts @@ -0,0 +1,41 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { PresetRepository } from "../src/postgres/preset-repository"; +import { ApiService } from "../src/flow-service"; +import { protectedApiFetch } from "../src/protected-api"; +vi.mock("cloudflare:workers",()=>({WorkerEntrypoint:class{},DurableObject:class{}})); +vi.mock("@cloudflare/workers-oauth-provider",()=>({OAuthProvider:class{},AuthorizationError:class extends Error{},getOAuthApi:vi.fn()})); + +it.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("versions all preset kinds, protects defaults/references, enforces tenants and API validation",async()=>{ + const f=await loadingFixture(process.env.AUTH_TEST_DATABASE_URL!); + try{ + const service=new ApiService(f.env,f.auth),store=new PresetRepository(f.db,f.tenantId); + for(const kind of ["vm","permission","model"] as const){ + const settings=kind==="vm"?{provider:"none" as const}:kind==="permission"?{runScopes:[]}: {model:"fixture-model",effort:"high"}; + const first=(await service.savePreset({kind,slug:"first",name:"First",settings})).preset; + expect(first).toMatchObject({isDefault:true,revision:1,slug:"first"}); + const next=(await service.savePreset({kind,slug:"second",name:"Second",settings})).preset; + await expect(service.deletePreset(first.id)).rejects.toMatchObject({code:"default_preset"}); + await service.defaultPreset(next.id); + const updated=await service.savePreset({kind,slug:"first",name:"Renamed",settings,expectedRevision:1},first.id); + expect(updated.preset.revision).toBe(2); + await expect(service.savePreset({kind,slug:"changed",name:"Bad",settings},first.id)).rejects.toMatchObject({code:"immutable_slug"}); + await expect(service.savePreset({kind,slug:"first",name:"Stale",settings,expectedRevision:1},first.id)).rejects.toMatchObject({code:"stale_preset"}); + await expect(service.savePreset({kind,slug:"first",name:"Duplicate",settings})).rejects.toMatchObject({code:"duplicate_slug"}); + const skillId=crypto.randomUUID(); + await f.db.pool.query("INSERT INTO app.skills(tenant_id,id,key,definition) VALUES($1,$2,$3,$4)",[f.tenantId,skillId,`uses-${kind}`,{factorize:{[`${kind}-preset`]:'first'}}]); + await expect(service.deletePreset(first.id)).rejects.toMatchObject({code:"preset_referenced",message:expect.stringContaining(`uses-${kind}`)}); + await f.db.pool.query("DELETE FROM app.skills WHERE tenant_id=$1 AND id=$2",[f.tenantId,skillId]); + await service.deletePreset(first.id); + expect((await store.list()).find(p=>p.id===first.id)).toBeUndefined(); + expect((await f.db.pool.query("SELECT revision FROM app.preset_revisions WHERE tenant_id=$1 AND preset_id=$2 ORDER BY revision",[f.tenantId,first.id])).rows).toEqual([{revision:1},{revision:2}]); + await expect(new PresetRepository(f.db,f.otherTenant).remove(next.id)).rejects.toMatchObject({code:"not_found"}); + } + await expect(service.savePreset({kind:"vm",slug:"missing",name:"Missing",settings:{provider:"exe",connectionId:"foreign",image:"",tags:[]}})).rejects.toMatchObject({status:400}); + await expect(service.savePreset({kind:"model",slug:"missing",name:"Missing",settings:{modelAccountId:crypto.randomUUID()}})).rejects.toMatchObject({status:400}); + const request=new Request(f.env.APP_ORIGIN+"/api/v1/presets",{method:"POST",headers:{Origin:f.env.APP_ORIGIN,"Content-Type":"application/json"},body:JSON.stringify({kind:"model",slug:"bad slug",name:"Bad",settings:{}})}); + expect((await protectedApiFetch(request,f.env,f.auth,{} as ExecutionContext)).status).toBe(400); + const denied=new ApiService(f.env,{...f.auth,scopes:["integrations:read"]}); + await expect(denied.deletePreset(crypto.randomUUID())).rejects.toMatchObject({status:403}); + }finally{await f.cleanup();} +}); diff --git a/packages/api/test/run-credential-repair.postgres.test.ts b/packages/api/test/run-credential-repair.postgres.test.ts index 5bcfc7ac..a0d3a294 100644 --- a/packages/api/test/run-credential-repair.postgres.test.ts +++ b/packages/api/test/run-credential-repair.postgres.test.ts @@ -34,13 +34,15 @@ describe.skipIf(!url)("run credential repair and cancellation (PostgreSQL)", () expect((await call(`/api/v1/runs/${f.runId}/stop`)).status).toBe(200); const stopped = (await f.db.pool.query("SELECT state,claim_released,vm_cleanup_complete FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId])).rows[0]; expect(stopped).toEqual({state: "stopped", claim_released: true, vm_cleanup_complete: true}); + const model=crypto.randomUUID(); + await records.write({id:model,kind:"model",name:"Repaired model",origin:null,description:null,managedModelPayload:JSON.stringify({providerUrl:"https://models.example/v1"}),expectedRevision:1,idempotencyKey:crypto.randomUUID(),operation:"upsert"}); + await f.db.pool.query("UPDATE app.triggers SET model='fixture',execution_config=$3 WHERE tenant_id=$1 AND id=$2",[f.tenantId,f.triggerIds[0],{agentKind:"pi",executionType:"agent",requiresVm:false,connectionId:"",modelAccess:"portable",modelAccountId:model,portableIntegrationIds:[replacement]}]); const invoked = await call(`/api/v1/triggers/${f.triggerIds[0]}/invocations`, {prompt: "repaired run", idempotencyKey: "repaired-future-run"}); expect(invoked.status).toBe(202); const next = await invoked.json() as {runId: string}; await scheduler.process(); - expect(launch).toHaveBeenCalledTimes(1); - expect(launch.mock.calls[0]![0].runIdentity).toEqual({backendOrigin: f.env.APP_ORIGIN}); - expect(launch.mock.calls[0]![0]).not.toHaveProperty("runProxy"); + expect(launch).not.toHaveBeenCalled(); + expect((await f.db.pool.query("SELECT state FROM app.runs WHERE tenant_id=$1 AND id=$2",[f.tenantId,next.runId])).rows[0].state).toBe("running"); const saved = (await f.db.pool.query("SELECT r.execution_config,a.scopes FROM app.runs r JOIN app.run_authorizations a ON a.tenant_id=r.tenant_id AND a.run_id=r.id WHERE r.tenant_id=$1 AND r.id=$2", [f.tenantId, next.runId])).rows[0]; expect(saved.execution_config.portableIntegrationIds).toEqual([replacement]); expect(saved.scopes).toEqual([]); diff --git a/packages/api/test/run-input-preview.postgres.test.ts b/packages/api/test/run-input-preview.postgres.test.ts index 165867b9..92374da2 100644 --- a/packages/api/test/run-input-preview.postgres.test.ts +++ b/packages/api/test/run-input-preview.postgres.test.ts @@ -35,7 +35,8 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("immutable run Source and P const skillOnly=await api.startRun(startRunInput.parse({skill}));expect((await api.getRun(skillOnly.runId)).prompt_preview).toBe(""); }); it("shows a shortened script instead of an agent prompt and preserves old rows without previews",async()=>{ - const script="printf '%s\\n' hello\n".repeat(80),receipt=await api.startRun(startRunInput.parse({script,executionConfigId:"local"})); + const script="printf '%s\\n' hello\n".repeat(80),receipt=await api.startRun(startRunInput.parse({prompt:"Historical row fixture"})); + await f.db.pool.query("UPDATE app.runs SET encrypted_prompt_preview=NULL,execution_config=execution_config||$3::jsonb WHERE tenant_id=$1 AND id=$2",[f.tenantId,receipt.runId,{executionType:"code",script}]); const item=(await api.listRuns(new URLSearchParams())).items.find((item:any)=>item.id===receipt.runId)!;expect(item.execution_type).toBe("code");expect(item.prompt_preview).toContain("printf");expect(item.prompt_preview.endsWith("…")).toBe(true);expect((await api.getRun(receipt.runId)).execution_script).toBe(script); const legacy=(await api.listRuns(new URLSearchParams())).items.find((item:any)=>item.id===f.runId)!;expect(legacy.prompt_preview).toBe("Prompt");expect(legacy.source).toBeTruthy(); }); diff --git a/packages/api/test/scope-redesign.test.ts b/packages/api/test/scope-redesign.test.ts index 9f1bad56..220e1074 100644 --- a/packages/api/test/scope-redesign.test.ts +++ b/packages/api/test/scope-redesign.test.ts @@ -24,6 +24,6 @@ describe("GEN-2418 permission boundaries", () => { expect(scope("PUT", "/api/v1/integrations/exe")).toBe("integrations:write"); expect(scope("POST", "/api/v1/triggers/{triggerId}/invocations")).toBe("runs:invoke"); expect(scope("POST", "/api/v1/runs/{runId}/kill")).toBe("runs:cancel"); - expect(scope("GET", "/api/v1/search")).toBe("triggers:read+runs:read"); + expect(scope("GET", "/api/v1/search")).toBe("skills:read+runs:read"); }); }); diff --git a/packages/api/test/search.postgres.test.ts b/packages/api/test/search.postgres.test.ts index 1abc10b8..13382f37 100644 --- a/packages/api/test/search.postgres.test.ts +++ b/packages/api/test/search.postgres.test.ts @@ -9,6 +9,7 @@ describe.skipIf(!url)("global search trigram matching (PostgreSQL)", () => { let db: Database, admin: Database; const databaseName = `search_test_${crypto.randomUUID().replaceAll("-", "")}`; const tenant = crypto.randomUUID(), otherTenant = crypto.randomUUID(); + const skill=crypto.randomUUID(); const trigger = crypto.randomUUID(), otherTrigger = crypto.randomUUID(); const run = crypto.randomUUID(), typoRun = crypto.randomUUID(), privateRun = crypto.randomUUID(); const invocation = crypto.randomUUID(), typoInvocation = crypto.randomUUID(), privateInvocation = crypto.randomUUID(); @@ -34,6 +35,9 @@ describe.skipIf(!url)("global search trigram matching (PostgreSQL)", () => { VALUES ($1,$2,$3,$4,'manual','GEN-2157','Fix punctuation in issue identifiers','Deploy GEN-2157','codex','succeeded',$11), ($1,$5,$3,$6,'manual','GEN-2158','A nearby but weaker identifier','Deploy GEN-2158','codex','succeeded',$11), ($7,$8,$9,$10,'manual','GEN-2157','Private issue','Private GEN-2157','codex','succeeded',$11)`, [tenant, run, trigger, invocation, typoRun, typoInvocation, otherTenant, privateRun, otherTrigger, privateInvocation, { agentKind: "codex", connectionId: "local" }]); + await db.pool.query("INSERT INTO app.skills(tenant_id,id,key,encrypted_body,definition) VALUES($1,$2,'release-review','encrypted',$3)",[tenant,skill,{description:"secret-description-token"}]); + await db.pool.query("INSERT INTO app.skills(tenant_id,id,key) SELECT $1,gen_random_uuid(),'bulk-'||n FROM generate_series(1,120) n",[tenant]); + await db.pool.query("UPDATE app.runs SET issue_id='HIDDEN-999' WHERE tenant_id=$1 AND id=$2",[tenant,run]); await db.pool.query(`INSERT INTO app.run_trace_events(tenant_id,run_id,sequence,id,event_type,title,preview_text) VALUES ($1,$2,1,'trace-search','assistant_message','Rollback summary','The rollback completed successfully')`, [tenant, run]); }); @@ -51,9 +55,16 @@ describe.skipIf(!url)("global search trigram matching (PostgreSQL)", () => { expect(exact[0]?.id).toBe(run); }); - it("matches a representative trigger-name typo without substring filtering", async () => { - const items = (await new OperationsRepository(db, tenant).search("deplyment")).items; - expect(items.some(item => item.kind === "trigger" && item.id === trigger)).toBe(true); + it("matches a skill-name typo and excludes trigger names", async () => { + const items = (await new OperationsRepository(db, tenant).search("releas-reveiw")).items; + expect(items.some(item => item.kind === "skill" && item.id === skill)).toBe(true); + }); + + it("bounds results, highlights names and orders repeated searches deterministically",async()=>{ + const store=new OperationsRepository(db,tenant); + const items=(await store.search("bulk")).items;expect(items).toHaveLength(100); + expect((await store.search("bulk")).items.map(item=>item.id)).toEqual(items.map(item=>item.id)); + expect((await store.search("release-review")).items[0].match.ranges.length).toBeGreaterThan(0); }); it("excludes unrelated rows and preserves tenant isolation", async () => { @@ -62,8 +73,9 @@ describe.skipIf(!url)("global search trigram matching (PostgreSQL)", () => { expect(items.every(item => item.id !== privateRun)).toBe(true); }); - it("keeps trace full-text search available", async () => { + it("excludes trace content, descriptions and issue fields", async () => { const items = (await new OperationsRepository(db, tenant).search("rollback")).items; - expect(items).toEqual(expect.arrayContaining([expect.objectContaining({ kind: "trace", id: "trace-search" })])); + expect(items).toEqual([]); + for(const query of ["deplyment","secret-description-token","HIDDEN-999","punctuation"]){expect((await new OperationsRepository(db,tenant).search(query)).items).toEqual([]);} }); }); diff --git a/packages/api/test/skill-definition.test.ts b/packages/api/test/skill-definition.test.ts new file mode 100644 index 00000000..f20d8208 --- /dev/null +++ b/packages/api/test/skill-definition.test.ts @@ -0,0 +1,20 @@ +import { expect, it } from "vitest"; +import { readSkillDefinition, writeSkillDefinition } from "../src/skill-definition"; + +it("defaults to inherited presets, unlimited concurrency and enabled", () => { + expect(readSkillDefinition("# Literal {{body}}\n", "example")).toEqual({ name: "example", description: "", factorize: { concurrency: 0, disabled: false }, markdown: "# Literal {{body}}\n" }); +}); +it("round trips controls without losing unknown metadata, comments or body", () => { + const source = '---\nname: example\ndescription: A skill\n# retain me\nlicense: MIT\nmetadata:\n other: retained\n factorize:\n custom: value\n vm-preset: old\n---\n# Body\n\n```sh\necho "$HOME"\n```\n'; + const before = readSkillDefinition(source, "example"); + const next = { ...before, factorize: { ...before.factorize, "vm-preset": undefined, "model-preset": "careful", concurrency: 0, disabled: true } }; + const saved = writeSkillDefinition(source, next); + expect(saved).toContain("# retain me"); + expect(saved).toContain("license: MIT"); + expect(saved).toContain("other: retained"); + expect(saved).toContain("custom: value"); + expect(readSkillDefinition(saved, "example")).toEqual(next); +}); +it.each(["---\n[broken\n---\n", "---\n- array\n---\n", "---\nmetadata: nope\n---\n", "---\nmetadata:\n factorize:\n vm-preset: Bad Slug\n---\n", "---\nmetadata:\n factorize:\n concurrency: -1\n---\n", "---\nmetadata:\n factorize:\n disabled: yes\n---\n", "---\nmetadata:\n factorize:\n concurrency: 2147483648\n---\n"])("rejects invalid definitions %s", source => { + expect(() => readSkillDefinition(source, "example")).toThrow(); +}); diff --git a/packages/api/test/skill-editor.postgres.test.ts b/packages/api/test/skill-editor.postgres.test.ts new file mode 100644 index 00000000..41faa964 --- /dev/null +++ b/packages/api/test/skill-editor.postgres.test.ts @@ -0,0 +1,33 @@ +import { expect,it,vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { installSkillArtifacts } from "./helpers/memory-skill-git"; +import { SkillLibrary } from "../src/skill-library"; +import { ApiService } from "../src/flow-service"; +import { readSkillDefinition } from "../src/skill-definition"; +vi.mock("../src/skill-git",()=>({withSkillGit:vi.fn()})); +vi.mock("cloudflare:workers",()=>({WorkerEntrypoint:class{},DurableObject:class{}})); +vi.mock("@cloudflare/workers-oauth-provider",()=>({OAuthProvider:class{},AuthorizationError:class extends Error{},getOAuthApi:vi.fn()})); +it.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("commits structured edits and selector autosaves to SKILL.md preserving unknown YAML and conditional revisions",async()=>{ + const f=await loadingFixture(process.env.AUTH_TEST_DATABASE_URL!); + try{ + installSkillArtifacts(f.env);await new SkillLibrary(f.env,f.tenantId).configure({kind:"managed"}); + const service=new ApiService(f.env,{...f.auth,scopes:[...f.auth.scopes,"skills:read","skills:write"]}); + const source="---\nname: structured\ndescription: Example\nlicense: MIT\nmetadata:\n retained: yes\n---\n# Hello\n"; + const skill=await service.createSkill({key:"structured",body:source}); + const vm=await service.savePreset({kind:"vm",name:"Development",slug:"development",settings:{provider:"none"}}); + const definition=readSkillDefinition(source,"structured");definition.factorize["vm-preset"]=vm.preset.slug; + const saved=await service.updateSkill(skill.id,{definition,expectedRevision:skill.revision}); + const current=await service.getSkill(skill.id); + expect(current.body).toContain("license: MIT");expect(current.body).toContain("retained: yes");expect(current.definition?.factorize["vm-preset"]).toBe("development");expect(current.definition?.markdown).toBe("# Hello\n"); + const index=(await f.db.pool.query("SELECT definition FROM app.skills WHERE tenant_id=$1 AND id=$2",[f.tenantId,skill.id])).rows[0].definition; + expect(index).not.toHaveProperty("markdown");expect(JSON.stringify(index)).not.toContain("Hello"); + const directory=await service.getSkillDirectory(skill.id); + expect(atob(directory.files.find(file=>file.path==="SKILL.md")!.content)).toBe(current.body); + expect(directory.commit).toBeTruthy(); + await expect(service.updateSkill(skill.id,{definition:{...definition,markdown:"Stale"},expectedRevision:skill.revision})).rejects.toMatchObject({status:409}); + expect((await service.getSkill(skill.id)).body).toBe(current.body); + const next=await service.updateSkill(skill.id,{definition:{...definition,description:"Updated",markdown:"# Updated",factorize:{concurrency:0,disabled:true}},expectedRevision:saved.revision}); + expect(next.definition).toMatchObject({description:"Updated",markdown:"# Updated",factorize:{concurrency:0,disabled:true}}); + expect(next.definition?.factorize["vm-preset"]).toBeUndefined(); + }finally{await f.cleanup();} +}); diff --git a/packages/api/test/skill-settings.postgres.test.ts b/packages/api/test/skill-settings.postgres.test.ts index faa8a0c6..43e54d32 100644 --- a/packages/api/test/skill-settings.postgres.test.ts +++ b/packages/api/test/skill-settings.postgres.test.ts @@ -1,86 +1,24 @@ -import { InvocationService } from "../src/job-domain"; -import { PostgresTriggerRepository } from "../src/postgres/job-repository"; -import { CredentialRepository } from "../src/postgres/credential-repository"; -import { beforeAll, afterAll, describe, expect, it, vi } from "vitest"; +import { expect,it,vi } from "vitest"; import { loadingFixture } from "./helpers/loading-fixture"; import { ApiService } from "../src/flow-service"; -import { encrypt, decrypt } from "../src/crypto"; -import { skillDefaults } from "../src/skill-settings"; +import { encrypt } from "../src/crypto"; import { protectedApiFetch } from "../src/protected-api"; vi.mock("cloudflare:workers",()=>({WorkerEntrypoint:class{},DurableObject:class{}})); vi.mock("@cloudflare/workers-oauth-provider",()=>({OAuthProvider:class{},AuthorizationError:class extends Error{},getOAuthApi:vi.fn()})); -describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("skill-owned execution defaults",()=>{ - let f:Awaited>,service:ApiService,id:string; - beforeAll(async()=>{f=await loadingFixture(process.env.AUTH_TEST_DATABASE_URL!);service=new ApiService(f.env,{...f.auth,scopes:[...f.auth.scopes,"skills:read","skills:write","runs:start"]});id=crypto.randomUUID();await f.db.pool.query("INSERT INTO app.skills(tenant_id,id,key,encrypted_body) VALUES($1,$2,'execution-skill',$3)",[f.tenantId,id,await encrypt("Skill instructions",f.env.CREDENTIAL_ENCRYPTION_KEY)]);}); - afterAll(async()=>{await f?.cleanup();}); - it("copies team settings once and validates the public boundary",async()=>{ - const initial=await service.getSkillSettings(id);expect(initial.defaults).toMatchObject({concurrencyLimit:1,requiresVm:false}); - await f.db.pool.query("UPDATE app.team_settings SET run_defaults=run_defaults||'{\"concurrencyLimit\":9}' WHERE tenant_id=$1",[f.tenantId]); - expect((await service.getSkillSettings(id)).defaults.concurrencyLimit).toBe(1); - expect(skillDefaults.safeParse({executionType:"code",script:"echo test",requiresVm:false}).success).toBe(false); - expect(skillDefaults.safeParse({vmImage:"https://registry.example/image"}).success).toBe(false); - expect(skillDefaults.safeParse({vmImage:"ghcr.io/example/image:tag"}).success).toBe(true); - const request=new Request(f.env.APP_ORIGIN+`/api/v1/skills/${id}/settings`,{method:"PUT",headers:{Origin:f.env.APP_ORIGIN,"Content-Type":"application/json"},body:JSON.stringify({expectedRevision:1,defaults:{executionType:"code",requiresVm:false}})}); - expect((await protectedApiFetch(request.clone() as typeof request,f.env,null,{} as ExecutionContext)).status).toBe(401); - expect((await protectedApiFetch(request,f.env,{...f.auth,scopes:[...f.auth.scopes,"skills:write"]},{} as ExecutionContext)).status).toBe(400); - }); - it("uses skill settings for manual and triggered scripts and pins old snapshots",async()=>{ - let settings=await service.getSkillSettings(id); - settings=await service.setSkillSettings(id,{expectedRevision:settings.revision,defaults:{executionType:"code",script:"echo first",requiresVm:true,executionConfigId:"local",vmImage:"alpine:3.22",concurrencyLimit:2,runScopes:[]}}); - const trigger=await service.createTrigger({name:"execution-trigger",skillId:id,prompt:"",events:[{kind:"manual",enabled:true,config:{}}]} as any); - expect(trigger.executionType).toBe("code");expect(trigger.skill?.id).toBe(id); - const first=await service.startRun({skill:id,idempotencyKey:"first-skill-launch"}); - const triggered=await service.invokeTrigger(trigger.id,{prompt:"",idempotencyKey:"first-triggered"}); - const config=async(runId:string)=>(await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2",[f.tenantId,runId])).rows[0].execution_config; - expect(await config(first.runId)).toMatchObject({script:"echo first",image:"alpine:3.22",runScopes:[]}); - expect(await config(triggered.runId)).toMatchObject({script:"echo first",image:"alpine:3.22"}); - settings=await service.setSkillSettings(id,{expectedRevision:settings.revision,defaults:{...settings.defaults,script:"echo second",vmImage:"alpine:3.23"}}); - const next=await service.startRun({skill:id,vmImage:"alpine:3.21",idempotencyKey:"explicit"}); - const nextTriggered=await service.invokeTrigger(trigger.id,{prompt:"",idempotencyKey:"second-triggered"}); - expect(await config(next.runId)).toMatchObject({script:"echo second",image:"alpine:3.21"}); - expect(await config(nextTriggered.runId)).toMatchObject({script:"echo second",image:"alpine:3.23"}); - expect(await config(first.runId)).toMatchObject({script:"echo first",image:"alpine:3.22"}); - await expect(service.setSkillSettings(id,{expectedRevision:1,defaults:settings.defaults})).rejects.toMatchObject({status:409}); - await expect(service.setSkillSettings(id,{expectedRevision:settings.revision,defaults:{executionType:"code",script:"echo invalid",requiresVm:false}})).rejects.toThrow(); - }); - it("applies agent model, prompt and permission defaults to both launch paths",async()=>{ - const modelId=crypto.randomUUID(); - await new CredentialRepository(f.db,f.tenantId,f.env.CREDENTIAL_ENCRYPTION_KEY).write({id:modelId,kind:"model",name:"Local model",origin:null,description:null,expectedRevision:0,idempotencyKey:crypto.randomUUID(),operation:"upsert",managedModelPayload:JSON.stringify({providerUrl:"https://models.example/v1"})}); - const current=await service.getSkillSettings(id); - await service.setSkillSettings(id,{expectedRevision:current.revision,defaults:{executionType:"agent",requiresVm:false,modelAccountId:modelId,model:"skill-model",prompt:"Skill prompt",runScopes:[],concurrencyLimit:4}}); - const direct=await service.startRun({skill:id,prompt:"Caller prompt",idempotencyKey:"agent-direct"}); - const triggerId=(await f.db.pool.query("SELECT trigger_id FROM app.trigger_skills WHERE tenant_id=$1 AND skill_id=$2",[f.tenantId,id])).rows[0].trigger_id; - const eventRun=await service.invokeTrigger(triggerId,{prompt:"",idempotencyKey:"agent-event"}); - for(const runId of [direct.runId,eventRun.runId]){ - const row=(await f.db.pool.query("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2",[f.tenantId,runId])).rows[0]; - expect(row.execution_config).toMatchObject({model:"skill-model",modelAccountId:modelId,runScopes:[]}); - } - const history=await service.listRuns(new URLSearchParams({skillId:id})); - expect(history.items.map(run=>run.id)).toEqual(expect.arrayContaining([direct.runId,eventRun.runId])); - const prompt=(await f.db.pool.query("SELECT encrypted_prompt FROM app.trigger_runs WHERE tenant_id=$1 AND id=$2",[f.tenantId,direct.runId])).rows[0].encrypted_prompt; - expect(await decrypt(prompt,f.env.CREDENTIAL_ENCRYPTION_KEY)).toBe("Skill instructions\n\nSkill prompt\n\nCaller prompt"); - }); - - it("keeps a trigger optional, enforces uniqueness, and accepts multiple event sources",async()=>{ - const optional=crypto.randomUUID();await f.db.pool.query("INSERT INTO app.skills(tenant_id,id,key,encrypted_body) VALUES($1,$2,'optional-skill',$3)",[f.tenantId,optional,await encrypt("Optional",f.env.CREDENTIAL_ENCRYPTION_KEY)]); - expect(await service.getSkillTrigger(optional)).toEqual({trigger:null}); - const ownedTrigger=await service.saveSkillTrigger(optional,{enabled:true,events:[{kind:"manual",enabled:true,config:{}}]}); - const ownedRun=await service.invokeTrigger(ownedTrigger.trigger!.id,{prompt:"",idempotencyKey:"skill-label"}); - expect((await f.db.pool.query("SELECT run_name FROM app.runs WHERE id=$1",[ownedRun.runId])).rows[0].run_name).toBe("optional-skill"); - const current=await service.getSkillTrigger(id); - expect(current.trigger?.name).toBe("execution-skill"); - await expect(service.createTrigger({name:"second-trigger",skillId:id,events:[],prompt:""} as any)).rejects.toMatchObject({status:409}); - const saved=await service.saveSkillTrigger(id,{expectedUpdatedAt:current.trigger!.updatedAt,enabled:true,events:[{kind:"manual",slug:"manual",enabled:true,config:{}},{kind:"schedule",slug:"hourly",enabled:true,config:{cron:"0 * * * *",timezone:"UTC"}}]}); - expect(saved.trigger!.events).toHaveLength(2); - expect(saved.trigger!.skillId).toBe(id); - expect(saved.trigger!.name).toBe("execution-skill"); - await f.db.pool.query("UPDATE app.skills SET key='renamed-execution' WHERE tenant_id=$1 AND id=$2",[f.tenantId,id]); - expect((await service.getSkillTrigger(id)).trigger?.name).toBe("renamed-execution"); - const manual=await service.invokeTrigger(saved.trigger!.id,{prompt:"",idempotencyKey:"multi-event"}); - expect((await f.db.pool.query("SELECT launch_skill_id FROM app.runs WHERE id=$1",[manual.runId])).rows[0].launch_skill_id).toBe(id); - const event=saved.trigger!.events.find(event=>event.kind==="schedule")!; - const scheduled=await new InvocationService(new PostgresTriggerRepository(f.db,f.tenantId,value=>encrypt(value,f.env.CREDENTIAL_ENCRYPTION_KEY),value=>decrypt(value,f.env.CREDENTIAL_ENCRYPTION_KEY)),value=>encrypt(value,f.env.CREDENTIAL_ENCRYPTION_KEY)).invoke(saved.trigger!.id,{source:"schedule",claimKey:"scheduled-skill-event",eventId:event.id,context:{[event.slug]:{}}}); - expect((await f.db.pool.query("SELECT launch_skill_id FROM app.runs WHERE id=$1",[scheduled.run.id])).rows[0].launch_skill_id).toBe(id); - }); - +it.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("reads effective preset settings and rejects the retired execution-settings mutation",async()=>{ + const f=await loadingFixture(process.env.AUTH_TEST_DATABASE_URL!); + try{ + const service=new ApiService(f.env,{...f.auth,scopes:[...f.auth.scopes,"skills:read","skills:write"]}),id=crypto.randomUUID(); + await f.db.pool.query("INSERT INTO app.skills(tenant_id,id,key,encrypted_body,encrypted_prompt) VALUES($1,$2,'effective-settings',$3,$4)",[f.tenantId,id,await encrypt("Instructions",f.env.CREDENTIAL_ENCRYPTION_KEY),await encrypt("Saved prompt",f.env.CREDENTIAL_ENCRYPTION_KEY)]); + const initial=await service.getSkillSettings(id);expect(initial.defaults).toMatchObject({executionType:"agent",prompt:"",requiresVm:false}); + expect((await service.getSkill(id)).definition?.markdown).toBe("Instructions\n\nSaved prompt"); + const model=(await service.listPresets()).presets.find(p=>p.kind==="model")!; + await service.savePreset({kind:"model",name:model.name,slug:model.slug,settings:{model:"updated-model"},expectedRevision:model.revision},model.id); + expect((await service.getSkillSettings(id)).defaults.model).toBe("updated-model"); + await expect(service.setSkillSettings(id,{expectedRevision:initial.revision,defaults:{prompt:"Old mutation"}})).rejects.toMatchObject({status:410,code:"settings_retired"}); + const request=()=>new Request(f.env.APP_ORIGIN+`/api/v1/skills/${id}/settings`,{method:"PUT",headers:{Origin:f.env.APP_ORIGIN,"Content-Type":"application/json"},body:JSON.stringify({expectedRevision:1,defaults:{}})}); + expect((await protectedApiFetch(request(),f.env,null,{} as ExecutionContext)).status).toBe(401); + expect((await protectedApiFetch(request(),f.env,{...f.auth,scopes:["skills:write"]},{} as ExecutionContext)).status).toBe(403); + expect((await protectedApiFetch(request(),f.env,{...f.auth,scopes:[...f.auth.scopes,"skills:write"]},{} as ExecutionContext)).status).toBe(410); + }finally{await f.cleanup();} }); diff --git a/packages/api/test/skill-table.postgres.test.ts b/packages/api/test/skill-table.postgres.test.ts new file mode 100644 index 00000000..ec616b2b --- /dev/null +++ b/packages/api/test/skill-table.postgres.test.ts @@ -0,0 +1,26 @@ +import { expect,it,vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { ApiService } from "../src/flow-service"; +import { encrypt } from "../src/crypto"; +import { readSkillDefinition,writeSkillDefinition } from "../src/skill-definition"; +vi.mock("cloudflare:workers",()=>({WorkerEntrypoint:class{},DurableObject:class{}})); +vi.mock("@cloudflare/workers-oauth-provider",()=>({OAuthProvider:class{},AuthorizationError:class extends Error{},getOAuthApi:vi.fn()})); +it.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("lists descriptions and preset references without bodies and counts disabled non-manual events",async()=>{ + const f=await loadingFixture(process.env.AUTH_TEST_DATABASE_URL!); + try{ + const service=new ApiService(f.env,{...f.auth,scopes:[...f.auth.scopes,"skills:read"]});await service.listPresets(); + for(const [i,key] of ["no-trigger","manual-only","disabled-automation"].entries()){ + const id=crypto.randomUUID(),definition=readSkillDefinition("Body secret",key);definition.description="Description "+key; + await f.db.pool.query("INSERT INTO app.skills(tenant_id,id,key,definition,encrypted_body) VALUES($1,$2,$3,$4,$5)",[f.tenantId,id,key,definition,await encrypt(writeSkillDefinition("",definition),f.env.CREDENTIAL_ENCRYPTION_KEY)]); + if(i>0)await f.db.pool.query("INSERT INTO app.trigger_skills(tenant_id,trigger_id,skill_id,position) VALUES($1,$2,$3,0)",[f.tenantId,f.triggerIds[i],id]); + if(i===1)await f.db.pool.query("DELETE FROM app.events WHERE tenant_id=$1 AND trigger_id=$2 AND kind<>'manual'",[f.tenantId,f.triggerIds[i]]); + if(i===2){await f.db.pool.query("UPDATE app.events SET enabled=false WHERE tenant_id=$1 AND trigger_id=$2",[f.tenantId,f.triggerIds[i]]);await f.db.pool.query("UPDATE app.triggers SET enabled=false WHERE tenant_id=$1 AND id=$2",[f.tenantId,f.triggerIds[i]]);} + } + const page=await service.listSkills({q:"",limit:100}); + expect(Object.fromEntries(page.items.map(s=>[s.key,s.hasTriggers]))).toEqual({"no-trigger":false,"manual-only":false,"disabled-automation":true}); + expect(page.items.every(s=>s.description===`Description ${s.key}`)).toBe(true); + expect(JSON.stringify(page)).not.toContain("Body secret"); + const small=await service.listSkills({q:"",limit:1});expect(small.nextCursor).toBeTruthy(); + const next=await service.listSkills({q:"",limit:1,cursor:small.nextCursor!});expect(next.items[0].id).not.toBe(small.items[0].id); + }finally{await f.cleanup();} +}); diff --git a/packages/api/test/trigger-context.postgres.test.ts b/packages/api/test/trigger-context.postgres.test.ts index 37f84041..09ee9132 100644 --- a/packages/api/test/trigger-context.postgres.test.ts +++ b/packages/api/test/trigger-context.postgres.test.ts @@ -56,7 +56,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("Trigger context contract a const receipt=await invoked.json() as any; const row=(await f.db.pool.query("SELECT encrypted_prompt,encrypted_skill_snapshot,run_name FROM app.trigger_runs WHERE tenant_id=$1 AND id=$2",[f.tenantId,receipt.runId])).rows[0]; expect(await decrypt(row.encrypted_prompt,f.env.CREDENTIAL_ENCRYPTION_KEY)).toBe(body+"\n\nBase {{literal}}\n\nSelected 7\n\nCaller {{literal}}");expect(row.run_name).toBe("Name 7"); - expect(JSON.parse(await decrypt(row.encrypted_skill_snapshot,f.env.CREDENTIAL_ENCRYPTION_KEY))).toMatchObject([{id:skillId,body}]); + expect(JSON.parse(await decrypt(row.encrypted_skill_snapshot,f.env.CREDENTIAL_ENCRYPTION_KEY))).toMatchObject([{id:skillId,body:expect.stringContaining(body)}]); expect((await f.db.pool.query("SELECT skill_id FROM app.trigger_skills WHERE tenant_id=$1 AND trigger_id=$2",[f.tenantId,trigger.id])).rows).toEqual([{skill_id:skillId}]); }); it("rejects empty effective invocation input without queuing or waking a VM and supports skill-only direct runs",async()=>{ diff --git a/packages/api/test/workspace-vm.postgres.test.ts b/packages/api/test/workspace-vm.postgres.test.ts index f5d7f152..363d0006 100644 --- a/packages/api/test/workspace-vm.postgres.test.ts +++ b/packages/api/test/workspace-vm.postgres.test.ts @@ -53,8 +53,10 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("optional, bound workspace it("fails explicit and selected Team defaults without fallback or a model turn",async()=>{ const count=modelRequests; await expect(service.startRun(startRunInput.parse({prompt:"Work",executionConfigId:"absent"}))).rejects.toMatchObject({status:400}); - await f.db.pool.query("UPDATE app.team_settings SET run_defaults=run_defaults||'{\"requiresVm\":true}'::jsonb WHERE tenant_id=$1",[f.tenantId]); + const defaultVm=(await service.listPresets()).presets.find(p=>p.kind==="vm"&&p.isDefault)!; + await f.db.pool.query("UPDATE app.presets SET settings=$3,revision=revision+1 WHERE tenant_id=$1 AND id=$2",[f.tenantId,defaultVm.id,{provider:"exe",connectionId:"absent",executionConfigId:"absent",image:"",tags:[]}]); await expect(service.startRun(startRunInput.parse({prompt:"Work"}))).rejects.toMatchObject({status:400}); + await f.db.pool.query("UPDATE app.presets SET settings=$3,revision=revision+1 WHERE tenant_id=$1 AND id=$2",[f.tenantId,defaultVm.id,{provider:"none"}]); const run=await launch({executionConfigId:"local"}),vm=new WorkspaceVm(f.db,f.env,async()=>adapter([],true)); await expect(vm.ensure(run)).rejects.toThrow("Selected VM");expect((await vm.row(f.tenantId,run.id))!.status).toBe("failed");expect(modelRequests).toBe(count); await vm.cleanup(f.tenantId,run.id); diff --git a/packages/app/src/features/jobs/editor.tsx b/packages/app/src/features/jobs/editor.tsx index 8c0ee88a..dcb64940 100644 --- a/packages/app/src/features/jobs/editor.tsx +++ b/packages/app/src/features/jobs/editor.tsx @@ -127,7 +127,7 @@ function EditorForm({ initial, defaults, section }: { initial?: Trigger; default
{ e.preventDefault(); save.mutate(draft); }}>
- {show("general") &&

General

Choose a unique name shared with team skills. Use lowercase letters, digits, and single hyphens.

+ {show("general") &&

General

Choose a unique name shared with team skills. Use lowercase letters, digits, and single hyphens.

Model and capacity

{(draft.executionType ?? "agent") === "agent" && <> }
{initial && { savingNavigation.current = true; }} />}
}{show("vm") &&

VM

Pi runs in Factorize. Enable a remote workspace when the task needs a VM. Scripts require a VM.

item.id)} apply={applyPreset} /> diff --git a/packages/app/src/features/jobs/trigger-editor.tsx b/packages/app/src/features/jobs/trigger-editor.tsx index 4fba0c94..6bd4f7e2 100644 --- a/packages/app/src/features/jobs/trigger-editor.tsx +++ b/packages/app/src/features/jobs/trigger-editor.tsx @@ -25,7 +25,7 @@ function ScheduleFields({ event, onChange }: { event: Extract preview.mutate()}>Preview schedule {preview.data &&

Next run: {preview.data.nextRunAt}

}{preview.error &&

{preview.error.message}

}; } -export function EventEditor({ events, onChange, onValidityChange }: { events: Event[]; onChange: (value: Event[]) => void; onValidityChange?: (invalid: boolean) => void }) { +export function EventEditor({ events, onChange, onValidityChange,addLabel="Add event" }: { addLabel?:string; events: Event[]; onChange: (value: Event[]) => void; onValidityChange?: (invalid: boolean) => void }) { const availability = useQuery(availabilityQuery), [kind, setKind] = useState("schedule"); const replace = (index: number, value: Event) => onChange(events.map((item, i) => i === index ? value : item)); return @@ -42,6 +42,6 @@ export function EventEditor({ events, onChange, onValidityChange }: { events: Ev {event.kind !== "manual" && }
)} - +
; } diff --git a/packages/app/src/features/search/dialog.tsx b/packages/app/src/features/search/dialog.tsx index ef89f52f..7d70c08c 100644 --- a/packages/app/src/features/search/dialog.tsx +++ b/packages/app/src/features/search/dialog.tsx @@ -18,19 +18,19 @@ export default function SearchDialog({ close }: { close: () => void }) { useEffect(() => { const previous = document.activeElement as HTMLElement | null; dialog.current?.showModal(); dialog.current?.querySelector("input")?.focus(); return () => { dialog.current?.close(); previous?.focus(); }; }, []); useEffect(() => { const timer = window.setTimeout(() => { setQuery(text.trim()); setSelected(0); }, 120); return () => window.clearTimeout(timer); }, [text]); const results = useQuery({ queryKey: ["search", q], enabled: !!q, queryFn: async ({ signal }) => { const { data, error } = await api.GET("/api/v1/search", { signal, params: { query: { q } } }); if (!data || error) throw new Error(messageOf(error)); return data; }, placeholderData: previous => previous, staleTime: 15_000, retry: 1 }); - const currentText = text.trim(), queryCurrent = currentText === q, items = currentText ? (results.data?.items ?? []) : []; + const currentText = text.trim(), queryCurrent = currentText === q && !results.isPlaceholderData, items = currentText ? (results.data?.items ?? []) : []; useEffect(() => { setSelected(0); }, [q, results.data]); useEffect(() => { dialog.current?.querySelector(`#search-result-${selected}`)?.scrollIntoView({ block: "nearest" }); }, [selected, results.data]); - const choose = (index: number) => { if (!queryCurrent) return; const item = items[index]; if (!item) return; close(); if (item.kind === "trigger") void navigate({ to: "/triggers/$triggerId", params: { triggerId: item.id } }); else void navigate({ to: "/runs/$runId", params: { runId: item.source.id }, search: { after: 0 } }); }; - return { if (e.target === e.currentTarget) close(); }} className="w-[min(92vw,42rem)] h-[min(36rem,80dvh)] overflow-hidden"> + const choose = (index: number) => { if (!queryCurrent) return; const item = items[index]; if (!item) return; close(); if (item.kind === "skill") void navigate({ to: "/skills/$skillId", params: { skillId: item.id } }); else void navigate({ to: "/runs/$runId", params: { runId: item.source.id }, search: { after: 0 } }); }; + return { if (e.target === e.currentTarget) close(); }} className="w-[min(92vw,42rem)] h-[min(36rem,80dvh)] overflow-hidden">
-

Search