diff --git a/TODO.md b/TODO.md index ae6b4d39..6452ff90 100644 --- a/TODO.md +++ b/TODO.md @@ -1,218 +1,119 @@ -# Implementation work +# Skill-centered teams implementation -## Working instructions +## Instructions -Implement these items from top to bottom. Complete one item, verify every acceptance criterion, check its boxes, then move to the next item. Keep implementation details and evidence here. Acceptance must be executable by an agent in this VM using isolated PostgreSQL, local services, deterministic provider/VM fixtures, and browser automation. Live deployments, third-party approval, and human actions are not acceptance prerequisites. Preserve existing data. Replace the managed-agent implementation cleanly and retire the old public contracts. Keep historical traces readable. Do not create Linear issues as part of this implementation. +I want you to tackle each item one at a time from top to bottom. complete the item to completion, and when the acceptance criteria passes then check the box and move to the next item. -Run focused checks for each item and the complete root suite after the final code change before handoff, using Node 24.12.0 and npm 11.19.0. Use the documented validation runner and isolated local database. New API operations require authorization, validation, OpenAPI, generated client updates, and boundary tests. Record incomplete work honestly and never check a criterion based only on code inspection. +Don't stop until all items are complete. -## 1. Personal team ownership +Check acceptance criteria only after local verification passes. Record evidence below each item. Use isolated PostgreSQL, Chromium, and deterministic service fixtures; no production database or live providers. Runs remains Runs. -Reuse tenant/membership records as personal teams. Provision a team automatically for each new user. Retire Factorize project CRUD, project navigation/filtering, and personal execution defaults. Move existing project contents under the owning team without deleting jobs, runs, skills, integrations, or historical artifacts. Preserve provider-specific project identifiers. Team settings exist before provider setup and may initially lack execution configuration. Migrate defaults deterministically and expose missing settings as actionable failures. Team invitations and switching are future work. +## 1. Required usernames and profile settings -- [x] Local signup/verification creates exactly one personal team and settings, including retries. -- [x] Migration fixtures with multiple projects and personal defaults preserve all resource IDs/history under the correct team and select deterministic team defaults. -- [x] REST/MCP and browser entry points expose team ownership and settings, reject cross-team access, and no longer expose Factorize project CRUD or personal defaults. -- [x] Full root validation passes and evidence is recorded. +Implementation: Require globally unique usernames of 3–39 lowercase letters/numbers, separated by single hyphens. Normalize uppercase. Collect at signup; accept username or email with password at login. Add Profile to account settings. Backfill existing users from their email prefix; fail with a diagnostic for invalid/colliding prefixes. Enforce uniqueness in PostgreSQL, including concurrent writes. Add authorized, validated public API operations and regenerate contracts. -### Item 1 evidence +Acceptance: +- [x] Signup requires a valid username; format, length, normalization, and duplicate handling pass local tests. +- [x] Email and username login both work with the password. +- [x] Profile allows username changes and rejects invalid/duplicate values, including concurrent claims. +- [x] Migration backfills email prefixes and diagnoses invalid/colliding values. -Completed on 2026-11-20. Migration 0067 creates shared Team settings and migrates deterministic defaults. Migration 0068 removes project requirements, preserves historical project associations as provenance, removes ineffective cross-project grants, migrates Team scopes, and creates personal teams for accounts without ownership. Existing membership roles remain intact. New jobs and runs require no project records. Personal/project default APIs, project CRUD/MCP tools, navigation, selectors, and filters are retired. Session metadata exposes the team. +Evidence: 63 targeted PostgreSQL/API/auth tests and 12 Chromium auth/profile tests passed in the pinned image; application build passed. -The complete root npm test passed using the pinned validation image, Node 24.12.0, npm 11.19.0, and isolated PostgreSQL on port 55437. Backend tests passed 724 with 5 skipped, compiled page/API tests passed 40, browser tests passed 95 with 1 skipped plus all 6 functional tests, and runtime/proxy/Docker lanes passed. Evidence is in /tmp/item1-verified.log. Migration fixtures preserve jobs and terminal runs from multiple projects, maintain team isolation, and prune ineffective grants before flattening. Old project-specific UI tests were replaced with flat-dashboard coverage while independent graph geometry tests remain. +## 2. Personal team identity and header -## 2. Canonical Triggers and Events +Implementation: Personal team names equal owner usernames, with no independent editor. Rename atomically with username changes. Show bee and team name in the shared header; team name navigates to Skills. -Rename jobs to Triggers and activation rules to Events throughout persistence, domain contracts, REST, MCP, scopes, generated clients, and docs. A Trigger owns Events, concurrency, permissions, and history. Invocation and lifecycle relationships work across the team. Remove compatibility aliases. Preserve only previously effective permission edges during flattening. +Acceptance: +- [x] Browser verifies team name and Skills destination. +- [x] Profile rename updates team/header after navigation and reload. +- [x] Rejected rename changes neither username nor team name. -- [x] Local contract tests exercise Trigger/Event CRUD, Event firing, concurrency, tenant isolation, invocation permissions, and lifecycle relationships. -- [x] Old job operations/scopes are absent and migration tests preserve effective authorization without activating formerly invalid edges. -- [x] Full root validation passes and evidence is recorded. +Evidence: PostgreSQL username/team atomicity and immutable-name assertions passed; all 12 Chromium auth/profile/header tests passed. -### Item 2 evidence +## 3. Team Settings layout and Git configuration -Migration 0069 renames application tables and columns to Triggers and Events while preserving IDs, separates outbox delivery IDs from Event IDs, refreshes PostgreSQL functions and affected indexes, migrates event kinds/configuration/context envelopes and effective stored grants, and keeps webhook/caller payloads intact. Stored encrypted template references are upgraded on read. The public API, MCP operations, frontend routes, generated contract, and product docs use Trigger/Event names. Old job routes and scopes are rejected. Legacy flow/write grant expansion is removed from live authorization and applied only to stored grants during migration. Historical pre-0052 credential-cutover tests retain their original schema fixture. +Implementation: Reuse account-settings layout with VM, Permissions, Skills sidebar. Default /settings to VM. VM owns execution/model/concurrency defaults and presets; Permissions owns scopes/integration access/destinations; Skills owns existing repository selection/folder/sync controls, removed from Skills list. Save subpages independently without overwriting others. -Completed on 2026-11-20. The complete root npm test passed with the required pinned toolchain and isolated PostgreSQL. All 726 backend tests passed (5 skipped), all 40 compiled frontend/API tests passed, and browser, proxy, runtime, and Docker lanes passed. Evidence is in /tmp/item2-final.log. Historical artifact-kind migration preserves object keys. The archived rollback anchor is tested against its original page contract. +Acceptance: +- [x] Direct links and active selection work for all subpages on desktop/mobile. +- [x] Saving each section preserves other settings. +- [x] Repository configuration/sync work with local fixtures and appear only under Team Settings. -## 3. Dashboard Triggers table and graph +Evidence: application build and three compiled Chromium Skills/settings tests passed, covering desktop/mobile saves and repository replacement/sync fixtures. -Add dashboard Triggers subnavigation. Reuse the jobs table with name, enabled state, and running count/limit. Move the project graph to the team-wide Triggers page and show cross-former-project relationships. Both views open Trigger detail. +## 4. Skill-owned execution settings -- [x] Browser tests create and open Triggers from both table and graph, including empty/loading/error states and mobile navigation. -- [x] Focused checks pass and evidence is recorded. The complete root suite is required in item 15. +Implementation: Skills own agent/script mode, VM/model, permissions, prompt, and concurrency. New skills copy team defaults. Manual and triggered launches use saved skill defaults with supported explicit overrides. Existing runs retain immutable launch snapshots. -### Item 3 evidence +Acceptance: +- [x] New skills copy team defaults; later skill changes govern future manual and triggered launches. +- [x] Supported explicit overrides take precedence. +- [x] Agent/script modes work; scripts require a VM. +- [x] Changing skill settings does not mutate existing run snapshots. -Completed on 2026-11-20. The dashboard Triggers page has URL-persisted Table and Graph views, a shared Create trigger action, and recoverable list/graph errors. The graph covers the entire team and opens the same Trigger details as the table. Browser checks passed 26 tests with 1 stress test skipped, including mobile create/open from both views, grouped edges, cyclic routes, touch gestures, loading, errors, retry, and empty states. All 4 graph API checks passed and package boundaries passed. Evidence is in /tmp/item3-browser-final.log, /tmp/item3-api-final.log, and /tmp/item3-boundaries.log. The app build passed. Final root validation remains required in item 15. +Evidence: seven PostgreSQL execution/default tests passed for agent/script manual and triggered launches, explicit overrides, optimistic writes, and immutable existing snapshots. Skill settings API/client generated. -## 4. Shared skill and Trigger names +## 5. One optional trigger per skill -Use MCP Skills naming rules. Replace Trigger name/slug/description with one name. Enforce one team-wide namespace across skills and Triggers and reserve manual. Cover edits, concurrent creates, and Git imports. Reject invalid imports atomically and retain the last published library. +Implementation: Enforce at most one trigger per skill, retaining multiple event sources per trigger. Skill Settings > Trigger owns events and enabled state. No independent trigger name or skill selector in UI. Derive display labels from owning skill; preserve trigger IDs and workflow links internally and external API/MCP compatibility. -- [x] Local tests cover valid/invalid names, cross-resource collisions, concurrent writes, renames, and conflicting Git imports without partial publication. -- [x] Focused checks pass and evidence is recorded. The complete root suite is required in item 15. +Acceptance: +- [x] Database/API reject a second trigger for one skill; skills without triggers work. +- [x] Multiple event sources launch the owning skill correctly. +- [x] Skill rename updates trigger display labels; trigger UI has no independent name or skill picker. -### Item 4 evidence +Evidence: four PostgreSQL skill settings/ownership scenarios and four Chromium Skills/settings scenarios passed; backend/frontend type checks and build passed. Legacy ownership links are explicitly staged for item 6 conversion before the final constraint. -Completed on 2026-11-20. Trigger REST/MCP inputs and responses expose one name, with slug/description inputs rejected. Skills and Triggers follow Agent Skills naming rules and reserve manual. Migration 0070 adds a shared transactional namespace, normalizes legacy names without deleting resources, preserves artifact pointers/history, and records previous names in configuration diagnostics. PostgreSQL uniqueness guards raw writes and concurrent creates. Skill imports validate the complete candidate library and Trigger collisions before remote writes or publication. +## 6. Preserve existing context during migration -The 4 naming boundary/concurrency checks passed, as did Git publication and migration checks. The broad backend run passed 112 files and exposed outdated fixtures in two files; their corrected lifecycle/scope rerun passed all 28 tests (/tmp/item4-scope-lifecycle-final.log). All 5 migration checks passed (/tmp/item4-migration-lifecycle.log), including a legacy cross-resource collision with retained IDs/history. The editor/Triggers browser rerun passed 46 tests with 1 stress test skipped (/tmp/item4-browser-final.log). TypeScript, app build, and contract generation passed. Final complete root validation is still required in item 15. +Implementation: Create a new skill for each existing trigger using prompt and execution settings. Preserve attached skill instructions/files, event templates, existing skills, trigger identities/relationships, and historical runs. Do not reinterpret event-template context or discard inputs. Keep migration-created skills across upstream syncs until published, and preserve supporting files when their instructions are edited. -## 5. Team defaults and settings layout +Acceptance: +- [x] Fixtures cover prompt-only, attached-skill, event-template, and script triggers. +- [x] Instructions/files survive and event templates stay unchanged. +- [x] Trigger relationships and historical run readability survive migration. -Store model-provider, VM, capacity, and permission defaults in Team settings. Copy concrete defaults into newly created Triggers and allow overrides. Default edits affect future Triggers and direct runs. Rename Execution to VM. Put provider credentials beside scopes and allowed destinations in Permissions. Keep model settings outside VM. Direct MCP defaults are bounded by caller grants and explicit unauthorized requests fail. +Evidence: context migration fixtures passed for prompts, shared attached directories, templates, scripts, workflow grants, history and provenance. Five skill-settings/library integration scenarios also passed. -- [x] API/browser tests cover seeding, overrides, explicit empty permissions, caller bounds, default edits, missing configuration errors, and settings layout. -- [x] Focused checks pass and evidence is recorded. The complete root suite is required in item 15. +## 7. Skill pages, list, and workflow graph -### Item 5 evidence +Implementation: Team tabs become Skills, Runs, Integrations, Settings. Skill header is bee team / skill-name; subnav Overview, Runs, Settings. Settings sidebar General, VM, Permissions, Trigger. Overview shows instructions, directory browser, Start run; Runs includes manual/triggered runs. Remove obsolete breadcrumbs/usage labels. Improve searchable Skills list with trigger/latest-run/update information; retain trigger graph as Skills graph view. Redirect legacy trigger pages/settings to owning skill. -Completed on 2026-11-20. Migration 0071 defines initial Team capacity and permission defaults while retaining existing selections. New Triggers copy current VM/model/concurrency/scope/credential/destination settings, with explicit empty overrides preserved. Unchanged default fields are omitted by the creation form so the backend resolves current defaults. Existing Triggers retain their saved settings. Missing/unavailable VM settings and removed default destinations fail before a partial Trigger is committed. Provider credentials and allowed destinations are under Permissions, model/capacity are in General, and the canonical VM section rejects the retired Execution path. +Acceptance: +- [x] Direct links, selected tabs, headers, skill history, and legacy redirects pass browser tests. +- [x] List search/statuses and Start run operate correctly. +- [x] Existing workflow graph edges and trigger controls remain functional. -Direct runs intersect defaults with caller scopes and integrations. Destination grants are snapshotted and delegated grants cannot exceed the active parent. Local tests cover allowed/denied invocation and revocation. The broad backend pass had 737 passing tests and one outdated request-parser expectation, which passed after correction in /tmp/item5-last-checks.log. All 7 Team default/authority cases passed, along with direct defaults and manual permission checks (20 tests total in /tmp/item5-authority-verified.log). The refreshed database passed all 5 queue checks, including shared Team capacity (/tmp/item5-queue-final.log). The main browser pass had 56 passing tests and one script-label collision; the corrected script and new defaults/layout cases passed (/tmp/item5-ui-verified.log). TypeScript, app build, generation, boundaries, and diff whitespace checks passed. Final complete root validation remains in item 15. +Evidence: six compiled Chromium scenarios passed, including mobile navigation, skill defaults, both history sources, legacy redirects and graph controls/edges. Eight backend settings/history/graph tests passed. -## 6. Context and Event templates +## 8. Directory browsing and content caching -Agent Triggers have one optional skill and one optional prompt. Each Event has an optional Mustache template. Compose Trigger prompt, rendered Event text, and manual caller instructions in order. Missing templates contribute nothing. Full objects remain available through expressions such as {{webhook}}. Run-name templates see all structured Event data. Provide previews. Skill-only runs are valid. Empty skill and effective prompt fail before provisioning. Scripts retain their script editor. +Implementation: Persistent, encrypted published-directory cache keyed by tenant/repository/immutable commit; browser caching for navigation. Directory tree and read-only file viewer, explicit binary handling, existing instructions editor. Save/sync chooses new revision; cached revision stays readable during refresh failure with notice. Preserve historical versions and tenant isolation. -- [x] Tests exercise skill-only, prompt-only, Event-only, manual instructions, full-object interpolation, missing templates, run-name data access, previews, and empty-input rejection. -- [x] Focused checks pass and evidence is recorded. The complete root suite is required in item 15. +Acceptance: +- [x] Instrumented Git fixture proves repeated cached revision reads add no Git fetches. +- [x] Save/sync shows new revision while historical snapshots remain unchanged. +- [x] Nested files, invalid paths, binary files, tenant isolation, and refresh failure pass tests. -### Item 6 evidence +Evidence: four PostgreSQL cache/library scenarios passed, including counted fetches, encrypted storage, old/new commits, tenant isolation, invalid paths and upstream failure. Seven Chromium Skills/directory scenarios passed. -Completed on 2026-11-20. One optional skill and a literal optional prompt replace multi-skill/template context. Each Event owns its optional Mustache template; missing templates contribute no payload, manual text appends last, and full normalized webhook objects require explicit selection. Run-name rendering retains structured Event data. REST/MCP previews use the same composition. Empty effective input fails before queueing or provisioning. Migration 0072 preserves original ciphertext, multi-skill links, and accepted run snapshots; affected Triggers require explicit context review before re-enabling. +## 9. Team Runs navigation and filter cleanup -All 22 context and migration checks passed (/tmp/item6-context-final.log), including persisted snapshots, scope and Team isolation, retired-field rejection, full objects, and skill-only direct runs. All 24 editor browser checks passed (/tmp/item6-editor-final.log), including optional prompt, Event templates, escaped previews, and scripts. The earlier dashboard/runs/editor browser pass had 67 passing tests and one stress skip. API/app TypeScript, app build, contract generation, and whitespace checks passed. Final complete root validation remains required in item 15. +Implementation: Run detail/full trace reuse team header/subnav with Runs selected, regardless of launch source. Remove trigger breadcrumb and team-table Skill filter. Retain Start run skill selection and skill-filtered links. -The broad backend pass found outdated manual-invocation expectations and a duplicated skill-selection dependency. The relational selection is now authoritative; all 10 affected checks passed in /tmp/item6-last-fixtures.log. The broad pass had 744 other passing tests and 5 skips. +Acceptance: +- [x] Manual/triggered run detail and full trace show team navigation with Runs selected. +- [x] Trigger breadcrumb and table Skill dropdown are absent. +- [x] Start run skill selection and skill-filtered history remain functional. -## 7. MCP Skills extension +Evidence: all 24 compiled Chromium Runs scenarios passed, including manual/triggered detail/full trace, run switching, skill-filtered links and Start run selection. -Use the official extension and publish all active team skills and supporting files. Authorize discovery and reads. Cover editor/Git changes, rename/delete, pagination, and failed publication. Keep skill metadata independent of VM configuration. Follow the framework and extension specification for supported files and metadata. +## Final validation -- [x] A local MCP client discovers and reads an entire skill package and observes publication changes with cross-team reads denied. -- [x] Focused checks pass and evidence is recorded. The complete root suite is required in item 15. +- [x] Regenerate OpenAPI/client; check package boundaries. +- [x] Complete root npm test suite passes in pinned validation image with isolated local database, after final code change. -### Item 7 evidence +Validation environment: Node 24.12.0 and npm 11.19.0 in the pinned Factorize validation runner image from `docs/factorize-validation-runner.md`. Dependencies installed with `npm ci`. All database checks use isolated loopback PostgreSQL databases; provider, Git, email and VM behaviors are covered with local deterministic fixtures. -Completed on 2026-11-20. Modern MCP discovery declares the official Skills extension. skills/list pages complete manifests; skills/get and resources/read authorize every request and validate canonical Team-prefixed URIs. Manifests contain exact SHA-256 digests and byte lengths for SKILL.md and supporting files. Literal legacy bodies receive a published frontmatter wrapper; author metadata and binary bytes are retained. Invalid metadata and oversized/duplicate manifests fail publication before remote writes. Git failures preserve the last valid publication. Skill metadata does not depend on a VM. - -All package, modern MCP, Git transport, and publication checks passed (11 tests across /tmp/item7-tests.log and /tmp/item7-boundary-final.log, with the initial HTTP-header fixture corrected). Coverage includes discovery, pagination, complete package reads and digests, edits/rename/delete, cross-Team denial, revoked membership/scopes, malformed paths, binary content, and rejected Git metadata. API TypeScript, Worker dry-run bundle, generated docs, and docs validation passed (/tmp/item7-types-verified.log, /tmp/item7-bundle.log, /tmp/item7-docs-final.log). Final complete root validation remains in item 15. - -## 8. Hosted Pi and PostgreSQL sessions - -Bundle a pinned Pi framework in the Factorize build as the sole managed agent. Remove in-VM Pi/Codex/Claude launch paths. Keep scripts as VM workloads. Configure an OpenAI-compatible base URL, model, and optional credential through integrations. Use PostgreSQL for messages, checkpoints, tool call/results, session metadata, and run state. Reuse framework streaming, compaction, and lifecycle behavior. Determine the compatible execution host from framework runtime requirements while preserving Worker infrastructure identity. - -- [x] A deterministic local OpenAI-compatible server drives a real bundled Pi turn, streaming, errors, compaction, cancellation, and session recovery from PostgreSQL after restart. -- [x] Managed-agent launches contain no guest harness dependency; retained historical traces remain readable. -- [x] Focused checks pass and evidence is recorded. The complete root suite is required in item 15. - -### Item 8 evidence - -Completed on 2026-11-20. Pi Agent Core and Pi AI 1.5.2 are pinned in the Factorize build. Scheduler-managed agents initialize hosted PostgreSQL sessions and never construct a guest agent backend. Scripts retain VM execution. The new model integration contract takes an OpenAI-compatible provider URL, optional key, and context/output limits; it exposes safe metadata and retires device authorization, native/portable model selection and managed harness selection. Models are independent of VM catalogs. VM connection setup and image verification no longer probe guest agent CLIs or models. Historical guest launch fixtures are test-only; historical trace parsers and retained rows remain readable. - -Migration 0073 adds encrypted session/checkpoint and streaming event persistence, tool-call records, lease epochs, and compaction/turn metadata. It preserves historical run configurations and records retired Team/Trigger agent choices as diagnostics. The framework owns provider streaming, tool validation/execution, and cancellation. Framework model calls provide checkpointed compaction while retaining original events. Live message projections use the existing trace table. Provider credentials are resolved per turn and excluded from error traces. - -The local real-Pi/OpenAI-compatible server and provider API pass had 11 passing checks (/tmp/item8-core-final.log), covering authenticated and keyless streaming, errors, tool continuation in a fresh harness, compaction, cancellation, competing/expired leases, and scheduler launch without guest dependencies. The broader focused pass had 34 passing checks (/tmp/item8-focused.log); all 43 VM transport checks and 23 historical trace checks passed (/tmp/item8-vm-transport.log, /tmp/item8-history.log). All 11 settings browser tests passed (/tmp/item8-settings-verified.log). A real workerd test streams and executes a framework-validated tool successfully (/tmp/item8-workerd.log) and is included in root validation. API TypeScript, app build, generated contract/docs and docs validation passed. Final complete root validation remains required in item 15. - -## 9. Hosted Pi as an MCP client - -Give Pi a run-scoped identity bounded by effective permissions. Use the same skills, MCP tools, resources, and reflection as external agents. Avoid privileged internal tool shortcuts. Include a provider-independent launch instruction mentioning reflection. - -- [x] One unchanged skill executes through hosted Pi and an external local MCP client; denied scopes and integration revocation are enforced. -- [x] Focused checks pass and evidence is recorded. The complete root suite is required in item 15. - -### Item 9 evidence - -Completed on 2026-11-20. Hosted Pi discovers protocol capabilities/tools and calls the public Worker MCP boundary with short-lived HMAC credentials bound to its PostgreSQL lease epoch. Application scopes, owner validity, active state, selected integrations and revocation are enforced by the same services used by external clients. MCP exposes credential-injected request/read operations alongside reflection. Resource and Skills extension adapters give Pi standard MCP reads; pinned input packages are available only to their own active run without granting broad library access. The bootstrap instruction points to reflection and pinned skill URIs. Model credential resolution uses the new provider configuration, and retired device/subscription implementations are removed. - -Migration 0074 removes the obsolete Trigger-parent requirement from permanent run credential revocations, covers all reflected integration kinds and known historical delete receipts, and remains retry-safe. Hosted invocation enforces destination grants, retains source-run provenance, and cannot expand permissions. MCP request cancellation propagates to upstream requests. Streaming journals retain framework deltas instead of repeatedly copying growing partial messages. - -All 39 focused harness, MCP, invocation and forwarding checks passed (/tmp/item9-final.log), followed by all 7 final MCP checks after cancellation wiring (/tmp/item9-mcp-complete.log). These execute an unchanged skill using both real hosted Pi and a separate local MCP client, verify scope/Team isolation, stable pinned packages after deletion, token forgery/expiry/lease replacement, disconnection/reconnect denial, destination limits, and idempotent revocation backfill without revoking newer snapshots. Earlier shared integration/grant checks also passed (/tmp/item9-integration.log). API TypeScript, Worker dry-run bundle, generated contract/docs, docs validation and whitespace checks passed. Final complete root validation remains required in item 15. - -## 10. Optional workspace VMs - -Requires VM defaults off for agents and is mandatory for scripts. Resolve explicit configuration before Team defaults. Failure of the selected configuration is an error. Provision and wait for readiness before the first Pi turn. Bind workspace identity server-side and expose verified current_vm through reflection; VM-free runs report null. Cover exe.dev and Fly with deterministic adapters. - -- [x] Local tests prove readiness precedes the first turn, explicit/default failures are surfaced, VM-free runs provision nothing, identities cannot be spoofed, and cleanup/cancellation work. -- [x] Focused checks pass and evidence is recorded. The complete root suite is required in item 15. - -### Item 10 evidence - -Completed on 2026-11-20. Migration 0075 preserves existing effective VM choices while new agent defaults are VM-free, and introduces independent workspace receipts. Explicit selections precede Team defaults; required missing/unavailable VMs fail without fallback. Triggers copy settings once. Scripts always require a VM. The editor and Team settings expose Requires VM; choosing a VM no longer resets model credentials. - -Workspace provisioning is separate from guest harness launch. exe.dev and Fly use documented provider APIs, persisted operation identities, fenced provisioning/cleanup leases, selected integration epochs and encrypted random guest proofs. Readiness precedes the first Pi turn; later turns and vm_exec verify the binding again. Reflection describes Factorize as the agent host and the remote current_vm separately. vm_exec rejects arbitrary VM IDs and unbound external identities. Cleanup retains late provisioning and deletion failures for retry; hosted sessions retain their terminal status during cleanup. - -All 11 workspace/provider checks passed (/tmp/item10-final.log), including real Pi turns after both adapters become ready, VM-free execution, explicit/default failure, Trigger default isolation, spoof/proof checks, cancellation and deletion retries. The shared hosted harness/MCP pass had 22 passing checks (/tmp/item10-vm.log). All 36 editor/settings browser checks passed (/tmp/item10-browser-final.log), following corrections to historical fixtures for explicit model configuration. API TypeScript, app build, Worker dry-run, generated contract and docs validation passed. Complete root validation remains required in item 15. - -## 11. Asynchronous and recoverable runs - -Return run ID promptly. Expose state, diagnostics, and results. Use idempotent launch and durable execution leases. Recover interrupted streaming and tool execution without duplicating known effects. Reconcile or explicitly report uncertain tool outcomes. Prevent concurrent resumptions and cancellation from restoring access. - -- [x] Local fault-injection tests restart during provisioning, streaming, and tool execution, retry the same launch, race workers, and cancel active work with one consistent outcome. -- [x] Focused checks pass and evidence is recorded. The complete root suite is required in item 15. - -### Item 11 evidence - -Completed on 2026-11-20. Admission returns an idempotent receipt without provisioning or model work. Independent per-run durable alarms keep long streams and workspace startup off global admission/maintenance. PostgreSQL lease epochs fence execution and MCP authorization. Complete checkpoints recover streamed turns; a durable tool journal records canonical arguments before effects and encrypted results before delivery. Recovery uses Pi's own validated tool runner, replays committed results and executes only missing calls. Detached run/Trigger tools receive stable server idempotency keys and retry interrupted responses on the same call. Unknown mutating outcomes block with pi_tool_uncertain, call ID and diagnostics; later effects/model requests stop. Cancellation cannot reopen a lease or commit late tool output. - -All 33 harness/MCP/workspace/recovery/alarm checks passed (/tmp/item11-final.log). Faults cover partial tool batches, lost detached-run responses, uncertain remote writes, expired/concurrent leases, old-worker streaming completion, asynchronous receipts, per-run alarm identity/retry, late provisioning and cancellation. API TypeScript (/tmp/item11-types-verified.log), Worker bundle (/tmp/item11-bundle.log), and package boundaries passed. Complete root validation remains required in item 15. - -## 12. Media passthrough and run artifacts - -Follow the pinned Pi framework's accepted media/content contracts and provider adapters. Factorize is a media pipe. Support launch attachments and media fetched through authorized tools using the same artifact references. Store bytes in existing RUN_ARTIFACTS R2 and ownership, size, type, checksum, and lifecycle in PostgreSQL. Expose uploads and reads through documented application endpoints/MCP where appropriate. Stream large transfers and keep credentials out of references and traces. Let framework capability checks report unsupported media. - -- [x] A local model fixture verifies actual image bytes from launch and mid-run tool retrieval, plus every additional media type supported by the pinned Pi version. -- [x] Tests cover restart recovery, malformed/unsupported content, interrupted uploads, idempotent retries, and cross-team denial using local R2. -- [x] Focused checks pass and evidence is recorded. The complete root suite is required in item 15. - -### Item 12 evidence - -Completed on 2026-11-20. Migration 0076 adds independent media/upload-attempt receipts and run input/scratch links while bytes use existing RUN_ARTIFACTS R2. Documented public reservation, binary upload/download and integration-fetch operations enforce active identity, ownership, immutable idempotency, size and SHA-256. Uploads stream through incremental hashing and Worker fixed-length streams. Image-only launches are valid; the dashboard uses the same public endpoints. MCP fetch_media and read_media share ordinary integration authorization and standard image content with external clients. Hosted Pi stores references in checkpoints/tool receipts/events and hydrates original bytes only at the framework boundary. Reflection reports the exact pinned text/image capability and bounded upload/turn sizes; audio/video unsupported by Pi 1.5.2 are rejected without conversion. - -All 6 media checks passed with PostgreSQL, real local R2, real Pi and public REST/MCP (/tmp/item12-media-last.log), including launch/tool image byte equality across fresh harnesses, integrity, large multi-chunk streams, cancellation/retry, malformed content, unsupported types and Team/run isolation. The shared harness/MCP/recovery pass had 19 passing checks (/tmp/item12-final.log). Both runs browser checks passed (/tmp/item12-browser.log), including raw image upload before image-only admission. A real Worker runtime test verifies incremental hashing/fixed-length streaming into R2 (/tmp/item12-runtime-final.log) and is part of root validation. API TypeScript, app build, Worker bundle, generated contract/docs and docs validation passed. Complete root validation remains required in item 15. - -## 13. Artifact cleanup - -Retain inputs and results for run retention. Intermediate blobs are scratch with a short recovery window. Do not add artifact promotion. Clean abandoned uploads and expired scratch without deleting active-run dependencies. Make PostgreSQL/R2 partial failure and retries safe. - -- [x] Controlled-clock local tests cover abandoned uploads, active runs, terminal recovery windows, result retention, deletion retries, and partially completed writes. -- [x] Focused checks pass and evidence is recorded. The complete root suite is required in item 15. - -### Item 13 evidence - -Completed on 2026-11-20. Migration 0077 records first reachability and cleanup leases/tombstones. Active run dependencies are protected, scratch expires one hour after termination, and unattached uploads expire after 24 hours. Inputs and media references included in actual structured results remain with retained run history. Result reachability is automatic; no promotion endpoint or separate published-output feature exists. Invalid/foreign result references fail the run explicitly. Run deletion leaves independent receipts for object cleanup. Private HTTP proxy buffers created only for fetch_media expire immediately after capture. - -Cleanup fences new attachment/read operations, claims independent PostgreSQL leases, confirms R2 deletions, retries partial failures and repeats tombstone deletion for 24 hours to cover late writes. Existing retention-pause settings also pause media expiry. All 13 controlled-clock lifecycle/media checks passed (/tmp/item13-complete.log), covering abandoned uploads, active leases/runs, terminal recovery, input/result retention, real Pi result references, missing result media, private response buffers, competing cleaners, lost deletion acknowledgements and late unadopted writes. The shared recovery pass had 18 passing checks (/tmp/item13-final.log). API TypeScript and Worker bundle passed; complete root validation remains required in item 15. - -## 14. Runs Source and Prompt columns - -Keep run name. Source snapshots Trigger name or manual for direct runs. Prompt shows optional /skill plus effective prompt, or shortened script. Store snapshots at creation and preserve complete detail content and historical rows. - -- [x] Browser/API tests cover renamed/deleted Triggers and skills, manual Trigger invocation, direct runs, scripts, old rows, and long content at desktop/mobile widths. -- [x] Focused checks pass and evidence is recorded. The complete root suite is required in item 15. - -### Item 14 evidence - -Completed on 2026-11-20. Migration 0078 preserves captured Trigger source names, backfills only missing names, and adds encrypted bounded list previews plus full context snapshots. New Trigger/manual/Event and direct admissions snapshot literal effective context independently of the reusable skill body; scripts snapshot their actual script. Source is the captured Trigger name or manual for direct runs. Existing launch skill keys remain immutable. Full harness input, full context/script, run name and historical rows remain available. Authorized list reads decrypt only bounded previews for new rows, with a bounded-page historical fallback; source sorting/pagination uses snapshots. - -All four PostgreSQL/API checks passed (/tmp/item14-preview.log), covering names after rename/deletion, manual Trigger/direct runs, skill-only context, Event/manual composition, script shortening, encrypted snapshots, full detail, historical fallback, permissions and pagination. All 23 runs browser checks passed (/tmp/item14-all-browser.log), including desktop/mobile Source/Prompt columns, escaping, long names/prompts, unchanged run-name links, metadata widths and table-contained scrolling. API TypeScript, app build, generated contracts and Worker bundle passed. Complete root validation remains required in item 15. - -## 15. Migration and final integration validation - -Complete coordinated migration while preserving accounts, integrations, skills, runs, artifacts, and historical trace readability. Identify incompatible names and multi-skill jobs with actionable local diagnostics. Validate supported upgrade paths and final public contracts. Update OpenAPI, generated client, and product docs. Test locally without requiring deployment or external approvals. - -- [x] Representative pre-change database fixtures migrate without resource/history loss or unintended permission expansion, including a retry after interruption. -- [x] End-to-end local tests cover signup, Team setup, Trigger Event, MCP skill, hosted Pi, optional VM, media, result, restart, and cleanup. -- [x] npm run generate, boundary checks, and complete npm test pass on the required toolchain; evidence and any remaining limitations are recorded. - -### Item 15 evidence - -Completed on 2026-11-20. Representative upgrade fixtures apply migrations 0067–0079 with rollback/interruption and retry at each new migration, followed by the actual migration runner to verify no replay. Eight migration checks preserve accounts, encrypted integrations, resource IDs, historical runs/traces, artifact object keys and previously effective authorization. Invalid/colliding names migrate deterministically; previous multi-skill context is archived with an explicit review requirement. Migration 0079 preserves unstarted guest-agent admissions as blocked, with actionable diagnostics and cancellation; it never reinterprets their credentials or launches a retired harness. The runtime also rejects such legacy admissions. Already-running historical guest executions retain their existing readers; the documented production release procedure drains them before cutover. No production migration or deployment was performed. - -The full local lifecycle test passes through signup and personal Team creation, provider/VM defaults, a templated Trigger Event, duplicate admission, published MCP skill metadata/files, actual hosted Pi requests after VM readiness, scoped VM commands, unchanged image retrieval, fresh-harness restart, structured result media retention, run expiry and object/VM cleanup. Tests use isolated PostgreSQL, local HTTP fixtures and local R2. Additional actual workerd tests cover OAuth consent, client isolation, integration revocation, ordinary MCP requests, guest delegation and hosted Pi background outcome delivery to an idle/reconnected session. VM execution rechecks the calling lease immediately before the command; exe.dev workspace inventory failures cannot masquerade as deletion, and shared native Factorize proxies are rejected. - -The final complete root npm test passed on Node 24.12.0/npm 11.19.0 in the pinned validation runner, using only the isolated localhost:55437 database. Evidence: /tmp/item15-root-4.log (exit 0, all 12 validation stages passed). Backend: 128 files, 816 tests passed and 5 skipped. Compiled app/API/PostgreSQL: 40 passed. Browser: 111 passed and 1 skipped, plus all 6 functional checks. Proxy: 4 process-runner checks and 32 protocol checks passed. Docker: both real-container vendor-identity/script/cleanup checks passed. Contract generation/drift, package/API boundaries, docs validation, TypeScript, Worker dry-run bundles, Pi/media/conditions/hosting/OAuth/rollback runtime checks and Tail relay checks all passed. The backend lane deadline is now 480 seconds and the overall deadline 1000 seconds to accommodate the expanded suite; individual test timeouts and failure assertions remain enforced. - -Focused upgrade/lifecycle evidence: /tmp/item15-integrated.log (8 migration checks, lifecycle and provider checks), /tmp/item15-last-focused.log (14 VM/provider/lifecycle checks), /tmp/item15-agent-runtime-4.log (actual workerd background outcome delivery), and /tmp/item15-static-2.log (40 compiled application checks). OpenAPI, generated client, product docs and operator runbooks describe the final contracts. The supported media contract follows pinned Pi 1.5.2: text and images; unsupported audio/video fail explicitly without conversion. Public contract renames are breaking and have no compatibility aliases. Existing data is preserved; pending legacy guest-agent runs require cancellation and a newly configured admission rather than silent credential substitution. External deployment/provider approval is outside local acceptance and was not used to claim completion. +Final verification: complete root `npm test` exited 0 after the final code change. All backend, compiled app/API/PostgreSQL, browser, proxy and Docker lanes passed. Backend: 132 test files passed (835 tests passed; five pre-existing optional tests skipped). Compiled application smoke/integration: 40 tests passed. Generated OpenAPI/client, documentation exports and package boundaries are current. Desktop and mobile layouts were also inspected in Chromium. diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index edcfcd36..3ef68654 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -296,6 +296,30 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/profile": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Read your profile; interactive owner browser session required + * @description Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + */ + get: operations["get_api_v1_profile"]; + /** + * Change your globally unique username; interactive owner browser session required + * @description Cookie-only browser operation. Mutations require an exact app Origin and reject cross-site requests. Authorization headers are rejected. Responses are never cached. + */ + put: operations["put_api_v1_profile"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/session": { parameters: { query?: never; @@ -1594,6 +1618,84 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/skills/{skillId}/files": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Browse the published skill directory at its immutable revision + * @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_files"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/skills/{skillId}/trigger": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Read a skill's optional trigger + * @description Requires the skills:read and triggers:read scopes. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + get: operations["get_api_v1_skills_skillId_trigger"]; + /** + * Configure a skill's event sources and enabled state + * @description Requires the skills:write and triggers:write scopes. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + put: operations["put_api_v1_skills_skillId_trigger"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/skills/{skillId}/settings": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Read skill execution defaults + * @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 + * @description Requires the skills:write and triggers:write scopes. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + put: operations["put_api_v1_skills_skillId_settings"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/skills": { parameters: { query?: never; @@ -4034,6 +4136,85 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_profile: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Success */ + 200: { + headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; + /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ + "X-Factorize-Contract"?: "gen-2157-static-v1"; + [name: string]: unknown; + }; + content: { + "application/json": { + username: string; + /** Format: email */ + email: string; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + put_api_v1_profile: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + username: string; + }; + }; + }; + responses: { + /** @description Success */ + 200: { + headers: { + /** @description Conditions-only webhook runtime deployment marker. */ + "X-Factorize-Webhook-Conditions"?: "v1"; + /** @description Deployment compatibility marker for the complete GEN-2157 static-client API contract. Deploy this API stage before static frontend cutover. */ + "X-Factorize-Contract"?: "gen-2157-static-v1"; + [name: string]: unknown; + }; + content: { + "application/json": { + username: string; + /** Format: email */ + email: string; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; get_api_v1_session: { parameters: { query?: never; @@ -4096,7 +4277,6 @@ export interface operations { requestBody: { content: { "application/json": { - /** Format: email */ email: string; password: string; returnTo?: string; @@ -4146,6 +4326,7 @@ export interface operations { "application/json": { /** Format: email */ email: string; + username: string; password: string; /** Format: uuid */ connection?: string; @@ -6917,34 +7098,772 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; - get_api_v1_skills: { + get_api_v1_skills_skillId_files: { parameters: { - query?: { - q?: string; - limit?: number; - cursor?: string; + query?: never; + header?: never; + path: { + skillId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Published files, with base64 encoded contents */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + revision: number; + commit: string | null; + files: { + path: string; + content: string; + executable: 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"]; + }; + }; + get_api_v1_skills_skillId_trigger: { + parameters: { + query?: never; header?: never; - path?: never; + path: { + skillId: string; + }; cookie?: never; }; requestBody?: never; responses: { - /** @description Skills */ + /** @description Optional trigger */ 200: { headers: { [name: string]: unknown; }; content: { "application/json": { - items: { + trigger: { /** Format: uuid */ id: string; - key: string; - revision: number; - usageCount: number; + name: string; + enabled: boolean; + requiresVm: boolean; + /** @enum {string} */ + executionType?: "agent" | "code"; + prompt: string; + script?: string; + runNameTemplate: string; + tags?: string[]; + model: string; + effort?: string; + executionConfig: { + connectionId: string; + requiresVm?: boolean; + workspace?: string; + cwd?: string; + agentKind: string; + image?: string; + region?: string; + size?: string; + /** @enum {string} */ + executionType?: "agent" | "code"; + script?: string; + }; + 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[]; + /** Format: uuid */ + modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; + skillId?: string | null; + executionConfigId: string; + agentKind: string; + concurrencyLimit: number; + runningCount: number; + currentRuns: number; + maxConcurrency: number; + lastRunState: ("queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored") | null; + events: ({ + /** Format: uuid */ + id: string; + slug: string; + /** @constant */ + kind: "manual"; + template?: string; + /** @default true */ + enabled: boolean; + /** @default {} */ + config: Record; + /** Format: uuid */ + triggerId: string; + createdAt: string; + updatedAt: string; + } | { + /** Format: uuid */ + id: string; + slug: string; + /** @constant */ + kind: "schedule"; + template?: string; + /** @default true */ + enabled: boolean; + config: { + cron: string; + timezone: string; + }; + /** Format: uuid */ + triggerId: string; + createdAt: string; + updatedAt: string; + } | { + /** Format: uuid */ + id: string; + slug: string; + /** @constant */ + kind: "webhook"; + template?: string; + /** @default true */ + enabled: boolean; + config: { + conditions?: { + [key: string]: unknown; + }; + /** @constant */ + provider: "linear"; + projectId: string; + matchRules: { + /** @enum {string} */ + type: "owner" | "creator" | "status" | "label" | "assignee"; + targetId: string; + }[]; + secretConfigured?: boolean; + } | { + conditions?: { + [key: string]: unknown; + }; + /** @constant */ + provider: "clickup"; + listId: string; + matchRules: { + /** @enum {string} */ + type: "owner" | "creator" | "status" | "label" | "assignee"; + targetId: string; + }[]; + secretConfigured?: boolean; + } | { + conditions?: { + [key: string]: unknown; + }; + /** @constant */ + provider: "github"; + installationId: number; + repositoryId: number; + event?: string; + action?: string; + matchRules?: { + /** @enum {string} */ + type: "owner" | "creator" | "status" | "label" | "assignee"; + targetId: string; + }[]; + secretConfigured?: boolean; + } | { + conditions?: { + [key: string]: unknown; + }; + /** @constant */ + provider: "cloudflareTail"; + integrationId: string; + destination?: string; + secretConfigured?: boolean; + }; + /** Format: uuid */ + triggerId: string; + createdAt: string; + updatedAt: string; + } | { + /** Format: uuid */ + id: string; + slug: string; + /** @constant */ + kind: "triggerLifecycle"; + template?: string; + /** @default true */ + enabled: boolean; + config: { + sourceTriggerIds: string[]; + states: ("succeeded" | "failed" | "stopped" | "edited")[]; + }; + /** Format: uuid */ + triggerId: string; + createdAt: string; + updatedAt: string; + } | { + /** Format: uuid */ + id: string; + slug: string; + /** @constant */ + kind: "triggerIdle"; + template?: string; + /** @default true */ + enabled: boolean; + config: { + sourceTriggerIds: string[]; + }; + /** Format: uuid */ + triggerId: string; + createdAt: string; + updatedAt: string; + })[]; + skill?: { + /** Format: uuid */ + id: string; + key: string; + revision: number; + } | null; + contextReviewRequired?: boolean; createdAt: string; updatedAt: 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"]; + }; + }; + put_api_v1_skills_skillId_trigger: { + parameters: { + query?: never; + header?: never; + path: { + skillId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + events: ({ + id?: string; + slug?: string; + /** @constant */ + kind: "manual"; + template?: string; + /** @default true */ + enabled?: boolean; + /** @default {} */ + config?: Record; + } | { + id?: string; + slug?: string; + /** @constant */ + kind: "schedule"; + template?: string; + /** @default true */ + enabled?: boolean; + config: { + cron: string; + timezone: string; + }; + } | { + id?: string; + slug?: string; + /** @constant */ + kind: "webhook"; + template?: string; + /** @default true */ + enabled?: boolean; + config: { + conditions?: { + [key: string]: unknown; + }; + /** @constant */ + provider: "linear"; + projectId: string; + matchRules: { + /** @enum {string} */ + type: "owner" | "creator" | "status" | "label" | "assignee"; + targetId: string; + }[]; + } | { + conditions?: { + [key: string]: unknown; + }; + /** @constant */ + provider: "clickup"; + listId: string; + matchRules: { + /** @enum {string} */ + type: "owner" | "creator" | "status" | "label" | "assignee"; + targetId: string; + }[]; + } | { + conditions?: { + [key: string]: unknown; + }; + /** @constant */ + provider: "github"; + installationId: number; + repositoryId: number; + event?: string; + action?: string; + matchRules?: { + /** @enum {string} */ + type: "owner" | "creator" | "status" | "label" | "assignee"; + targetId: string; + }[]; + } | { + conditions?: { + [key: string]: unknown; + }; + /** @constant */ + provider: "cloudflareTail"; + integrationId: string; + }; + } | { + id?: string; + slug?: string; + /** @constant */ + kind: "triggerLifecycle"; + template?: string; + /** @default true */ + enabled?: boolean; + config: { + sourceTriggerIds: string[]; + states: ("succeeded" | "failed" | "stopped" | "edited")[]; + }; + } | { + id?: string; + slug?: string; + /** @constant */ + kind: "triggerIdle"; + template?: string; + /** @default true */ + enabled?: boolean; + config: { + sourceTriggerIds: string[]; + }; + })[]; + /** @default true */ + enabled?: boolean; + /** Format: date-time */ + expectedUpdatedAt?: string; + }; + }; + }; + responses: { + /** @description Saved trigger */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + trigger: { + /** Format: uuid */ + id: string; + name: string; + enabled: boolean; + requiresVm: boolean; + /** @enum {string} */ + executionType?: "agent" | "code"; + prompt: string; + script?: string; + runNameTemplate: string; + tags?: string[]; + model: string; + effort?: string; + executionConfig: { + connectionId: string; + requiresVm?: boolean; + workspace?: string; + cwd?: string; + agentKind: string; + image?: string; + region?: string; + size?: string; + /** @enum {string} */ + executionType?: "agent" | "code"; + script?: string; + }; + 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[]; + /** Format: uuid */ + modelAccountId?: string; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; + skillId?: string | null; + executionConfigId: string; + agentKind: string; + concurrencyLimit: number; + runningCount: number; + currentRuns: number; + maxConcurrency: number; + lastRunState: ("queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored") | null; + events: ({ + /** Format: uuid */ + id: string; + slug: string; + /** @constant */ + kind: "manual"; + template?: string; + /** @default true */ + enabled: boolean; + /** @default {} */ + config: Record; + /** Format: uuid */ + triggerId: string; + createdAt: string; + updatedAt: string; + } | { + /** Format: uuid */ + id: string; + slug: string; + /** @constant */ + kind: "schedule"; + template?: string; + /** @default true */ + enabled: boolean; + config: { + cron: string; + timezone: string; + }; + /** Format: uuid */ + triggerId: string; + createdAt: string; + updatedAt: string; + } | { + /** Format: uuid */ + id: string; + slug: string; + /** @constant */ + kind: "webhook"; + template?: string; + /** @default true */ + enabled: boolean; + config: { + conditions?: { + [key: string]: unknown; + }; + /** @constant */ + provider: "linear"; + projectId: string; + matchRules: { + /** @enum {string} */ + type: "owner" | "creator" | "status" | "label" | "assignee"; + targetId: string; + }[]; + secretConfigured?: boolean; + } | { + conditions?: { + [key: string]: unknown; + }; + /** @constant */ + provider: "clickup"; + listId: string; + matchRules: { + /** @enum {string} */ + type: "owner" | "creator" | "status" | "label" | "assignee"; + targetId: string; + }[]; + secretConfigured?: boolean; + } | { + conditions?: { + [key: string]: unknown; + }; + /** @constant */ + provider: "github"; + installationId: number; + repositoryId: number; + event?: string; + action?: string; + matchRules?: { + /** @enum {string} */ + type: "owner" | "creator" | "status" | "label" | "assignee"; + targetId: string; + }[]; + secretConfigured?: boolean; + } | { + conditions?: { + [key: string]: unknown; + }; + /** @constant */ + provider: "cloudflareTail"; + integrationId: string; + destination?: string; + secretConfigured?: boolean; + }; + /** Format: uuid */ + triggerId: string; + createdAt: string; + updatedAt: string; + } | { + /** Format: uuid */ + id: string; + slug: string; + /** @constant */ + kind: "triggerLifecycle"; + template?: string; + /** @default true */ + enabled: boolean; + config: { + sourceTriggerIds: string[]; + states: ("succeeded" | "failed" | "stopped" | "edited")[]; + }; + /** Format: uuid */ + triggerId: string; + createdAt: string; + updatedAt: string; + } | { + /** Format: uuid */ + id: string; + slug: string; + /** @constant */ + kind: "triggerIdle"; + template?: string; + /** @default true */ + enabled: boolean; + config: { + sourceTriggerIds: string[]; + }; + /** Format: uuid */ + triggerId: string; + createdAt: string; + updatedAt: string; + })[]; + skill?: { + /** Format: uuid */ + id: string; + key: string; + revision: number; + } | null; + contextReviewRequired?: boolean; + createdAt: string; + updatedAt: 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"]; + }; + }; + get_api_v1_skills_skillId_settings: { + parameters: { + query?: never; + header?: never; + path: { + skillId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Skill settings */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + revision: number; + defaults: { + executionConfigId?: string; + requiresVm?: boolean; + model?: string; + /** @enum {string} */ + effort?: "" | "minimal" | "low" | "medium" | "high" | "xhigh"; + /** @description Public Docker/OCI image reference, or blank for the provider default. */ + vmImage?: string; + tags?: string[]; + /** Format: uuid */ + modelAccountId?: string; + portableIntegrationIds?: string[]; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; + /** @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")[]; + concurrencyLimit?: number; + allowedTriggerIds?: string[]; + /** + * @default agent + * @enum {string} + */ + executionType: "agent" | "code"; + /** @default */ + prompt: string; + script?: string; + }; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + put_api_v1_skills_skillId_settings: { + parameters: { + query?: never; + header?: never; + path: { + skillId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + expectedRevision: number; + defaults: { + executionConfigId?: string; + requiresVm?: boolean; + model?: string; + /** @enum {string} */ + effort?: "" | "minimal" | "low" | "medium" | "high" | "xhigh"; + /** @description Public Docker/OCI image reference, or blank for the provider default. */ + vmImage?: string; + tags?: string[]; + /** Format: uuid */ + modelAccountId?: string; + portableIntegrationIds?: string[]; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; + /** @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")[]; + concurrencyLimit?: number; + allowedTriggerIds?: string[]; + /** + * @default agent + * @enum {string} + */ + executionType?: "agent" | "code"; + /** @default */ + prompt?: string; + script?: string; + }; + }; + }; + }; + responses: { + /** @description Saved skill settings */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + revision: number; + defaults: { + executionConfigId?: string; + requiresVm?: boolean; + model?: string; + /** @enum {string} */ + effort?: "" | "minimal" | "low" | "medium" | "high" | "xhigh"; + /** @description Public Docker/OCI image reference, or blank for the provider default. */ + vmImage?: string; + tags?: string[]; + /** Format: uuid */ + modelAccountId?: string; + portableIntegrationIds?: string[]; + githubInstallationIds?: number[]; + linearConnectionId?: "linear" | null; + xConnectionIds?: string[]; + /** @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")[]; + concurrencyLimit?: number; + allowedTriggerIds?: string[]; + /** + * @default agent + * @enum {string} + */ + executionType: "agent" | "code"; + /** @default */ + prompt: string; + script?: string; + }; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + get_api_v1_skills: { + parameters: { + query?: { + q?: string; + limit?: number; + cursor?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Skills */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + items: { + /** Format: uuid */ + id: string; + key: string; + revision: number; + usageCount: number; + createdAt: string; + updatedAt: string; + trigger?: { + /** Format: uuid */ + id: string; + enabled: boolean; + } | null; + lastRunState?: string | null; }[]; nextCursor: string | null; }; diff --git a/packages/api/migrations/0080_usernames.sql b/packages/api/migrations/0080_usernames.sql new file mode 100644 index 00000000..0285f656 --- /dev/null +++ b/packages/api/migrations/0080_usernames.sql @@ -0,0 +1,17 @@ +ALTER TABLE app.auth_users ADD COLUMN username text; +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM app.auth_users WHERE length(split_part(lower(email),'@',1)) NOT BETWEEN 3 AND 39 OR split_part(lower(email),'@',1) !~ '^[a-z0-9]+(-[a-z0-9]+)*$') THEN + RAISE EXCEPTION 'Username migration: an email prefix is not a valid username; choose a valid username before migrating'; + END IF; + IF EXISTS (SELECT 1 FROM app.auth_users GROUP BY split_part(lower(email),'@',1) HAVING count(*)>1) THEN + RAISE EXCEPTION 'Username migration: duplicate email prefixes; choose distinct usernames before migrating'; + END IF; +END $$; +UPDATE app.auth_users SET username=split_part(lower(email),'@',1); +ALTER TABLE app.auth_users ALTER COLUMN username SET NOT NULL; +-- Internal identity provisioning still needs an identity before public signup. +ALTER TABLE app.auth_users ALTER COLUMN username SET DEFAULT ('user-' || replace(gen_random_uuid()::text,'-','')); +ALTER TABLE app.auth_users ADD CONSTRAINT auth_users_username_format CHECK(length(username) BETWEEN 3 AND 39 AND username ~ '^[a-z0-9]+(-[a-z0-9]+)*$'); +ALTER TABLE app.auth_users ADD CONSTRAINT auth_users_username_unique UNIQUE(username); +INSERT INTO app.schema_migrations(version) VALUES ('0080_usernames') ON CONFLICT DO NOTHING; diff --git a/packages/api/migrations/0081_personal_team_names.sql b/packages/api/migrations/0081_personal_team_names.sql new file mode 100644 index 00000000..cc02a862 --- /dev/null +++ b/packages/api/migrations/0081_personal_team_names.sql @@ -0,0 +1,27 @@ +ALTER TABLE app.tenants ADD COLUMN personal_owner_id uuid REFERENCES app.auth_users(id); +CREATE UNIQUE INDEX tenants_personal_owner ON app.tenants(personal_owner_id) WHERE personal_owner_id IS NOT NULL; +WITH owners AS (SELECT DISTINCT ON (tenant_id) tenant_id,user_id FROM app.members WHERE role='owner' ORDER BY tenant_id,created_at,user_id) +UPDATE app.tenants t SET personal_owner_id=o.user_id,name=u.username FROM owners o JOIN app.auth_users u ON u.id=o.user_id WHERE t.id=o.tenant_id; +CREATE FUNCTION app.personal_team_name() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.personal_owner_id IS NOT NULL THEN + SELECT username INTO NEW.name FROM app.auth_users WHERE id=NEW.personal_owner_id; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER personal_team_name BEFORE INSERT OR UPDATE ON app.tenants FOR EACH ROW EXECUTE FUNCTION app.personal_team_name(); +CREATE FUNCTION app.assign_personal_team() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.role='owner' AND NOT EXISTS(SELECT 1 FROM app.tenants WHERE personal_owner_id=NEW.user_id) THEN + UPDATE app.tenants SET personal_owner_id=NEW.user_id WHERE id=NEW.tenant_id AND personal_owner_id IS NULL; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER assign_personal_team AFTER INSERT ON app.members FOR EACH ROW EXECUTE FUNCTION app.assign_personal_team(); +CREATE FUNCTION app.rename_personal_team() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + UPDATE app.tenants SET name=NEW.username,updated_at=now() WHERE personal_owner_id=NEW.id; + RETURN NEW; +END $$; +CREATE TRIGGER rename_personal_team AFTER UPDATE OF username ON app.auth_users FOR EACH ROW EXECUTE FUNCTION app.rename_personal_team(); +INSERT INTO app.schema_migrations(version) VALUES ('0081_personal_team_names') ON CONFLICT DO NOTHING; diff --git a/packages/api/migrations/0082_skill_execution_settings.sql b/packages/api/migrations/0082_skill_execution_settings.sql new file mode 100644 index 00000000..406eefd8 --- /dev/null +++ b/packages/api/migrations/0082_skill_execution_settings.sql @@ -0,0 +1,16 @@ +ALTER TABLE app.skills ADD COLUMN run_defaults jsonb; +ALTER TABLE app.skills ADD COLUMN encrypted_prompt text; +ALTER TABLE app.skills ADD COLUMN encrypted_script text; +ALTER TABLE app.skills ADD COLUMN settings_revision integer NOT NULL DEFAULT 1; +UPDATE app.skills s SET run_defaults=COALESCE((SELECT run_defaults-'capacity' FROM app.team_settings WHERE tenant_id=s.tenant_id),'{}'::jsonb); +ALTER TABLE app.skills ALTER COLUMN run_defaults SET NOT NULL; +CREATE FUNCTION app.initialize_skill_defaults() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.run_defaults IS NULL THEN + SELECT COALESCE(run_defaults-'capacity','{}'::jsonb) INTO NEW.run_defaults FROM app.team_settings WHERE tenant_id=NEW.tenant_id; + NEW.run_defaults:=COALESCE(NEW.run_defaults,'{}'::jsonb); + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER initialize_skill_defaults BEFORE INSERT ON app.skills FOR EACH ROW EXECUTE FUNCTION app.initialize_skill_defaults(); +INSERT INTO app.schema_migrations(version) VALUES ('0082_skill_execution_settings') ON CONFLICT DO NOTHING; diff --git a/packages/api/migrations/0083_skill_trigger_ownership.sql b/packages/api/migrations/0083_skill_trigger_ownership.sql new file mode 100644 index 00000000..2c322648 --- /dev/null +++ b/packages/api/migrations/0083_skill_trigger_ownership.sql @@ -0,0 +1,5 @@ +-- Legacy links are converted by the following context-preserving migration. +ALTER TABLE app.trigger_skills ADD COLUMN skill_owned boolean NOT NULL DEFAULT false; +ALTER TABLE app.trigger_skills ALTER COLUMN skill_owned SET DEFAULT true; +CREATE UNIQUE INDEX one_owned_trigger_per_skill ON app.trigger_skills(tenant_id,skill_id) WHERE skill_owned; +INSERT INTO app.schema_migrations(version) VALUES ('0083_skill_trigger_ownership') ON CONFLICT DO NOTHING; diff --git a/packages/api/migrations/0084_migrate_trigger_skills.sql b/packages/api/migrations/0084_migrate_trigger_skills.sql new file mode 100644 index 00000000..588db3ad --- /dev/null +++ b/packages/api/migrations/0084_migrate_trigger_skills.sql @@ -0,0 +1,43 @@ +ALTER TABLE app.skills ADD COLUMN legacy_context jsonb NOT NULL DEFAULT '[]'::jsonb; +ALTER TABLE app.skills ADD COLUMN migration_pending boolean NOT NULL DEFAULT false; +DO $$ +DECLARE item record; new_id uuid; chosen text; suffix integer; contexts jsonb; +BEGIN + FOR item IN SELECT * FROM app.triggers t ORDER BY tenant_id,id LOOP + new_id:=gen_random_uuid(); suffix:=0; + chosen:=left(item.slug,43)||'-skill-'||left(replace(new_id::text,'-',''),12); + WHILE EXISTS(SELECT 1 FROM app.resource_names WHERE tenant_id=item.tenant_id AND name=chosen) LOOP + suffix:=suffix+1; chosen:=left(item.slug,39)||'-skill-'||left(replace(new_id::text,'-',''),12)||'-'||suffix; + END LOOP; + SELECT COALESCE(jsonb_agg(jsonb_build_object('key',s.key,'encrypted_body',s.encrypted_body,'encrypted_directory',s.encrypted_directory,'artifact_version',s.artifact_version) ORDER BY ts.position),'[]'::jsonb) + INTO contexts FROM ( + SELECT skill_id,position FROM app.trigger_skills WHERE tenant_id=item.tenant_id AND trigger_id=item.id + UNION + SELECT skill_id,position FROM app.legacy_trigger_skill_links WHERE tenant_id=item.tenant_id AND trigger_id=item.id AND item.context_review_required + ) ts JOIN app.skills s ON s.tenant_id=item.tenant_id AND s.id=ts.skill_id; + INSERT INTO app.skills(tenant_id,id,key,encrypted_body,encrypted_script,run_defaults,legacy_context,migration_pending) + VALUES(item.tenant_id,new_id,chosen,COALESCE(item.encrypted_prompt,''),NULL, + jsonb_strip_nulls(jsonb_build_object( + 'executionType',COALESCE(item.execution_config->>'executionType','agent'), + 'requiresVm',COALESCE((item.execution_config->>'requiresVm')::boolean,COALESCE(item.execution_config->>'executionType'='code',false) OR COALESCE(item.execution_config->>'connectionId'<>'',false)), + 'executionConfigId',NULLIF(item.execution_config->>'connectionId',''), + 'vmImage',item.execution_config->>'image','model',item.model,'effort',item.effort,'tags',item.tags, + 'modelAccountId',item.execution_config->>'modelAccountId','runScopes',item.run_scopes, + 'portableIntegrationIds',COALESCE(item.execution_config->'portableIntegrationIds','[]'::jsonb), + 'githubInstallationIds',COALESCE(item.execution_config->'githubInstallationIds','[]'::jsonb), + 'linearConnectionId',item.execution_config->>'linearConnectionId','xConnectionIds',COALESCE(item.execution_config->'xConnectionIds','[]'::jsonb), + 'concurrencyLimit',item.concurrency_limit, + 'allowedTriggerIds',(SELECT COALESCE(jsonb_agg(destination_trigger_id),'[]'::jsonb) FROM app.manual_invocation_permissions WHERE tenant_id=item.tenant_id AND source_trigger_id=item.id) + )),contexts,true); + -- Scripts remain in the original execution projection until a settings save + -- encrypts them into the skill setting. No plaintext script is newly persisted. + INSERT INTO app.configuration_diagnostics(tenant_id,resource_kind,resource_id,code,details) + VALUES(item.tenant_id,'trigger',item.id,'skill_owned_migration',jsonb_build_object('skillId',new_id,'previousName',item.name,'previousPrompt',item.encrypted_prompt,'previousExecutionConfig',item.execution_config)); + DELETE FROM app.trigger_skills WHERE tenant_id=item.tenant_id AND trigger_id=item.id; + INSERT INTO app.trigger_skills(tenant_id,trigger_id,skill_id,position,context_skill,skill_owned) VALUES(item.tenant_id,item.id,new_id,0,false,true); + UPDATE app.triggers SET encrypted_prompt='',execution_config=execution_config||jsonb_build_object('skillId',new_id) WHERE tenant_id=item.tenant_id AND id=item.id; + END LOOP; +END $$; +DROP INDEX app.one_owned_trigger_per_skill; +CREATE UNIQUE INDEX one_trigger_per_skill ON app.trigger_skills(tenant_id,skill_id); +INSERT INTO app.schema_migrations(version) VALUES ('0084_migrate_trigger_skills') ON CONFLICT DO NOTHING; diff --git a/packages/api/migrations/0085_skill_content_cache.sql b/packages/api/migrations/0085_skill_content_cache.sql new file mode 100644 index 00000000..4f22f584 --- /dev/null +++ b/packages/api/migrations/0085_skill_content_cache.sql @@ -0,0 +1,9 @@ +CREATE TABLE app.skill_content_cache ( + tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, + repository text NOT NULL, + commit_sha text NOT NULL, + encrypted_content text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY(tenant_id,repository,commit_sha) +); +INSERT INTO app.schema_migrations(version) VALUES ('0085_skill_content_cache') ON CONFLICT DO NOTHING; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 14a912e5..d476a3d7 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -1,3 +1,6 @@ +import { skillTriggerInput, skillTriggerResponse } from "./skill-trigger"; +import { skillSettings, skillSettingsInput } from "./skill-settings"; +import { profileInput, profileResponse } from "./usernames"; import {mediaUploadInput,mediaReceipt,fetchMediaInput} from "./media-contracts"; import {modelProviderConfiguration} from "./pi-provider"; import { teamRunDefaults, teamResponse } from "./flow-schemas"; @@ -34,7 +37,7 @@ import { traceReplaySchema } from "./trace-replay-schemas"; import { X_OAUTH_SCOPES } from "./x-oauth"; import document from "./api-document.json"; import { authInputs, authSuccess, continuationSuccess, connectionStartInput, connectionStartSuccess, connectionResumeInput, loginSuccess, sessionResponse, type AuthAction } from "./auth-api"; -import { skillInput, skillUpdateInput, skillPage, skillResponse, skillTriggersResponse, previewSkillInput, previewPromptResponse } from "./skills"; +import { skillDirectoryResponse, skillInput, skillUpdateInput, skillPage, skillResponse, skillTriggersResponse, previewSkillInput, previewPromptResponse } from "./skills"; import { flyConnectionInput, flyConnectionMetadata } from "./fly-account-client"; import { flyExecutionConfiguration, flyExecutionConfigurationInput } from "./fly-execution-configurations"; @@ -287,6 +290,8 @@ export const API_ROUTES: RouteContract[] = [ }, (service, { params, body }) => service.deleteBearerIntegration(params.integrationId, body), { body: bearerIntegrationDelete, maxBodyBytes: 4096, ownerSession: true }), authRoute("POST", "/api/v1/auth/connections", "connection-start", "Persist an individual validated MCP connection; sets a per-attempt browser cookie", connectionStartSuccess, connectionStartInput), authRoute("POST", "/api/v1/auth/connections/resume", "connection-resume", "Resume verified onboarding in the initiating browser; never grants OAuth access", continuationSuccess, connectionResumeInput), + {...authRoute("GET", "/api/v1/profile", "profile", "Read your profile; interactive owner browser session required", profileResponse),ownerSession:true}, + {...authRoute("PUT", "/api/v1/profile", "profile-update", "Change your globally unique username; interactive owner browser session required", profileResponse, profileInput),ownerSession:true}, authRoute("GET", "/api/v1/session", "session", "Get current browser session", sessionResponse), authRoute("POST", "/api/v1/auth/login", "login", "Sign in", loginSuccess, authInputs.login), authRoute("POST", "/api/v1/auth/signup", "signup", "Request signup; existing accounts return the same accepted response", authSuccess, authInputs.signup, 202), @@ -809,6 +814,11 @@ export const API_ROUTES: RouteContract[] = [ route("PUT", "/api/v1/skill-library", "skills:write", { summary: "Select the authoritative skills repository", responses: { "200": { description: "Select the authoritative skills repository", content: { "application/json": { schema: jsonSchema(libraryStatus, "output") } } } } }, (service,{body}) => service.configureSkillLibrary(body), {body:configureLibrary}), route("POST", "/api/v1/skill-library/token", "skills:write", { summary: "Issue a one-hour repository credential (read-only for GitHub mirrors)", responses: { "200": { description: "Issue a one-hour repository credential (read-only for GitHub mirrors)", content: { "application/json": { schema: jsonSchema(libraryToken, "output") } } } } }, (service) => service.skillLibraryToken()), route("POST", "/api/v1/skill-library/sync", "skills:write", { summary: "Synchronize the tracked branch", responses: { "200": { description: "Synchronize the tracked branch", content: { "application/json": { schema: jsonSchema(libraryStatus, "output") } } } } }, (service) => service.syncSkillLibrary()), + 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", "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 }), diff --git a/packages/api/src/auth-api.ts b/packages/api/src/auth-api.ts index 0f4dbade..dad8dcdf 100644 --- a/packages/api/src/auth-api.ts +++ b/packages/api/src/auth-api.ts @@ -1,3 +1,4 @@ +import { usernameSchema } from "./usernames"; import { integrationConsentLabels } from "./agent-api"; import { ACCESS_SCOPES } from "./access-tokens"; import { connectionFor, originalBrowser, startConnection, connectionDestination } from "./oauth-continuation"; @@ -17,8 +18,8 @@ const password = z.string().min(12).max(200).meta({ writeOnly: true }); const connection = z.uuid().optional(); const token = z.string().min(1).max(512).meta({ writeOnly: true }); export const authInputs = { - login: z.object({ email, password, returnTo: z.string().max(8192).optional(), connection }).strict(), - signup: z.object({ email, password, connection }).strict(), + login: z.object({ email: z.string().trim().toLowerCase().min(1).max(320), password, returnTo: z.string().max(8192).optional(), connection }).strict(), + signup: z.object({ email, username: usernameSchema, password, connection }).strict(), request: z.object({ email, connection }).strict(), verify: z.object({ token }).strict(), reset: z.object({ token, password }).strict(), @@ -47,7 +48,7 @@ export function safeReturnTo(value: string | undefined): string { try { const url = new URL(value, "https://local.invalid"); if (url.origin !== "https://local.invalid") return "/integrations"; - if (!/^\/(?:authorize|device|integrations|triggers(?:\/[^/]+(?:\/(?:edit|settings))?)?|runs(?:\/[^/]+)?|settings(?:\/(?:integrations|api-keys(?:\/new)?|password))?)$/.test(url.pathname)) return "/integrations"; + if (!/^\/(?:authorize|device|integrations|skills(?:\/[^/]+(?:\/(?:runs|settings(?:\/(?:general|vm|permissions|trigger))?))?)?|triggers(?:\/[^/]+(?:\/(?:edit|settings(?:\/(?:general|vm|context|permissions|events))?))?)?|runs(?:\/[^/]+(?:\/(?:trace|info))?)?|settings(?:\/(?:profile|vm|permissions|skills|vm-presets|integrations|api-keys(?:\/new)?|authorized-clients|password))?)$/.test(url.pathname)) return "/integrations"; return url.pathname + url.search + url.hash; } catch { return "/integrations"; } } @@ -68,7 +69,7 @@ async function currentSession(request: Request, env: Env): Promise = {}): Promise { // These operations use browser cookies only. Ignore neither a bad bearer nor a @@ -101,8 +102,15 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env const pending = await connectionFor(env, String(input.connection)); if (!pending || !await originalBrowser(request, env, pending)) return failure(400, "Invalid or expired connection. Restart connecting from your MCP client."); } - if (action === "session" || action === "logout" || action === "password" || action === "consent-preview" || action === "consent-decision" || action === "device-preview" || action === "device-decision") { + if (action === "profile" || action === "profile-update" || action === "session" || action === "logout" || action === "password" || action === "consent-preview" || action === "consent-decision" || action === "device-preview" || action === "device-decision") { const session = await currentSession(request, env); + if (action === "profile" || action === "profile-update") { + if (!session) return failure(401, "Sign in to manage your profile."); + const repo = new AuthRepository(databaseFor(env), env); + if (action === "profile") return authJson(await repo.profile(session.userId)); + const result = await repo.updateProfile(session.userId, String(input.username)); + return result.status === 200 ? authJson(result.body) : failure(result.status, (result.body as {error:string}).error); + } if (action === "session") { if (!session) return authJson({ authenticated: false }); const workspace = (await databaseFor(env).pool.query<{ name: string | null }>("SELECT name FROM app.tenants WHERE id=$1", [session.tenantId])).rows[0]; @@ -180,7 +188,7 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env if ((action === "verification" || action === "reset") && result.status === 200 && "userId" in result.body && result.body.userId && !result.body.tenantId) return failure(403, "This account needs a workspace owner invitation."); // The new public signup contract intentionally does not enumerate accounts. // Keep legacy form status compatibility until those screens are cut over. - if (action === "signup" && (result.status === 201 || result.status === 409)) return authJson({ ok: true }, 202); + if (action === "signup" && (result.status === 201 || result.status === 409 && (!("error" in result.body) || result.body.error !== "That username is already taken."))) return authJson({ ok: true }, 202); return result.status < 300 ? authJson({ ok: true }) : failure(result.status, "error" in result.body ? result.body.error ?? "Request failed." : "Request failed."); } diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index e66b4be7..cb75c37d 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -1,3 +1,7 @@ +import { markdown, validPath } from "./skill-files"; +import { PostgresSkillContentCache } from "./postgres/skill-content-cache"; +import { skillTriggerInput } from "./skill-trigger"; +import { skillDefaults, skillSettingsInput } from "./skill-settings"; import {runPromptPreview} from "./run-prompt"; import {createHash} from "node:crypto"; import {Buffer} from "node:buffer"; @@ -94,10 +98,10 @@ 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)); } + 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 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)); } + 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))); } private async executionConfig(id: string) { // Target IDs created by the migration are deterministic md5-derived UUIDs, // so they do not necessarily have RFC 4122 version/variant bits. Any @@ -301,7 +305,7 @@ export class ApiService { const runningCount = Number(stats?.running_count ?? 0); return publicValue(triggerResponse, { ...trigger, - skillId: trigger.executionConfig.skillId ?? null, + skillId: trigger.skill?.id ?? trigger.executionConfig.skillId ?? null, runScopes: trigger.runScopes ?? [...DEFAULT_RUN_SCOPES], executionType: trigger.executionType ?? "agent", requiresVm: trigger.executionConfig.requiresVm ?? (trigger.executionType==="code" || Boolean(trigger.executionConfig.connectionId)), @@ -398,9 +402,63 @@ export class ApiService { 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 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"); + const files=skill.version?.files??[markdown(skill.body??"")]; + if(files.some(file=>!validPath(file.path)))throw new ServiceError(409,"invalid_skill","Skill contains an invalid file path."); + return {revision:skill.revision,commit:skill.version?.commit??null,files}; + } + 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}:{})})}; + } + async setSkillSettings(id:string,request:unknown) { + 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}; + } 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; } } 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}; + } + 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 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); + } async listSkillTriggers(id: string) { await this.authorize("skills:read"); return publicValue(skillTriggersResponse, { skillId: id, triggers: await this.skills().triggers(id) }); } async previewTriggerPrompt(input: unknown) { await this.authorize("skills:read"); @@ -825,7 +883,7 @@ export class ApiService { async getTeamGraph() { await this.authorize("triggers:read"); const db = databaseFor(this.env), tenantId = this.auth.tenantId; - const triggers = await db.pool.query(`SELECT j.id,j.name,j.enabled,j.execution_config,j.concurrency_limit, + const triggers = await db.pool.query(`SELECT j.id,COALESCE((SELECT s.key FROM app.trigger_skills ts JOIN app.skills s ON s.tenant_id=ts.tenant_id AND s.id=ts.skill_id WHERE ts.tenant_id=j.tenant_id AND ts.trigger_id=j.id),j.name) name,j.enabled,j.execution_config,j.concurrency_limit, (SELECT count(*)::int FROM app.trigger_runs r WHERE r.tenant_id=j.tenant_id AND r.trigger_id=j.id AND r.state IN ('reserved','starting','running','blocked','stopping')) running_count, COALESCE(jsonb_agg(jsonb_build_object('id',t.id,'kind',t.kind,'enabled',t.enabled,'config',CASE WHEN t.kind='triggerLifecycle' THEN jsonb_build_object('sourceTriggerIds',t.config->'sourceTriggerIds','sourceTriggerId',t.config->'sourceTriggerId','states',t.config->'states') @@ -869,9 +927,10 @@ export class ApiService { 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"); - const defaults = team.runDefaults; + const owned = request.skillId ? (await this.readSkillSettings(request.skillId).catch(error=>{if(error instanceof ServiceError && error.status===404)throw new ServiceError(400,"invalid_request","The selected skill is unavailable.");throw error;})).defaults : undefined; + const defaults = {...team.runDefaults,...owned}; const executionConfigId = request.executionConfigId ?? defaults.executionConfigId; - const requiresVm=request.executionType==="code" || (request.requiresVm ?? (request.executionConfigId ? true : defaults.requiresVm ?? false)); + const requiresVm=(request.executionType ?? owned?.executionType)==="code" || (request.requiresVm ?? (request.executionConfigId ? true : defaults.requiresVm ?? false)); if(request.executionConfigId && request.requiresVm===false)throw new ServiceError(400,"invalid_request","A VM override requires requiresVm=true."); const input = { ...defaults, @@ -888,7 +947,7 @@ export class ApiService { const portable = await this.portableSelections(executionConfig, executionType, input); const events = this.normalizedEvents(input.events).map((event) => ({ ...event, triggerId: id })); const skill = - executionType === "agent" && input.skillId + input.skillId ? (await this.skillSelections([input.skillId]))[0] : undefined; const trigger: Trigger = { @@ -897,7 +956,7 @@ export class ApiService { name: input.name, slug: input.name, - prompt: input.prompt ?? "", + prompt: input.prompt || owned?.prompt || "", executionType, script: executionType === "code" ? input.script : undefined, runNameTemplate: input.runNameTemplate ?? "", @@ -907,7 +966,7 @@ export class ApiService { ...(input.effort ? { effort: input.effort } : {}), executionConfig: { ...executionConfig, - skillId: executionType === "agent" ? (input.skillId ?? undefined) : undefined, + skillId: input.skillId ?? undefined, ...portable, executionType, ...(input.script ? { script: input.script } : {}), @@ -923,7 +982,7 @@ export class ApiService { try { return this.presentTrigger(await this.triggers().create(trigger, defaults.allowedTriggerIds ?? [])); } catch (error: any) { - if ((error?.code ?? error?.cause?.code) === "23505") throw new ServiceError(409, "conflict", "A skill or Trigger already uses this name"); + if ((error?.code ?? error?.cause?.code) === "23505") throw new ServiceError(409, "conflict", "This skill already has a trigger, or the resource name is taken"); if ((error?.code ?? error?.cause?.code) === "23503" && String(error?.constraint ?? error?.cause?.constraint).includes("manual_invocation_permissions")) throw new ServiceError(409, "run_defaults_required", "A default invocation destination is unavailable. Update Team permissions defaults."); throw error; } @@ -952,9 +1011,9 @@ export class ApiService { triggerId, })); const skillId = - input.skillId === undefined ? current.executionConfig.skillId : input.skillId; + input.skillId === undefined ? current.skill?.id ?? current.executionConfig.skillId : input.skillId; const skill = - executionType === "agent" && skillId + skillId ? (await this.skillSelections([skillId]))[0] : undefined; const updated = await repository @@ -976,7 +1035,7 @@ export class ApiService { effort: input.effort, executionConfig: { ...executionConfig, - skillId: executionType === "agent" ? (skillId ?? undefined) : undefined, + skillId: skillId ?? undefined, ...portable, executionType, ...(input.script ? { script: input.script } : {}), @@ -990,7 +1049,7 @@ export class ApiService { input.expectedUpdatedAt, ) .catch((error) => { - if ((error?.code ?? error?.cause?.code) === "23505") throw new ServiceError(409, "conflict", "A skill or Trigger already uses this name"); + if ((error?.code ?? error?.cause?.code) === "23505") throw new ServiceError(409, "conflict", "This skill already has a trigger, or the resource name is taken"); if (error instanceof StaleTriggerEdit) throw new ServiceError( 409, @@ -1087,6 +1146,7 @@ export class ApiService { async startRun(input: z.infer) { 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), auth = this.auth; if (auth.runId) { @@ -1130,7 +1190,12 @@ 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"); - const defaults = team.runDefaults; + 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 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."); @@ -1188,11 +1253,8 @@ export class ApiService { inputMediaIds:input.attachments?.map(item=>item.artifactId) ?? [], ...(input.script ? {script: input.script} : {}), }; - const skill = input.skill ? await this.skills().get(input.skill) : null; - if (input.script && skill) throw new ServiceError(400, "invalid_request", "Script runs cannot include an agent skill."); - if (input.skill && !skill) throw new ServiceError(404, "not_found", "Launch skill not found"); - 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 ? {body:skill.body!} : undefined,text); + 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 prompt = composePrompt(skill && !input.script ? {body:skill.body!} : undefined,text); const encryptedPrompt = await encrypt(prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); const encryptedSkills = skill ? await encrypt( @@ -1203,7 +1265,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, defaults]); + 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.");} const duplicate = await existing(client); if (duplicate) return duplicate; if (!locked.rows[0]?.matches) diff --git a/packages/api/src/job-domain.ts b/packages/api/src/job-domain.ts index e5338da0..669fd3d9 100644 --- a/packages/api/src/job-domain.ts +++ b/packages/api/src/job-domain.ts @@ -197,7 +197,7 @@ export class InvocationService { 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.name), createdAt, updatedAt: createdAt }; + 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 (!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."); diff --git a/packages/api/src/postgres/auth-repository.ts b/packages/api/src/postgres/auth-repository.ts index 6a74441a..92d9c16c 100644 --- a/packages/api/src/postgres/auth-repository.ts +++ b/packages/api/src/postgres/auth-repository.ts @@ -1,3 +1,4 @@ +import { usernameSchema } from "../usernames"; import { hashPassword, normalizeEmail, tokenDigest, validEmail, validPassword, verifyPassword } from "../auth"; import { sendAuthEmail, validateAuthEmailConfig } from "../auth-email"; import type { Env } from "../types"; @@ -13,15 +14,18 @@ export class AuthRepository { async signup(input: Record) { const email = normalizeEmail(String(input.email ?? "")), password = String(input.password ?? ""); if (!validEmail(email) || !validPassword(password)) return { status: 400, body: { error: "Use a valid email and a password of 12–200 characters." } }; + const username = usernameSchema.safeParse(input.username); + if (!username.success) return { status: 400, body: { error: "Choose a username of 3–39 letters/numbers with single hyphens between segments." } }; validateAuthEmailConfig(this.env); const userId = crypto.randomUUID(), passwordHash = await hashPassword(password); try { await this.database.transaction(async client => { - await client.query("INSERT INTO app.auth_users(id,email,email_verified) VALUES ($1,$2,false)", [userId, email]); + await client.query("INSERT INTO app.auth_users(id,email,email_verified,username) VALUES ($1,$2,false,$3)", [userId, email, username.data]); await client.query("INSERT INTO app.auth_accounts(id,user_id,provider,provider_account_id,password_hash) VALUES ($1,$2::uuid,'credential',$2::uuid::text,$3)", [crypto.randomUUID(), userId, passwordHash]); await this.ensurePersonalTeam(client, userId, email); }); } catch (error: any) { + if (error?.constraint === "auth_users_username_unique") return { status: 409, body: { error: "That username is already taken." } }; if (error?.code === "23505") return { status: 409, body: { error: "That email is already registered. Sign in, resend verification, or reset your password." } }; throw error; } @@ -29,12 +33,25 @@ export class AuthRepository { return { status: 201, body: { ok: true } }; } + async profile(userId: string) { + return (await this.database.pool.query<{username:string;email:string}>("SELECT username,email FROM app.auth_users WHERE id=$1", [userId])).rows[0]; + } + async updateProfile(userId: string, username: string) { + try { + const row = (await this.database.pool.query<{username:string;email:string}>("UPDATE app.auth_users SET username=$2 WHERE id=$1 RETURNING username,email", [userId, usernameSchema.parse(username)])).rows[0]; + return { status: 200, body: row }; + } catch (error: any) { + if (error?.constraint === "auth_users_username_unique") return { status: 409, body: { error: "That username is already taken." } }; + throw error; + } + } + async login(input: Record) { const email = normalizeEmail(String(input.email ?? "")), password = String(input.password ?? ""); return this.database.transaction(async client => { - const row = (await client.query<{ id: string; email: string; email_verified: boolean }>("SELECT id,email,email_verified FROM app.auth_users WHERE lower(email)=$1 FOR UPDATE", [email])).rows[0]; + const row = (await client.query<{ id: string; email: string; email_verified: boolean }>("SELECT id,email,email_verified FROM app.auth_users WHERE lower(email)=$1 OR username=$1 FOR UPDATE", [email])).rows[0]; const account = row ? (await client.query<{ password_hash: string }>("SELECT password_hash FROM app.auth_accounts WHERE user_id=$1 AND provider='credential'", [row.id])).rows[0] : null; - if (!validPassword(password) || !row || !account?.password_hash || !(await verifyPassword(password, account.password_hash))) return { status: 401, body: { error: "Invalid email or password." } }; + if (!validPassword(password) || !row || !account?.password_hash || !(await verifyPassword(password, account.password_hash))) return { status: 401, body: { error: "Invalid username, email, or password." } }; if (!row.email_verified) return { status: 403, body: { error: "Verify your email before signing in. You can resend the verification email below." } }; // Existing accounts keep their existing workspace; never derive tenancy from OAuth. const member = (await client.query<{ tenant_id: string; session_version: number }>("SELECT tenant_id,session_version FROM app.members WHERE user_id=$1 AND role='owner' ORDER BY created_at,tenant_id LIMIT 1", [row.id])).rows[0]; diff --git a/packages/api/src/postgres/automation-scheduler.ts b/packages/api/src/postgres/automation-scheduler.ts index 8e44440b..f44a44c8 100644 --- a/packages/api/src/postgres/automation-scheduler.ts +++ b/packages/api/src/postgres/automation-scheduler.ts @@ -1,3 +1,4 @@ +import { PostgresSkillContentCache } from "./skill-content-cache"; import { SkillContent } from "../skill-content"; import { decrypt, encrypt } from "../crypto"; import { InvocationError, InvocationService } from "../job-domain"; @@ -21,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)); } + 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 async schedules() { for (let count = 0; count < 50; count++) { const due = await this.database.transaction(async client => { diff --git a/packages/api/src/postgres/job-repository.ts b/packages/api/src/postgres/job-repository.ts index 1660628e..543dd125 100644 --- a/packages/api/src/postgres/job-repository.ts +++ b/packages/api/src/postgres/job-repository.ts @@ -41,11 +41,11 @@ export class PostgresTriggerRepository implements TriggerRepository { if (db === this.database.orm) { [eventRows, skillRows] = await Promise.all([ loadedEvents ?? db.select().from(events).where(and(eq(events.tenantId, this.tenantId), eq(events.triggerId, row.id), isNull(events.removedAt))).orderBy(events.position, events.createdAt, events.id), - loadedSkills?.filter(skill => skill.trigger_id === row.id) ?? this.database.pool.query("SELECT s.id,s.key,s.revision,s.encrypted_body,s.encrypted_directory,s.artifact_version,js.position,js.context_skill FROM app.trigger_skills js JOIN app.skills s ON s.tenant_id=js.tenant_id AND s.id=js.skill_id WHERE js.tenant_id=$1 AND js.trigger_id=$2 ORDER BY js.position", [this.tenantId, row.id]).then(result => result.rows), + loadedSkills?.filter(skill => skill.trigger_id === row.id) ?? this.database.pool.query("SELECT s.id,s.key,s.revision,s.encrypted_body,s.encrypted_directory,s.artifact_version,s.legacy_context,js.position,js.context_skill FROM app.trigger_skills js JOIN app.skills s ON s.tenant_id=js.tenant_id AND s.id=js.skill_id WHERE js.tenant_id=$1 AND js.trigger_id=$2 ORDER BY js.position", [this.tenantId, row.id]).then(result => result.rows), ]); } else { eventRows = loadedEvents ?? await db.select().from(events).where(and(eq(events.tenantId, this.tenantId), eq(events.triggerId, row.id), isNull(events.removedAt))).orderBy(events.position, events.createdAt, events.id); - skillRows = loadedSkills?.filter(skill => skill.trigger_id === row.id) ?? (await db.execute(sql`SELECT s.id,s.key,s.revision,s.encrypted_body,s.encrypted_directory,s.artifact_version,js.position,js.context_skill FROM app.trigger_skills js JOIN app.skills s ON s.tenant_id=js.tenant_id AND s.id=js.skill_id WHERE js.tenant_id=${this.tenantId}::uuid AND js.trigger_id=${row.id}::uuid ORDER BY js.position`)).rows; + skillRows = loadedSkills?.filter(skill => skill.trigger_id === row.id) ?? (await db.execute(sql`SELECT s.id,s.key,s.revision,s.encrypted_body,s.encrypted_directory,s.artifact_version,s.legacy_context,js.position,js.context_skill FROM app.trigger_skills js JOIN app.skills s ON s.tenant_id=js.tenant_id AND s.id=js.skill_id WHERE js.tenant_id=${this.tenantId}::uuid AND js.trigger_id=${row.id}::uuid ORDER BY js.position`)).rows; } 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), diff --git a/packages/api/src/postgres/run-query-repository.ts b/packages/api/src/postgres/run-query-repository.ts index 873e7044..839a089f 100644 --- a/packages/api/src/postgres/run-query-repository.ts +++ b/packages/api/src/postgres/run-query-repository.ts @@ -23,7 +23,7 @@ export class RunQueryRepository { if (triggerIds.length) { values.push(triggerIds); clauses.push(`r.trigger_id=ANY($${values.length}::uuid[])`); } const skill = query.get("skillId"); if (skill === "none") clauses.push("r.launch_skill_id IS NULL"); - else if (skill) { values.push(skill); clauses.push(`r.launch_skill_id=$${values.length}::uuid`); } + else if (skill) { values.push(skill); clauses.push(`(r.launch_skill_id=$${values.length}::uuid OR r.trigger_id IN (SELECT trigger_id FROM app.trigger_skills WHERE tenant_id=r.tenant_id AND skill_id=$${values.length}::uuid))`); } const states = query.getAll("state"); if (states.length) { values.push(states.flatMap(state => state === "done" ? ["done", "succeeded"] : [state])); clauses.push(`r.state=ANY($${values.length}::text[])`); } if (query.get("contextQuery")) { values.push(`%${query.get("contextQuery")}%`); clauses.push(`i.context::text ILIKE $${values.length}`); } diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 30d947b8..ccfdae00 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -17,7 +17,7 @@ export const schemaMigrations = app.table("schema_migrations", { version: text("version").primaryKey(), appliedAt: timestamp("applied_at", { withTimezone: true }).notNull().defaultNow(), }); -export const tenants = app.table("tenants", { id: uuid("id").primaryKey(), name: text("name"), createdAt: createdAt(), updatedAt: updatedAt() }); +export const tenants = app.table("tenants", { id: uuid("id").primaryKey(), personalOwnerId:uuid("personal_owner_id").references(()=>authUsers.id), name: text("name"), createdAt: createdAt(), updatedAt: updatedAt() }); export const teamSettings = app.table("team_settings", { tenantId: uuid("tenant_id").primaryKey().references(() => tenants.id, { onDelete: "cascade" }), runDefaults: jsonb("run_defaults").notNull().default({}), updatedAt: updatedAt(), @@ -27,7 +27,7 @@ export const vmPresets = app.table("vm_presets", { id: uuid("id").notNull(), name: text("name").notNull(), settings: jsonb("settings").notNull(), executionConfigId: text("execution_config_id").notNull(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("vm_presets_name").on(t.tenantId, sql`lower(${t.name})`)]); -export const authUsers = app.table("auth_users", { id: uuid("id").primaryKey(), email: text("email").notNull().unique(), emailVerified: boolean("email_verified").notNull().default(false), createdAt: createdAt() }, t => [uniqueIndex("auth_users_email_normalized").on(sql`lower(${t.email})`)]); +export const authUsers = app.table("auth_users", { id: uuid("id").primaryKey(), username:text("username").notNull().unique("auth_users_username_unique").default(sql`'user-' || replace(gen_random_uuid()::text,'-','')`), email: text("email").notNull().unique(), emailVerified: boolean("email_verified").notNull().default(false), createdAt: createdAt() }, t => [uniqueIndex("auth_users_email_normalized").on(sql`lower(${t.email})`)]); export const authAccounts = app.table("auth_accounts", { id: uuid("id").primaryKey(), userId: uuid("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }), provider: text("provider").notNull(), providerAccountId: text("provider_account_id").notNull(), passwordHash: text("password_hash"), }, t => [unique().on(t.provider, t.providerAccountId)]); @@ -124,9 +124,13 @@ export const skillLibraryBackfill = app.table("skill_library_backfill", { attemptedAt: timestamp("attempted_at", {withTimezone:true}), error: text("error"), }); export const skills = app.table("skills", { - tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), key: text("key").notNull(), encryptedBody: text("encrypted_body"), artifactVersion: jsonb("artifact_version"), encryptedDirectory: text("encrypted_directory"), revision: integer("revision").notNull().default(1), createdAt: createdAt(), updatedAt: updatedAt(), + tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), key: text("key").notNull(), runDefaults:jsonb("run_defaults").notNull(), encryptedPrompt:text("encrypted_prompt"), encryptedScript:text("encrypted_script"), settingsRevision:integer("settings_revision").notNull().default(1), legacyContext:jsonb("legacy_context").notNull().default([]), migrationPending:boolean("migration_pending").notNull().default(false), encryptedBody: text("encrypted_body"), artifactVersion: jsonb("artifact_version"), encryptedDirectory: text("encrypted_directory"), revision: integer("revision").notNull().default(1), createdAt: createdAt(), updatedAt: updatedAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.key)]); -export const triggerSkills = app.table("trigger_skills", { contextSkill:boolean("context_skill").notNull().default(true), tenantId: uuid("tenant_id").notNull(), triggerId: uuid("trigger_id").notNull(), skillId: uuid("skill_id").notNull(), position: integer("position").notNull() }, t => [primaryKey({ columns: [t.tenantId, t.triggerId, t.skillId] }), unique().on(t.tenantId, t.triggerId, t.position), uniqueIndex("trigger_one_skill").on(t.tenantId,t.triggerId), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.skillId], foreignColumns: [skills.tenantId, skills.id] }).onDelete("restrict")]); +export const skillContentCache = app.table("skill_content_cache", { + tenantId:uuid("tenant_id").notNull().references(()=>tenants.id,{onDelete:"cascade"}), + repository:text("repository").notNull(),commitSha:text("commit_sha").notNull(),encryptedContent:text("encrypted_content").notNull(),createdAt:createdAt(), +},t=>[primaryKey({columns:[t.tenantId,t.repository,t.commitSha]})]); +export const triggerSkills = app.table("trigger_skills", { skillOwned:boolean("skill_owned").notNull().default(true), contextSkill:boolean("context_skill").notNull().default(true), tenantId: uuid("tenant_id").notNull(), triggerId: uuid("trigger_id").notNull(), skillId: uuid("skill_id").notNull(), position: integer("position").notNull() }, t => [primaryKey({ columns: [t.tenantId, t.triggerId, t.skillId] }), unique().on(t.tenantId, t.triggerId, t.position), uniqueIndex("trigger_one_skill").on(t.tenantId,t.triggerId), uniqueIndex("one_trigger_per_skill").on(t.tenantId,t.skillId), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.skillId], foreignColumns: [skills.tenantId, skills.id] }).onDelete("restrict")]); export const events = app.table("events", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), triggerId: uuid("trigger_id").notNull(), kind: text("kind").$type().notNull(), slug: text("slug").notNull(), enabled: boolean("enabled").notNull().default(true), config: jsonb("config").$type>().notNull().default({}), encryptedTemplate:text("encrypted_template"), legacyTemplate:boolean("legacy_template").notNull().default(false), position: integer("position").notNull().default(0), createdAt: createdAt(), updatedAt: updatedAt(), removedAt: timestamp("removed_at", { withTimezone: true }), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("events_active_slug").on(t.tenantId, t.triggerId, t.slug).where(sql`${t.removedAt} is null`), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade"), check("no_webhook_handler_code", sql`NOT (${t.config} ? 'handlerCode')`), check("events_kind_check", sql`${t.kind} in ('manual','schedule','webhook','triggerLifecycle','triggerIdle')`)]); @@ -230,7 +234,7 @@ export const databaseSchema = { runMedia,runMediaLinks,mediaUploadAttempts,runWorkspaces,piSessions,piSessionEvents,piToolCalls, teamSettings, schemaMigrations, tenants, vmPresets, oauthConnections, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, - connections, agentIntegrations, agentIdentities, vmGrants, agentProxyResponses, integrationCollections, integrationRecords, integrationChanges, modelDeviceAuthorizations, linearWorkspaces, githubInstallations, githubSetupStates, projects, triggers, vmImageVerifications, skillLibraries, skillLibraryBackfill, skills, triggerSkills, events, webhookConditionsCutover, invocations, manualInvocationPermissions, triggerRuns, runAuthorizations, runs, runArtifacts, runRetentionCleanup, + connections, agentIntegrations, agentIdentities, vmGrants, agentProxyResponses, integrationCollections, integrationRecords, integrationChanges, modelDeviceAuthorizations, linearWorkspaces, githubInstallations, githubSetupStates, projects, triggers, vmImageVerifications, skillLibraries, skillLibraryBackfill, skills, skillContentCache, triggerSkills, events, webhookConditionsCutover, invocations, manualInvocationPermissions, triggerRuns, runAuthorizations, runs, runArtifacts, runRetentionCleanup, runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, lifecycleEvents, triggerEditDeliveries, triggerEvents, webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, runTraceCursors, runTraceChunks, runTraceProjections, traceReplayLimits, traceReplayOperations, diff --git a/packages/api/src/postgres/skill-content-cache.ts b/packages/api/src/postgres/skill-content-cache.ts new file mode 100644 index 00000000..bb59d124 --- /dev/null +++ b/packages/api/src/postgres/skill-content-cache.ts @@ -0,0 +1,16 @@ +import { encrypt,decrypt } from "../crypto"; +import type { Directory } from "../skill-files"; +import type { SkillContentCache } from "../skill-content"; +import type { Database } from "./database"; +/** Published commits are immutable. Tenant-qualified, encrypted rows can serve + * subsequent requests without retaining Worker sockets or fetching Git again. */ +export class PostgresSkillContentCache implements SkillContentCache { + constructor(private database:Database,private tenant:string,private key:string){} + async get(repository:string,commit:string):Promise{ + const row=(await this.database.pool.query("SELECT encrypted_content FROM app.skill_content_cache WHERE tenant_id=$1 AND repository=$2 AND commit_sha=$3",[this.tenant,repository,commit])).rows[0]; + return row?JSON.parse(await decrypt(row.encrypted_content,this.key)):undefined; + } + async put(repository:string,commit:string,content:Directory[]){ + await this.database.pool.query("INSERT INTO app.skill_content_cache(tenant_id,repository,commit_sha,encrypted_content) VALUES($1,$2,$3,$4) ON CONFLICT DO NOTHING",[this.tenant,repository,commit,await encrypt(JSON.stringify(content),this.key)]); + } +} diff --git a/packages/api/src/postgres/skill-repository.ts b/packages/api/src/postgres/skill-repository.ts index d1b3194a..19036276 100644 --- a/packages/api/src/postgres/skill-repository.ts +++ b/packages/api/src/postgres/skill-repository.ts @@ -3,12 +3,14 @@ import type { Database, DatabaseClient } from "./database"; 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 }; +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 }; 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, 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 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 }; } + 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, + (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) { // A shared parameter for UUID and text comparisons is inferred as UUID by // PostgreSQL. Keep the key parameter separate, and never cast keys to UUID. diff --git a/packages/api/src/postgres/webhook-service.ts b/packages/api/src/postgres/webhook-service.ts index af611686..d935a166 100644 --- a/packages/api/src/postgres/webhook-service.ts +++ b/packages/api/src/postgres/webhook-service.ts @@ -1,3 +1,4 @@ +import { PostgresSkillContentCache } from "./skill-content-cache"; import { SkillContent } from "../skill-content"; import { clickUpJson, matchingClickUpTask } from "../clickup"; import { verifyTailDelivery, sanitizeTailEvent, suppressTailEvent } from "../cloudflare-tail"; @@ -15,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)); + 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))); } 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]); diff --git a/packages/api/src/skill-content.ts b/packages/api/src/skill-content.ts index b50b40c6..6ce78742 100644 --- a/packages/api/src/skill-content.ts +++ b/packages/api/src/skill-content.ts @@ -1,9 +1,10 @@ import type { Env } from "./types"; -import { bodyOf, type Directory, type SkillVersion } from "./skill-files"; +import { bodyOf, markdown, validateLibrary, type Directory, type SkillVersion } from "./skill-files"; import { withSkillGit } from "./skill-git"; export type ArtifactVersion = { repo: string; remote: string; commit: string; key: string }; export type SkillContentRow = { + legacy_context?: (SkillContentRow & {key?:string})[]; artifact_version?: ArtifactVersion | null; encrypted_body?: string | null; encrypted_directory?: string | null; @@ -22,11 +23,15 @@ export async function repositoryToken( } } -// Request-local only. All skills in one published commit share a shallow Git fetch. +export interface SkillContentCache {get(repository:string,commit:string):Promise;put(repository:string,commit:string,content:Directory[]):Promise;} +// Request-local coalescing plus an optional durable cache of immutable commits. export class SkillContent { private versions = new Map>>(); - constructor(private binding?: Env["SKILL_ARTIFACTS"]) {} + constructor(private binding?: Env["SKILL_ARTIFACTS"], private cache?:SkillContentCache) {} private async fetch(ref: ArtifactVersion) { + const repository=JSON.stringify([ref.repo,ref.remote]); + const cached=await this.cache?.get(repository,ref.commit); + if(cached){validateLibrary(cached);return new Map(cached.map(dir=>[dir.key,dir]));} if (!this.binding) throw new Error("Skill Artifacts binding is unavailable"); const token = await repositoryToken(this.binding, ref.repo, "read"); const remote = { @@ -36,16 +41,26 @@ export class SkillContent { headers: { Authorization: "Bearer " + token.plaintext }, }; const directories = await withSkillGit(remote, (repo) => repo.directories("skills")); + validateLibrary(directories); + await this.cache?.put(repository,ref.commit,directories); return new Map(directories.map((dir) => [dir.key, dir])); } - async read(row: SkillContentRow, decrypt: (value: string) => Promise, editedBody?: string) { + async read(row: SkillContentRow, decrypt: (value:string)=>Promise, editedBody?:string): Promise<{body:string;version?:SkillVersion}> { + const base=await this.readBase(row,decrypt,editedBody); + if(!row.legacy_context?.length)return base; + const inherited=await Promise.all(row.legacy_context.map(entry=>this.read(entry,decrypt))); + const body=editedBody??[...inherited.map(entry=>entry.body),base.body].filter(Boolean).join("\n\n"); + const files=[markdown(body),...(base.version?.files??[]).filter(file=>file.path!=="SKILL.md"),...inherited.flatMap((entry,index)=>(entry.version?.files??[markdown(entry.body)]).map(file=>({...file,path:`legacy/${index+1}-${row.legacy_context![index].key??"context"}/${file.path}`})))]; + return {body,version:{commit:base.version?.commit??"migration",files}}; + } + private async readBase(row: SkillContentRow, decrypt: (value: string) => Promise, editedBody?: string) { const ref = row.artifact_version; let version: SkillVersion | undefined; if (ref) { - const cacheKey = ref.repo + ":" + ref.commit; + const cacheKey = JSON.stringify([ref.repo,ref.remote,ref.commit]); let loading = this.versions.get(cacheKey); if (!loading) { - loading = this.fetch(ref); + loading = this.fetch(ref).catch(error=>{this.versions.delete(cacheKey);throw error;}); this.versions.set(cacheKey, loading); } const directory = (await loading).get(ref.key); @@ -53,8 +68,8 @@ export class SkillContent { version = { commit: ref.commit, files: directory.files }; return { body: editedBody ?? bodyOf(directory), version }; } - if (!row.encrypted_body && editedBody === undefined) throw new Error("Skill has no published content"); + if (row.encrypted_body == null && editedBody === undefined) throw new Error("Skill has no published content"); if (row.encrypted_directory) version = JSON.parse(await decrypt(row.encrypted_directory)) as SkillVersion; - return { body: editedBody ?? (await decrypt(row.encrypted_body!)), version }; + return { body: editedBody ?? (row.encrypted_body ? await decrypt(row.encrypted_body) : ""), version }; } } diff --git a/packages/api/src/skill-library.ts b/packages/api/src/skill-library.ts index b23602cf..87fcf7dd 100644 --- a/packages/api/src/skill-library.ts +++ b/packages/api/src/skill-library.ts @@ -1,3 +1,4 @@ +import { PostgresSkillContentCache } from "./postgres/skill-content-cache"; import {publishedFiles} from "./mcp-skills"; import { SkillContent, repositoryToken, type ArtifactVersion } from "./skill-content"; import { decrypt } from "./crypto"; @@ -19,7 +20,7 @@ type LibraryRow = { error: string | null; github_tree: string | null; }; -type Current = Directory & { id: string; body: string; version?: SkillVersion; ref?: ArtifactVersion }; +type Current = Directory & { id: string; body: string; version?: SkillVersion; ref?: ArtifactVersion; migrationPending?:boolean }; function fingerprint(dir: Directory) { return JSON.stringify( dir.files @@ -112,10 +113,10 @@ export class SkillLibrary { } private async current(client: DatabaseClient, edits?: Map): Promise { const { rows } = await client.query( - "SELECT id,key,encrypted_body,encrypted_directory,artifact_version FROM app.skills WHERE tenant_id=$1 ORDER BY key FOR UPDATE", + "SELECT id,key,encrypted_body,encrypted_directory,artifact_version,legacy_context,migration_pending FROM app.skills WHERE tenant_id=$1 ORDER BY key FOR UPDATE", [this.tenant], ); - const content = new SkillContent(this.env.SKILL_ARTIFACTS); + const content = new SkillContent(this.env.SKILL_ARTIFACTS,new PostgresSkillContentCache(this.db,this.tenant,this.env.CREDENTIAL_ENCRYPTION_KEY)); return Promise.all( rows.map(async (row) => { const { body, version } = await content.read( @@ -137,6 +138,7 @@ export class SkillLibrary { version, files: version?.files ?? [markdown(body)], ref: row.artifact_version, + migrationPending:row.migration_pending, }; }), ); @@ -249,7 +251,7 @@ export class SkillLibrary { 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, + ON CONFLICT(tenant_id,key) DO UPDATE SET encrypted_body=NULL,encrypted_directory=NULL,artifact_version=excluded.artifact_version,legacy_context='[]'::jsonb, 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], ); @@ -335,16 +337,21 @@ export class SkillLibrary { } } const current = await this.current(client); - const dirs = await repo.directories( + const incoming = await repo.directories( source.kind === "managed" ? managedFolder : source.folder, current, ); + const incomingKeys=new Set(incoming.map(dir=>dir.key)); + const preserved=current.filter(dir=>dir.migrationPending&&!incomingKeys.has(dir.key)); + const dirs=[...incoming,...preserved]; + // Migration-created skills stay available until a publish adopts them. + await client.query("UPDATE app.skills SET migration_pending=false WHERE tenant_id=$1 AND key=ANY($2::text[])",[this.tenant,[...incomingKeys]]); const head = repo.head; const mirror = () => this.managed(row, "write").then((remote) => withSkillGit(remote, (repo) => repo.write(managedFolder, dirs, "Sync GitHub " + head)), ); - await this.publish(client, current, dirs, source.kind === "managed" ? head : mirror, head, tree); + await this.publish(client, current, dirs, source.kind === "managed" && !preserved.length ? head : mirror, head, tree); }; if (source.kind === "managed") await withSkillGit(await this.managed(row, "read"), reconcile); else await reconcile(await this.github(client, source)); @@ -375,7 +382,7 @@ export class SkillLibrary { this.tenant, this.env.CREDENTIAL_ENCRYPTION_KEY, client, - new SkillContent(this.env.SKILL_ARTIFACTS), + new SkillContent(this.env.SKILL_ARTIFACTS,new PostgresSkillContentCache(this.db,this.tenant,this.env.CREDENTIAL_ENCRYPTION_KEY)), edits, ); const result = await work(store); @@ -410,7 +417,7 @@ 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 WHERE tenant_id=$1 AND id=$2", + "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], ); } diff --git a/packages/api/src/skill-settings.ts b/packages/api/src/skill-settings.ts new file mode 100644 index 00000000..fb0d2e26 --- /dev/null +++ b/packages/api/src/skill-settings.ts @@ -0,0 +1,12 @@ +import { z } from "zod"; +import { teamRunDefaults } from "./flow-schemas"; +export const skillDefaults = teamRunDefaults.omit({capacity:true}).extend({ + vmImage:z.string().trim().max(512).refine(value=>teamRunDefaults.shape.vmImage.safeParse(value).success,"Enter a public Docker/OCI image reference without a URL scheme.").describe("Public Docker/OCI image reference, or blank for the provider default.").optional(), + executionType:z.enum(["agent","code"]).default("agent"), + prompt:z.string().max(50_000).default(""), + script:z.string().max(200_000).optional(), +}).strict().superRefine((value,ctx)=>{ + if(value.executionType==="code" && (!value.script?.trim() || value.requiresVm===false))ctx.addIssue({code:"custom",message:"Scripts require a script and a VM."}); +}); +export const skillSettings = z.object({revision:z.number().int().positive(),defaults:skillDefaults}); +export const skillSettingsInput = z.object({expectedRevision:z.number().int().positive(),defaults:skillDefaults}).strict(); diff --git a/packages/api/src/skill-trigger.ts b/packages/api/src/skill-trigger.ts new file mode 100644 index 00000000..f3215cf1 --- /dev/null +++ b/packages/api/src/skill-trigger.ts @@ -0,0 +1,5 @@ +import { z } from "zod"; +import { eventSchema } from "./flow-schemas"; +import { triggerResponse } from "./job-contracts"; +export const skillTriggerResponse=z.object({trigger:triggerResponse.nullable()}); +export const skillTriggerInput=z.object({events:z.array(eventSchema).max(50),enabled:z.boolean().default(true),expectedUpdatedAt:z.iso.datetime().optional()}).strict(); diff --git a/packages/api/src/skills.ts b/packages/api/src/skills.ts index c3c38da0..438658c6 100644 --- a/packages/api/src/skills.ts +++ b/packages/api/src/skills.ts @@ -6,7 +6,7 @@ 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 }); +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 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({ @@ -19,3 +19,5 @@ export type Skill = z.infer; export function composePrompt(skill: {body:string}|undefined, prompt:string):string { return [skill?.body ?? "",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/src/usernames.ts b/packages/api/src/usernames.ts new file mode 100644 index 00000000..08c6917b --- /dev/null +++ b/packages/api/src/usernames.ts @@ -0,0 +1,4 @@ +import { z } from "zod"; +export const usernameSchema = z.string().trim().toLowerCase().min(3).max(39).regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, "Use lowercase letters, numbers, and single hyphens between segments."); +export const profileInput = z.object({ username: usernameSchema }).strict(); +export const profileResponse = z.object({ username: usernameSchema, email: z.email() }).strict(); diff --git a/packages/api/test/auth-api.test.ts b/packages/api/test/auth-api.test.ts index 6ae1fcbd..20b0e92f 100644 --- a/packages/api/test/auth-api.test.ts +++ b/packages/api/test/auth-api.test.ts @@ -150,7 +150,7 @@ describe("public auth API and cookie security", () => { const signup = vi.spyOn(AuthRepository.prototype, "signup"); for (const result of [{ status: 201, body: { ok: true } }, { status: 409, body: { error: "Existing email" } }]) { signup.mockResolvedValue(result); - const response = await call("/api/v1/auth/signup", { email: "owner@test.com", password: "long-test-password" }); + const response = await call("/api/v1/auth/signup", { email: "owner@test.com", username: "owner", password: "long-test-password" }); expect(response.status).toBe(202); expect(await contract(response, "/api/v1/auth/signup", "POST")).toEqual({ ok: true }); } @@ -216,7 +216,7 @@ describe("public auth API and cookie security", () => { describe("safe interrupted-flow navigation", () => { it.each(["//evil.test", "https://evil.test", "/\\evil.test", "/device-evil", "/triggers/trigger-a/settings/extra", "/auth/logout", "/triggers\nLocation:evil", "/%2f%2fevil.test"])("rejects %s", value => expect(safeReturnTo(value)).toBe("/integrations")); - it.each(["/authorize?client_id=a&state=b", "/device?user_code=ABCD-EFGH", "/triggers/trigger-a/edit", "/triggers/trigger-a/settings?tab=prompt", "/runs", "/runs/run-a"])("preserves %s", value => expect(safeReturnTo(value)).toBe(value)); + it.each(["/authorize?client_id=a&state=b", "/device?user_code=ABCD-EFGH", "/triggers/trigger-a/edit", "/triggers/trigger-a/settings?tab=prompt", "/runs", "/runs/run-a", "/runs/run-a/trace", "/skills", "/skills/review", "/skills/review/runs", "/skills/review/settings/trigger", "/settings/profile", "/settings/skills"])("preserves %s", value => expect(safeReturnTo(value)).toBe(value)); }); describe("cookie-only consent and device API boundaries", () => { diff --git a/packages/api/test/hosted-workflow.postgres.test.ts b/packages/api/test/hosted-workflow.postgres.test.ts index d59e77f5..481c5a41 100644 --- a/packages/api/test/hosted-workflow.postgres.test.ts +++ b/packages/api/test/hosted-workflow.postgres.test.ts @@ -45,7 +45,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("complete local hosted work const request=async(method:string,path:string,body?:unknown)=>protectedApiFetch(new Request(f.env.APP_ORIGIN+path,{method,headers:{Origin:f.env.APP_ORIGIN,"Content-Type":"application/json"},...(body!==undefined?{body:JSON.stringify(body)}:{})}),f.env,owner,{waitUntil(){}} as any); const json=async(method:string,path:string,body?:unknown,status=200)=>{const response=await request(method,path,body),data=await response.json();expect(response.status,JSON.stringify(data)).toBe(status);return data as any;}; const email="workflow-"+crypto.randomUUID()+"@example.test",password="local workflow password only"; - await json("POST","/api/v1/auth/signup",{email,password},202);const token=new URL(mail.TextBody.match(/https:\/\/\S+/)[0]).searchParams.get("token"); + await json("POST","/api/v1/auth/signup",{email,username:email.split("@")[0].replaceAll("_","-").slice(0,39),password},202);const token=new URL(mail.TextBody.match(/https:\/\/\S+/)[0]).searchParams.get("token"); const verified=await request("POST","/api/v1/auth/email-verification/complete",{token});expect(verified.status).toBe(200);const session=await readSession(decodeURIComponent(verified.headers.get("Set-Cookie")!.match(/factorize_session=([^;]+)/)![1]),f.env.SESSION_SIGNING_SECRET);expect(session).not.toBeNull();owner={...session!,authMethod:"session",scopes:[...ACCESS_SCOPES]}; expect((await json("GET","/api/v1/team")).runDefaults.requiresVm).toBe(false); server=createServer(async(req,res)=>{ diff --git a/packages/api/test/native-auth.postgres.test.ts b/packages/api/test/native-auth.postgres.test.ts index d6354aed..c0ac780e 100644 --- a/packages/api/test/native-auth.postgres.test.ts +++ b/packages/api/test/native-auth.postgres.test.ts @@ -53,7 +53,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("native authentication with function token(index = sent.length - 1) { return new URL(sent[index]!.TextBody.match(/https:\/\/\S+/)![0]).searchParams.get("token")!; } async function registered() { mail(); const email = `user_${crypto.randomUUID().slice(0, 8)}@example.test`; - expect((await auth.signup({ email, password })).status).toBe(201); + expect((await auth.signup({ email, username: email.split("@")[0].toLowerCase().replaceAll("_","-").slice(0,39), password })).status).toBe(201); return { email, verification: token() }; } async function verified() { const user = await registered(); expect((await auth.completeVerification(user.verification)).status).toBe(200); return user; } @@ -122,9 +122,9 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("native authentication with ...(input ? { body: JSON.stringify(input) } : {}), }), env, null, {} as ExecutionContext, ); - expect((await json("/api/v1/auth/signup", { email, password })).status).toBe(202); + expect((await json("/api/v1/auth/signup", { email, username: email.split("@")[0].replaceAll("_","-").slice(0,39), password })).status).toBe(202); const verification = token(); - expect((await json("/api/v1/auth/signup", { email, password })).status).toBe(202); + expect((await json("/api/v1/auth/signup", { email, username: email.split("@")[0].replaceAll("_","-").slice(0,39), password })).status).toBe(202); expect((await json("/api/v1/auth/login", { email, password })).status).toBe(403); expect((await json("/api/v1/auth/email-verification/complete", { token: verification })).status).toBe(200); expect((await json("/api/v1/auth/email-verification/complete", { token: verification })).status).toBe(400); @@ -136,7 +136,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("native authentication with expect(active).toMatchObject({ authenticated: true, user: { email }, team: { role: "owner" } }); const workspaceId = active.team.id; await db.pool.query("UPDATE app.tenants SET name='API workspace' WHERE id=$1", [workspaceId]); - expect(await (await json("/api/v1/session", undefined, cookie)).json()).toMatchObject({ team: { name: "API workspace" } }); + expect(await (await json("/api/v1/session", undefined, cookie)).json()).toMatchObject({ team: { name: email.split("@")[0].replaceAll("_","-").slice(0,39) } }); const delegate = new ApiService(env, { tenantId: workspaceId, userId: active.user.id, sessionVersion: (await new IdentityRepository(db, workspaceId).member(active.user.id))!.sessionVersion, @@ -170,11 +170,11 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("native authentication with expect((await auth.completeVerification(user.verification)).status).toBe(400); expect((await auth.login({ email: user.email.toUpperCase(), password })).status).toBe(200); expect((await auth.login({ email: user.email, password: "incorrect password" })).status).toBe(401); - expect((await auth.signup({ email: user.email.toUpperCase(), password })).status).toBe(409); + expect((await auth.signup({ email: user.email.toUpperCase(), username: user.email.split("@")[0].replaceAll("_","-").slice(0,39), password })).status).toBe(409); }); it("signup never sets a session; email link GET does not consume verification", async () => { mail(); const email = `route_${crypto.randomUUID().slice(0, 8)}@example.test`; - const response = await post("/auth/signup", { email, password }); + const response = await post("/auth/signup", { email, username: email.split("@")[0].replaceAll("_","-").slice(0,39), password }); expect(response.status).toBe(201); expect(response.headers.get("set-cookie")).toBeNull(); const link = token(); expect((await app.request(`/auth/verify?token=${link}`, {}, env)).status).toBe(200); expect((await auth.login({ email, password })).status).toBe(403); @@ -236,7 +236,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("native authentication with }); it("migrates legacy Linear users through email proof while preserving workspace and connection", async () => { mail(); - expect((await auth.signup({ email: "legacy@example.test", password })).status).toBe(409); + expect((await auth.signup({ email: "legacy@example.test", username: "legacy", password })).status).toBe(409); await auth.requestReset({ email: "legacy@example.test" }); expect((await auth.completeReset({ token: token(), password })).status).toBe(200); const login = await auth.login({ email: "legacy@example.test", password }); @@ -320,9 +320,9 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("native authentication with it("fails closed on missing Postmark configuration and allows retry after delivery failure", async () => { const broken = new AuthRepository(db, { ...env, POSTMARK_SERVER_TOKEN: undefined }); - await expect(broken.signup({ email: "config@example.test", password })).rejects.toThrow("Authentication email requires"); + await expect(broken.signup({ email: "config@example.test", username: "config", password })).rejects.toThrow("Authentication email requires"); vi.stubGlobal("fetch", vi.fn(async () => Response.json({ ErrorCode: 400 }, { status: 422 }))); - await expect(auth.signup({ email: "retry@example.test", password })).rejects.toThrow("Postmark"); + await expect(auth.signup({ email: "retry@example.test", username: "retry", password })).rejects.toThrow("Postmark"); expect((await auth.login({ email: "retry@example.test", password })).status).toBe(403); mail(); await auth.requestEmail({ email: "retry@example.test" }, "verify"); expect((await auth.completeVerification(token())).status).toBe(200); diff --git a/packages/api/test/oauth-onboarding.postgres.test.ts b/packages/api/test/oauth-onboarding.postgres.test.ts index 26325dbf..a5f85373 100644 --- a/packages/api/test/oauth-onboarding.postgres.test.ts +++ b/packages/api/test/oauth-onboarding.postgres.test.ts @@ -41,7 +41,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP onboarding public boun } it("signs up, verifies, signs in automatically and explicitly consents once with original state/PKCE", async () => { mail(); const a = await start("new-user"), account = email(); - expect((await call("/api/v1/auth/signup", { email: account, password, connection: a.connection }, a.cookie)).status).toBe(202); + expect((await call("/api/v1/auth/signup", { email: account, username: account.split("@")[0].replaceAll("_","-").slice(0,39), password, connection: a.connection }, a.cookie)).status).toBe(202); expect(await (await call("/api/v1/auth/connections/resume", { connection: a.connection }, a.cookie)).json()).toMatchObject({ pending: true, clientName: "MCP CLI" }); const verification = token(); const verified = await call("/api/v1/auth/email-verification/complete", { token: verification }, a.cookie); expect(verified.status).toBe(200); const body = await verified.json() as any, cookie = a.cookie + "; " + cookieOf(verified); @@ -55,7 +55,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP onboarding public boun }); it("verifies in another browser but allows callback consent only in the initiating browser; denial is final", async () => { mail(); const a = await start("another-browser"), account = email(); - await call("/api/v1/auth/signup", { email: account, password, connection: a.connection }, a.cookie); + await call("/api/v1/auth/signup", { email: account, username: account.split("@")[0].replaceAll("_","-").slice(0,39), password, connection: a.connection }, a.cookie); const verified = await call("/api/v1/auth/email-verification/complete", { token: token() }); expect(await verified.json()).toEqual({ ok: true, crossBrowser: true }); const foreign = cookieOf(verified), returnTo = a.destination + `&connection=${a.connection}`; expect((await call("/api/v1/oauth/consent/preview", { authorizationQuery: returnTo.split("?")[1] }, foreign)).status).toBe(400); @@ -70,7 +70,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP onboarding public boun it("isolates simultaneous requests through resend, existing-account login and password recovery", async () => { mail(); const a = await start("a"), b = await start("b"), account = email(), cookies = a.cookie + "; " + b.cookie; expect(a.cookie.split("=")[0]).not.toBe(b.cookie.split("=")[0]); - await call("/api/v1/auth/signup", { email: account, password, connection: a.connection }, cookies); const first = token(); + await call("/api/v1/auth/signup", { email: account, username: account.split("@")[0].replaceAll("_","-").slice(0,39), password, connection: a.connection }, cookies); const first = token(); await call("/api/v1/auth/email-verification/request", { email: account, connection: b.connection }, cookies); const second = token(); for (const [t, c] of [[first, a], [second, b]]) { const verified = await call("/api/v1/auth/email-verification/complete", { token: t }, cookies); expect(verified.status).toBe(200); expect((await verified.json() as any).returnTo).toContain(`connection=${c.connection}`); } const c = await start("existing"), signed = await call("/api/v1/auth/login", { email: account, password, connection: c.connection }, c.cookie); @@ -84,8 +84,8 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP onboarding public boun it("rejects forged/expired connections and revoked verification without extending the client request", async () => { mail(); for (const returnTo of ["https://evil.test", "//evil.test", destination("bad").replace("127.0.0.1", "evil.test"), destination("bad").replace("S256", "plain")]) expect((await call("/api/v1/auth/connections", { returnTo })).status).toBe(400); const a = await start("expired"), account = email(); - expect((await call("/api/v1/auth/signup", { email: account, password, connection: a.connection })).status).toBe(400); - await call("/api/v1/auth/signup", { email: account, password, connection: a.connection }, a.cookie); const verification = token(); + expect((await call("/api/v1/auth/signup", { email: account, username: account.split("@")[0].replaceAll("_","-").slice(0,39), password, connection: a.connection })).status).toBe(400); + await call("/api/v1/auth/signup", { email: account, username: account.split("@")[0].replaceAll("_","-").slice(0,39), password, connection: a.connection }, a.cookie); const verification = token(); await f.db.pool.query("UPDATE app.oauth_connections SET expires_at=now()-interval '1 second' WHERE id=$1", [a.connection]); expect((await call("/api/v1/auth/email-verification/request", { email: account, connection: a.connection }, a.cookie)).status).toBe(400); const verified = await call("/api/v1/auth/email-verification/complete", { token: verification }, a.cookie); expect(verified.status).toBe(200); expect(await verified.json()).toMatchObject({ returnTo: "/auth/login?expired=1" }); @@ -98,7 +98,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP onboarding public boun async function device() { return await (await deviceAuthorization(new Request(f.env.APP_ORIGIN + "/oauth/device_authorization", { method: "POST", body: new URLSearchParams({ client_id: "client", scope: "team:read triggers:read integrations:read" }) }), f.env, oauth as any, ["team:read", "triggers:read", "integrations:read"])).json() as any; } it("continues device signup in the verification browser and rejects unsigned, cross-owner and forged consent", async () => { mail(); const issued = await device(), a = await start("device", `/device?user_code=${issued.user_code}`), account = email(); - await call("/api/v1/auth/signup", { email: account, password, connection: a.connection }, a.cookie); + await call("/api/v1/auth/signup", { email: account, username: account.split("@")[0].replaceAll("_","-").slice(0,39), password, connection: a.connection }, a.cookie); const verified = await call("/api/v1/auth/email-verification/complete", { token: token() }), cookie = cookieOf(verified); expect((await verified.json() as any).returnTo).toContain("/device?user_code="); expect(grant).not.toHaveBeenCalled(); const preview = await (await call("/api/v1/oauth/device/preview", { userCode: issued.user_code }, cookie)).json() as any; diff --git a/packages/api/test/pages-smoke.e2e.test.ts b/packages/api/test/pages-smoke.e2e.test.ts index f1abca08..ed076d29 100644 --- a/packages/api/test/pages-smoke.e2e.test.ts +++ b/packages/api/test/pages-smoke.e2e.test.ts @@ -72,7 +72,7 @@ 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", ready: heading("Team settings") }, + "settings": { path: () => "/settings", destination: () => "/settings/vm", ready: heading("VM settings") }, "VM presets": { path: () => "/settings/vm-presets", ready: heading("VM presets") }, "legacy integrations": { path: () => "/settings/integrations", destination: () => "/integrations", ready: heading("Available integrations") }, "integrations": { path: () => "/integrations", ready: heading("Available integrations") }, diff --git a/packages/api/test/skill-content-cache.postgres.test.ts b/packages/api/test/skill-content-cache.postgres.test.ts new file mode 100644 index 00000000..284e24dc --- /dev/null +++ b/packages/api/test/skill-content-cache.postgres.test.ts @@ -0,0 +1,50 @@ +import { beforeAll,afterAll,afterEach,describe,expect,it,vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { SkillContent } from "../src/skill-content"; +import { PostgresSkillContentCache } from "../src/postgres/skill-content-cache"; +import { withSkillGit } from "../src/skill-git"; +import { markdown,type Directory } from "../src/skill-files"; +import { ApiService } from "../src/flow-service"; +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()})); +vi.mock("../src/skill-git",()=>({withSkillGit:vi.fn()})); +describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("persistent skill directory cache",()=>{ + let f:Awaited>,id:string,dirs:Directory[]; + const ref={repo:"fixture",remote:"https://local.test/library.git",commit:"a".repeat(40),key:"cached-skill"}; + beforeAll(async()=>{ + f=await loadingFixture(process.env.AUTH_TEST_DATABASE_URL!);id=crypto.randomUUID(); + f.env.SKILL_ARTIFACTS={get:async()=>({createToken:async()=>({plaintext:"fixture-token"})})} as any; + dirs=[{key:ref.key,files:[markdown("Cached instructions"),{path:"nested/file.txt",content:btoa("Nested text"),executable:false},{path:"image.bin",content:btoa("\x00\xff"),executable:false}]}]; + vi.mocked(withSkillGit).mockImplementation(async()=>structuredClone(dirs) as any); + await f.db.pool.query("INSERT INTO app.skills(tenant_id,id,key,artifact_version) VALUES($1,$2,$3,$4)",[f.tenantId,id,ref.key,ref]); + }); + afterAll(async()=>{await f?.cleanup();}); + const service=()=>new ApiService(f.env,{...f.auth,scopes:[...f.auth.scopes,"skills:read"]}); + it("fetches once across independent API requests and encrypts cached content",async()=>{ + const first=await service().getSkillDirectory(id);expect(first.files).toHaveLength(3); + expect((await service().getSkillDirectory(id)).files).toEqual(first.files); + expect(withSkillGit).toHaveBeenCalledTimes(1); + const encrypted=(await f.db.pool.query("SELECT encrypted_content FROM app.skill_content_cache WHERE tenant_id=$1",[f.tenantId])).rows[0].encrypted_content; + expect(encrypted).not.toContain("Cached instructions");expect(await decrypt(encrypted,f.env.CREDENTIAL_ENCRYPTION_KEY)).toContain("nested/file.txt"); + }); + it("selects new commits after edits/sync and preserves older pinned commits",async()=>{ + dirs=[{key:ref.key,files:[markdown("New instructions")]}]; + await f.db.pool.query("UPDATE app.skills SET artifact_version=$3,revision=revision+1 WHERE tenant_id=$1 AND id=$2",[f.tenantId,id,{...ref,commit:"b".repeat(40)}]); + const next=await service().getSkillDirectory(id);expect(next.revision).toBe(2);expect(atob(next.files[0].content)).toBe("New instructions");expect(withSkillGit).toHaveBeenCalledTimes(2); + const old=await new SkillContent(undefined,new PostgresSkillContentCache(f.db,f.tenantId,f.env.CREDENTIAL_ENCRYPTION_KEY)).read({artifact_version:ref},async value=>value); + expect(old.body).toBe("Cached instructions");expect(withSkillGit).toHaveBeenCalledTimes(2); + }); + it("isolates tenants, rejects paths before caching and reads warm versions during upstream failure",async()=>{ + const otherCache=new PostgresSkillContentCache(f.db,f.otherTenant,f.env.CREDENTIAL_ENCRYPTION_KEY); + expect(await otherCache.get(JSON.stringify([ref.repo,ref.remote]),ref.commit)).toBeUndefined(); + const privateId=crypto.randomUUID();await f.db.pool.query("INSERT INTO app.skills(tenant_id,id,key,artifact_version) VALUES($1,$2,'private-context',$3)",[f.otherTenant,privateId,ref]); + await expect(service().getSkillDirectory(privateId)).rejects.toMatchObject({status:404}); + dirs=[{key:ref.key,files:[markdown("Invalid"),{path:"../secret",content:"",executable:false}]}]; + await expect(new SkillContent(f.env.SKILL_ARTIFACTS,otherCache).read({artifact_version:ref},async value=>value)).rejects.toThrow(); + expect(await otherCache.get(JSON.stringify([ref.repo,ref.remote]),ref.commit)).toBeUndefined(); + vi.mocked(withSkillGit).mockRejectedValue(new Error("Upstream offline")); + expect((await service().getSkillDirectory(id)).revision).toBe(2); + await expect(new SkillContent(f.env.SKILL_ARTIFACTS,otherCache).read({artifact_version:ref},async value=>value)).rejects.toThrow("Upstream offline"); + }); +}); diff --git a/packages/api/test/skill-library.postgres.test.ts b/packages/api/test/skill-library.postgres.test.ts index a1c6e42e..86e464e5 100644 --- a/packages/api/test/skill-library.postgres.test.ts +++ b/packages/api/test/skill-library.postgres.test.ts @@ -334,6 +334,8 @@ it.skipIf(!process.env.AUTH_TEST_DATABASE_URL)( mirrorHead = "e".repeat(40); mirrored = [{ key: "renamed", files: [markdown("Managed push")] }]; snapshots.set(mirrorHead, mirrored); + const migratedId=crypto.randomUUID(); + await f.db.pool.query("INSERT INTO app.skills(tenant_id,id,key,encrypted_body,migration_pending) VALUES($1,$2,'migrated-context',$3,true)",[f.tenantId,migratedId,await encrypt("Preserved migration context",f.env.CREDENTIAL_ENCRYPTION_KEY)]); const workflow = Object.assign(Object.create(SkillPushWorkflow.prototype), { env: f.env }); await workflow.run( { @@ -345,6 +347,10 @@ it.skipIf(!process.env.AUTH_TEST_DATABASE_URL)( { do: (_label: string, run: () => Promise) => run() }, ); expect(await store.get("renamed")).toMatchObject({ body: "Managed push", revision: 1 }); + expect(await store.get(migratedId)).toMatchObject({body:"Preserved migration context"}); + mirrorHead="f".repeat(40);mirrored=[{key:"renamed",files:[markdown("Another upstream push")]}];snapshots.set(mirrorHead,structuredClone(mirrored)); + await library.sync(); + expect(await store.get(migratedId)).toMatchObject({body:"Preserved migration context"}); } finally { await f.cleanup(); } diff --git a/packages/api/test/skill-ownership-migration.postgres.test.ts b/packages/api/test/skill-ownership-migration.postgres.test.ts new file mode 100644 index 00000000..d1624cb6 --- /dev/null +++ b/packages/api/test/skill-ownership-migration.postgres.test.ts @@ -0,0 +1,55 @@ +import { SkillContent } from "../src/skill-content"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { readFile,readdir } from "node:fs/promises"; +import { Database } from "../src/postgres/database"; +import { SkillRepository } from "../src/postgres/skill-repository"; +import { RunQueryRepository } from "../src/postgres/run-query-repository"; +import { encrypt,decrypt } from "../src/crypto"; +import { markdown } from "../src/skill-files"; +describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("trigger-to-skill context migration",()=>{ + const name="skill_migration_"+crypto.randomUUID().replaceAll("-",""); + const tenant=crypto.randomUUID(),oldSkill=crypto.randomUUID(),key=btoa("a".repeat(32)),ids=Array.from({length:4},()=>crypto.randomUUID()),runId=crypto.randomUUID(); + let admin:Database,db:Database,store:SkillRepository; + beforeAll(async()=>{ + admin=new Database({connectionString:process.env.AUTH_TEST_DATABASE_URL});await admin.pool.query(`CREATE DATABASE ${name}`); + const url=new URL(process.env.AUTH_TEST_DATABASE_URL!);url.pathname="/"+name;db=new Database({connectionString:url.href}); + const dir=new URL("../migrations/",import.meta.url); + for(const file of (await readdir(dir)).filter(f=>f.endsWith(".sql")).sort()){ + if(file==="0084_migrate_trigger_skills.sql"){ + await db.pool.query("INSERT INTO app.tenants(id) VALUES($1)",[tenant]); + await db.pool.query("INSERT INTO app.skills(tenant_id,id,key,encrypted_body,encrypted_directory) VALUES($1,$2,'attached-context',$3,$4)",[tenant,oldSkill,await encrypt("Original instructions",key),await encrypt(JSON.stringify({commit:"old",files:[markdown("Original instructions"),{path:"nested/context.txt",content:btoa("Supporting context"),executable:false}]}),key)]); + for(const [i,id] of ids.entries()){ + const config=i===3?{executionType:"code",requiresVm:true,connectionId:"local",script:"echo legacy-script"}:{executionType:"agent",requiresVm:false}; + await db.pool.query("INSERT INTO app.triggers(tenant_id,id,name,slug,encrypted_prompt,execution_config,model,concurrency_limit) VALUES($1,$2,$3,$3,$4,$5,'legacy-model',2)",[tenant,id,"legacy-"+i,await encrypt("Original prompt "+i,key),config]); + await db.pool.query("INSERT INTO app.events(tenant_id,id,trigger_id,kind,slug,encrypted_template) VALUES($1,$2,$3,'manual','manual',$4)",[tenant,crypto.randomUUID(),id,await encrypt("Event context {{manual.prompt}}",key)]); + } + await db.pool.query("INSERT INTO app.trigger_skills(tenant_id,trigger_id,skill_id,position,skill_owned) VALUES($1,$2,$3,0,false),($1,$4,$3,0,false)",[tenant,ids[1],oldSkill,ids[2]]); + await db.pool.query("INSERT INTO app.manual_invocation_permissions(tenant_id,source_trigger_id,destination_trigger_id) VALUES($1,$2,$3)",[tenant,ids[0],ids[1]]); + await db.pool.query("INSERT INTO app.invocations(tenant_id,id,trigger_id,source,claim_key,context) VALUES($1,$2,$3,'manual','historic','{}')",[tenant,runId,ids[0]]); + await db.pool.query("INSERT INTO app.trigger_runs(tenant_id,id,trigger_id,invocation_id,state,encrypted_prompt) VALUES($1,$2,$3,$2,'succeeded',$4)",[tenant,runId,ids[0],await encrypt("Historic prompt",key)]); + await db.pool.query("INSERT INTO app.runs(tenant_id,id,invocation_id,trigger_id,provider,issue_id,agent_name,agent_kind,state,execution_backend_kind,execution_config) VALUES($1,$2,$2,$3,'manual','historic','','pi','succeeded','hosted-pi','{}')",[tenant,runId,ids[0]]); + } + await db.pool.query(await readFile(new URL(file,dir),"utf8")); + } + store=new SkillRepository(db,tenant,key); + }); + afterAll(async()=>{await db?.close();if(admin){await admin.pool.query(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`);await admin.close();}}); + it("creates a distinct skill for every old trigger and retains original skills",async()=>{ + const links=(await db.pool.query("SELECT * FROM app.trigger_skills WHERE tenant_id=$1",[tenant])).rows; + expect(links).toHaveLength(4);expect(new Set(links.map(r=>r.skill_id)).size).toBe(4); + expect(await store.get(oldSkill)).toMatchObject({body:"Original instructions"}); + for(const [i,id] of ids.entries()){ + const row=(await db.pool.query("SELECT s.*,t.encrypted_prompt trigger_prompt,t.execution_config FROM app.trigger_skills ts JOIN app.skills s ON s.tenant_id=ts.tenant_id AND s.id=ts.skill_id JOIN app.triggers t ON t.tenant_id=ts.tenant_id AND t.id=ts.trigger_id WHERE ts.tenant_id=$1 AND ts.trigger_id=$2",[tenant,id])).rows[0]; + const skill=await store.get(row.id);expect(skill!.body).toContain("Original prompt "+i);expect(row.trigger_prompt).toBe("");expect(row.run_defaults.concurrencyLimit).toBe(2); + if(i===1||i===2){const edited=await new SkillContent().read(row,value=>decrypt(value,key),"Edited instructions");expect(edited.body).toBe("Edited instructions");expect(edited.version!.files.some(file=>file.path.endsWith("nested/context.txt"))).toBe(true);expect(skill!.body).toContain("Original instructions");expect(skill!.version!.files.some(f=>f.path.endsWith("nested/context.txt")&&f.content===btoa("Supporting context"))).toBe(true);} + if(i===3)expect(row.execution_config.script).toBe("echo legacy-script"); + } + }); + it("preserves event templates, workflow links, historical runs, and provenance",async()=>{ + const rows=(await db.pool.query("SELECT encrypted_template FROM app.events WHERE tenant_id=$1",[tenant])).rows; + for(const row of rows)expect(await decrypt(row.encrypted_template,key)).toBe("Event context {{manual.prompt}}"); + expect((await db.pool.query("SELECT * FROM app.manual_invocation_permissions WHERE tenant_id=$1",[tenant])).rows).toHaveLength(1); + expect((await new RunQueryRepository(db,tenant).list(new URLSearchParams())).items.some(r=>r.id===runId)).toBe(true); + expect((await db.pool.query("SELECT * FROM app.configuration_diagnostics WHERE tenant_id=$1 AND code='skill_owned_migration'",[tenant])).rows).toHaveLength(4); + }); +}); diff --git a/packages/api/test/skill-settings.postgres.test.ts b/packages/api/test/skill-settings.postgres.test.ts new file mode 100644 index 00000000..faa8a0c6 --- /dev/null +++ b/packages/api/test/skill-settings.postgres.test.ts @@ -0,0 +1,86 @@ +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 { loadingFixture } from "./helpers/loading-fixture"; +import { ApiService } from "../src/flow-service"; +import { encrypt, decrypt } from "../src/crypto"; +import { skillDefaults } from "../src/skill-settings"; +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); + }); + +}); diff --git a/packages/api/test/usernames.postgres.test.ts b/packages/api/test/usernames.postgres.test.ts new file mode 100644 index 00000000..f5480fbe --- /dev/null +++ b/packages/api/test/usernames.postgres.test.ts @@ -0,0 +1,58 @@ +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { readFile } from "node:fs/promises"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { AuthRepository } from "../src/postgres/auth-repository"; +import { protectedApiFetch } from "../src/protected-api"; +import { usernameSchema } from "../src/usernames"; +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)("usernames and profile", () => { + let f: Awaited>, repo: AuthRepository; + beforeAll(async () => { f = await loadingFixture(process.env.AUTH_TEST_DATABASE_URL!); Object.assign(f.env, { POSTMARK_SERVER_TOKEN:"local", POSTMARK_FROM_EMAIL:"accounts@example.test", POSTMARK_MESSAGE_STREAM:"outbound" }); repo = new AuthRepository(f.db, f.env); }); + afterAll(async () => { await f?.cleanup(); }); + afterEach(() => vi.unstubAllGlobals()); + it("requires usernames, normalizes case, and supports both password identifiers", async () => { + vi.stubGlobal("fetch", vi.fn(async () => Response.json({ ErrorCode:0 }))); + const email="alice@example.test", password="local password for tests"; + expect((await repo.signup({email,password})).status).toBe(400); + for (const value of ["ab","a".repeat(40),"-abc","abc-","ab--cd","ab_cd","a.b"]) expect(usernameSchema.safeParse(value).success).toBe(false); + expect((await repo.signup({email,password,username:"Alice-Smith"})).status).toBe(201); + await f.db.pool.query("UPDATE app.auth_users SET email_verified=true WHERE email=$1",[email]); + expect((await repo.login({email:"ALICE-SMITH",password})).status).toBe(200); + expect((await repo.login({email,password})).status).toBe(200); + expect((await repo.signup({email:"other@example.test",password,username:"alice-smith"})).status).toBe(409); + }); + it("authorizes profile changes, validates input, and arbitrates concurrent claims", async () => { + const request = (body:unknown,cookie=f.cookie) => protectedApiFetch(new Request(f.env.APP_ORIGIN+"/api/v1/profile", {method:"PUT",headers:{Origin:f.env.APP_ORIGIN,Cookie:cookie,"Content-Type":"application/json"},body:JSON.stringify(body)}),f.env,null,{} as ExecutionContext); + expect((await request({username:"valid-name"},"")).status).toBe(401); + expect((await request({username:"bad_name"})).status).toBe(400); + expect((await request({username:"New-Owner"})).status).toBe(200); + expect(await repo.profile(f.userId)).toMatchObject({username:"new-owner"}); + expect((await f.db.pool.query("SELECT name FROM app.tenants WHERE id=$1",[f.tenantId])).rows[0].name).toBe("new-owner"); + await f.db.pool.query("UPDATE app.tenants SET name='cannot-edit' WHERE id=$1",[f.tenantId]); + expect((await f.db.pool.query("SELECT name FROM app.tenants WHERE id=$1",[f.tenantId])).rows[0].name).toBe("new-owner"); + const other=crypto.randomUUID(); + await f.db.pool.query("INSERT INTO app.auth_users(id,email,email_verified) VALUES($1,'claim@example.test',true)",[other]); + const results=await Promise.all([repo.updateProfile(f.userId,"shared-name"),repo.updateProfile(other,"shared-name")]); + expect(results.map(r=>r.status).sort()).toEqual([200,409]); + expect((await f.db.pool.query("SELECT t.name,u.username FROM app.tenants t JOIN app.auth_users u ON u.id=t.personal_owner_id WHERE t.id=$1",[f.tenantId])).rows[0]).toEqual({name:(await repo.profile(f.userId))!.username,username:(await repo.profile(f.userId))!.username}); + expect((await f.db.pool.query("SELECT count(*) FROM app.auth_users WHERE username='shared-name'")).rows[0].count).toBe("1"); + }); + it("backfills migration prefixes and diagnoses invalid/colliding values", async () => { + const sql=await readFile(new URL("../migrations/0080_usernames.sql",import.meta.url),"utf8"); + // Test the real migration against an isolated shadow schema in a rolled-back transaction. + const client=await f.db.pool.connect(); + try { + for (const [emails,expected] of [[["Legacy@one.test"],"legacy"],[["bad_name@one.test"],"not a valid username"],[["same@one.test","same@two.test"],"duplicate email prefixes"]] as const) { + await client.query("BEGIN"); + await client.query("CREATE SCHEMA username_migration; CREATE TABLE username_migration.auth_users(id uuid DEFAULT gen_random_uuid(),email text); CREATE TABLE username_migration.schema_migrations(version text PRIMARY KEY)"); + for(const email of emails)await client.query("INSERT INTO username_migration.auth_users(email) VALUES($1)",[email]); + try { + await client.query(sql.replaceAll("app.","username_migration.")); + expect((await client.query("SELECT username FROM username_migration.auth_users")).rows[0].username).toBe(expected); + } catch(error:any) { expect(error.message).toContain(expected); } + await client.query("ROLLBACK"); + } + } finally { await client.query("ROLLBACK"); client.release(); } + }); +}); diff --git a/packages/app/src/features/auth/account-bar.tsx b/packages/app/src/features/auth/account-bar.tsx index 50e98e7e..249fed28 100644 --- a/packages/app/src/features/auth/account-bar.tsx +++ b/packages/app/src/features/auth/account-bar.tsx @@ -1,3 +1,5 @@ +import { TeamNavigation } from "./team-navigation"; +import { skillQuery, skillsQuery } from "../skills/queries"; import { useEffect, useRef, useState } from "react"; import { Button } from "../../shared/ui"; import { SearchLauncher } from "../search/launcher"; @@ -7,21 +9,20 @@ import { useMutation, useQuery } from "@tanstack/react-query"; import { api } from "factorize-api-client"; import { messageOf, refreshIdentity, sessionQuery } from "./session"; import { triggerQuery, triggersQuery } from "../jobs/queries"; -import { runStatusQuery } from "../runs/queries"; import { ResourceSwitcher } from "../../shared/resource-switcher"; -import { NavIcon } from "../../shared/nav-icon"; import beeMark from "../../assets/bee-mark-monochrome.png"; export function AccountBar() { const session = useQuery(sessionQuery); const authenticated = session.data?.authenticated; const pathname = useRouterState({ select: state => state.location.pathname }); + const skillMatch = pathname.match(/^\/skills\/([^/]+)/); + const routeSkillId = skillMatch ? decodeURIComponent(skillMatch[1]) : undefined; + const routeSkill = useQuery({...skillQuery(routeSkillId??""),enabled:!!authenticated&&!!routeSkillId}); + const skillOptions = useQuery({...skillsQuery(),enabled:!!authenticated&&!!routeSkillId}); const triggerMatch = pathname.match(/^\/triggers\/([^/]+)/); const routeTriggerId = triggerMatch && triggerMatch[1] !== "new" ? decodeURIComponent(triggerMatch[1]) : undefined; - const runMatch = pathname.match(/^\/runs\/([^/]+)/); - const routeRunId = runMatch && runMatch[1] !== "new" ? decodeURIComponent(runMatch[1]) : undefined; - const routeRun = useQuery({ ...runStatusQuery(routeRunId ?? ""), enabled: !!authenticated && !!routeRunId }); - const currentTriggerId = routeTriggerId ?? routeRun.data?.trigger_id; + const currentTriggerId = routeTriggerId; const routeTrigger = useQuery({ ...triggerQuery(currentTriggerId ?? ""), enabled: !!authenticated && !!currentTriggerId, retry: false }); const projectTriggers = useQuery({ ...triggersQuery({ sort: "title" }), enabled: !!authenticated && !!currentTriggerId }); const navigate = useNavigate(); @@ -52,7 +53,9 @@ export function AccountBar() {