From b6e7b02f74710af393bf310d72d7e9350fd43712 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Thu, 19 Nov 2026 21:00:50 +0000 Subject: [PATCH] Version skill directories in Artifacts and sync GitHub-backed libraries --- docs/skill-repositories.md | 48 + package-lock.json | 1413 ++++++++++++++++- package.json | 3 +- packages/api-client/src/schema.d.ts | 256 +++ .../api/migrations/0062_skill_libraries.sql | 11 + packages/api/package.json | 3 +- packages/api/src/api-contract.ts | 5 + packages/api/src/cloudflare-entry.ts | 28 + packages/api/src/execution.ts | 1 + packages/api/src/factorize-job-launcher.ts | 15 +- packages/api/src/flow-service.ts | 25 +- packages/api/src/github.ts | 4 +- packages/api/src/index.ts | 2 + packages/api/src/job-domain.ts | 4 +- packages/api/src/launch-payload.ts | 5 +- .../api/src/machine-job-execution-backend.ts | 3 +- packages/api/src/postgres/job-repository.ts | 6 +- packages/api/src/postgres/run-repository.ts | 8 +- packages/api/src/postgres/run-scheduler.ts | 4 +- packages/api/src/postgres/schema.ts | 9 +- packages/api/src/postgres/skill-repository.ts | 21 +- packages/api/src/protected-api.ts | 2 + packages/api/src/skill-files.ts | 73 + packages/api/src/skill-git.ts | 204 +++ packages/api/src/skill-github.ts | 161 ++ packages/api/src/skill-library-contract.ts | 32 + packages/api/src/skill-library.ts | 328 ++++ packages/api/src/types.ts | 1 + packages/api/src/worker.ts | 10 +- .../test/fixtures/agent-api-runtime-worker.ts | 1 + .../api/test/skill-library.postgres.test.ts | 224 +++ packages/api/test/skill-library.test.ts | 148 ++ packages/api/wrangler.jsonc | 7 +- packages/app/src/features/skills/detail.tsx | 4 +- packages/app/src/features/skills/library.tsx | 5 +- .../app/src/features/skills/repository.tsx | 226 +++ packages/docs/openapi.yaml | 425 +++++ scripts/agent-api-runtime.test.mjs | 3 +- scripts/api-wrangler.mjs | 5 + scripts/hosting-runtime.test.mjs | 53 +- scripts/oauth-runtime.test.mjs | 3 +- scripts/worker-infrastructure-baseline.json | 7 +- 42 files changed, 3742 insertions(+), 54 deletions(-) create mode 100644 docs/skill-repositories.md create mode 100644 packages/api/migrations/0062_skill_libraries.sql create mode 100644 packages/api/src/cloudflare-entry.ts create mode 100644 packages/api/src/skill-files.ts create mode 100644 packages/api/src/skill-git.ts create mode 100644 packages/api/src/skill-github.ts create mode 100644 packages/api/src/skill-library-contract.ts create mode 100644 packages/api/src/skill-library.ts create mode 100644 packages/api/test/skill-library.postgres.test.ts create mode 100644 packages/api/test/skill-library.test.ts create mode 100644 packages/app/src/features/skills/repository.tsx create mode 100644 scripts/api-wrangler.mjs diff --git a/docs/skill-repositories.md b/docs/skill-repositories.md new file mode 100644 index 00000000..27ac89b1 --- /dev/null +++ b/docs/skill-repositories.md @@ -0,0 +1,48 @@ +# Skill repositories + +Open **Skills → Connect Git repository**. Factorize-managed libraries use the +`main` branch and `skills//SKILL.md`. A first skill edit with Artifacts +enabled also creates a managed library and seeds the current skills. Existing +job links, literal prompt bodies and revision checks continue to work. + +**Get Git credential** issues a one-hour write token for the selected managed +repository. Copy the remote and token from the Skills page. For example: + +```sh +git -c http.extraHeader="Authorization: Bearer $ARTIFACTS_TOKEN" clone "$ARTIFACTS_REMOTE" my-skills +cd my-skills +# Edit skills//SKILL.md and its supporting files, then commit. +git -c http.extraHeader="Authorization: Bearer $ARTIFACTS_TOKEN" push origin main +``` + +For GitHub, select an active installation, repository, branch and dedicated +skills folder. Each immediate subdirectory must contain a UTF-8 SKILL.md. +Choose a branch with at least one commit. The initial connection publishes +its skills and commits any existing Factorize skills missing from that folder +to GitHub. A protected or read-only branch can be seeded through a PR before +connecting. Repo pushes and merges update the published library. +Factorize editor, REST and MCP changes commit to the selected branch; a +protected branch can require users to make changes through a PR on GitHub. +Switching sources creates a fresh Artifacts repo. The previous repo retains +its history and no longer publishes to this library. + +A library accepts regular files, including executable scripts and binary +assets, up to 8 MiB total and 2,000 entries. Managed synchronization uses +a shallow fetch limited to 16 MiB. The existing 100,000-character limit +applies to each SKILL.md. A move of an entire, uniquely identifiable skill +directory preserves job references. Use the Factorize editor to rename a +referenced skill and change its instructions together. Invalid commits leave +the last accepted version active. Fix the branch and push again or use +**Sync now**. Queued runs retain their selected file bytes and commit. +Agents can read `$FACTORIZE_SKILLS_DIR//` at launch. + +## Deployment + +Apply migration 0062 before deploying the Worker. Provision the Artifacts +namespace `factorize-skills` before deployment. The Wrangler configuration registers the +`factorize-skill-push` Workflow for pushes in that namespace. The Workflow +publishes the managed repository’s main branch. +The scheduled reconciliation retries missed events. Configure the existing +GitHub App to subscribe to push events with Contents read access, and grant +Contents write access for editor commits. Existing installations may need +to approve the permission change. Deploy the additive v1 API before the UI. diff --git a/package-lock.json b/package-lock.json index 4dcd3ce1..21f514cc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4650,6 +4650,27 @@ "node": ">=12" } }, + "node_modules/async-lock": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/async-lock/-/async-lock-1.5.0.tgz", + "integrity": "sha512-JgULma1mWaHlyJ67lvicyel5Cq+k55bXafE0gyvJBdHkH0vdE/IGGDF1glNyRInisNS6pZL2oho96S6Hw68kfQ==", + "license": "MIT" + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/axe-core": { "version": "4.13.0", "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.13.0.tgz", @@ -4734,6 +4755,53 @@ "node": ">=8" } }, + "node_modules/call-bind": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", + "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "get-intrinsic": "^1.3.0", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/ccount": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", @@ -4831,6 +4899,12 @@ "integrity": "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==", "license": "MIT" }, + "node_modules/clean-git-ref": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/clean-git-ref/-/clean-git-ref-2.0.1.tgz", + "integrity": "sha512-bLSptAy2P0s6hU4PzuIMKmMJJSE6gLXGH1cntDu7bWJUksvuM+7ReOK61mozULErYvP6a15rnYl0zFDef+pyPw==", + "license": "Apache-2.0" + }, "node_modules/clone": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", @@ -4922,6 +4996,18 @@ "integrity": "sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg==", "license": "MIT" }, + "node_modules/crc-32": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz", + "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==", + "license": "Apache-2.0", + "bin": { + "crc32": "bin/crc32.njs" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/cron-parser": { "version": "5.10.1", "resolved": "https://registry.npmjs.org/cron-parser/-/cron-parser-5.10.1.tgz", @@ -5075,6 +5161,21 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/deep-eql": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", @@ -5085,6 +5186,23 @@ "node": ">=6" } }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/dequal": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", @@ -5124,6 +5242,12 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/diff3": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/diff3/-/diff3-0.0.3.tgz", + "integrity": "sha512-iSq8ngPOt0K53A6eVr4d5Kn6GNrM2nQZtC740pzIriHtn4pOQ2lyzEXQMBeVcWERN0ye7fhBsk9PbLLQOnUx/g==", + "license": "MIT" + }, "node_modules/drizzle-kit": { "version": "0.31.10", "resolved": "https://registry.npmjs.org/drizzle-kit/-/drizzle-kit-0.31.10.tgz", @@ -5749,6 +5873,20 @@ } } }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/enhanced-resolve": { "version": "5.24.5", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.24.5.tgz", @@ -5786,6 +5924,24 @@ "url": "https://github.com/sponsors/antfu" } }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/es-module-lexer": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", @@ -5793,6 +5949,18 @@ "dev": true, "license": "MIT" }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/esbuild": { "version": "0.28.2", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", @@ -5952,6 +6120,21 @@ } } }, + "node_modules/for-each": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", + "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -5967,6 +6150,52 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/get-tsconfig": { "version": "4.14.3", "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.14.3.tgz", @@ -5987,6 +6216,18 @@ "dev": true, "license": "BSD-2-Clause" }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/graceful-fs": { "version": "4.2.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", @@ -6013,12 +6254,63 @@ "node": ">=20.0.0" } }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/hash-it": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/hash-it/-/hash-it-6.0.1.tgz", "integrity": "sha512-qhl8+l4Zwi1eLlL3lja5ywmDQnBzLEJxd0QJoAVIgZpgQbdtVZrN5ypB0y3VHwBlvAalpcbM2/A6x7oUks5zNg==", "license": "MIT" }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/hast-util-to-jsx-runtime": { "version": "2.3.6", "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz", @@ -6092,6 +6384,15 @@ "node": ">= 14" } }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, "node_modules/index-to-position": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/index-to-position/-/index-to-position-1.2.0.tgz", @@ -6105,6 +6406,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, "node_modules/inline-style-parser": { "version": "0.2.7", "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz", @@ -6142,6 +6449,18 @@ "dev": true, "license": "MIT" }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-decimal": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz", @@ -6174,6 +6493,27 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is-typed-array": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz", + "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==", + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "license": "MIT" + }, "node_modules/isbot": { "version": "5.2.2", "resolved": "https://registry.npmjs.org/isbot/-/isbot-5.2.2.tgz", @@ -6183,6 +6523,30 @@ "node": ">=18" } }, + "node_modules/isomorphic-git": { + "version": "1.44.17", + "resolved": "https://registry.npmjs.org/isomorphic-git/-/isomorphic-git-1.44.17.tgz", + "integrity": "sha512-jVTvfct/ZDqutRKOWSnTTLtbkKSXlvV5bWOkRpW143tsDfUxZsnNqSPq8BgNpsviuD9OuQ/1Sz8reNb/+daVSQ==", + "license": "MIT", + "dependencies": { + "async-lock": "^1.4.1", + "clean-git-ref": "^2.0.1", + "crc-32": "^1.2.0", + "diff3": "0.0.3", + "ignore": "^5.1.4", + "minimisted": "^2.0.0", + "pako": "^1.0.10", + "pify": "^4.0.1", + "sha.js": "^2.4.12", + "simple-get": "^4.0.1" + }, + "bin": { + "isogit": "cli.cjs" + }, + "engines": { + "node": ">=14.17" + } + }, "node_modules/jiti": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", @@ -6601,6 +6965,15 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/mdast-util-from-markdown": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.1.0.tgz", @@ -7232,6 +7605,18 @@ "node": ">=10.0.0" } }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/miniflare": { "version": "5.20260910.0-alpha", "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20260910.0-alpha.tgz", @@ -7263,6 +7648,24 @@ "node": ">=10" } }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minimisted": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/minimisted/-/minimisted-2.0.1.tgz", + "integrity": "sha512-1oPjfuLQa2caorJUM8HV8lGgWCc0qqAO1MNv/k05G4qslmsndV/5WdNZrqCiyqiz3wohia2Ij2B7w2Dr7/IyrA==", + "license": "MIT", + "dependencies": { + "minimist": "^1.2.5" + } + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -7297,6 +7700,15 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, "node_modules/openapi-fetch": { "version": "0.17.0", "resolved": "https://registry.npmjs.org/openapi-fetch/-/openapi-fetch-0.17.0.tgz", @@ -7333,6 +7745,12 @@ "integrity": "sha512-OKTGPthhivLw/fHz6c3OPtg72vi86qaMlqbJuVJ23qOvQ+53uw1n7HdmkJFibloF7QEjDrDkzJiOJuockM/ljw==", "license": "MIT" }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "license": "(MIT AND Zlib)" + }, "node_modules/parse-entities": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz", @@ -7509,6 +7927,15 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pify": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", + "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/playwright": { "version": "1.64.0", "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.0.tgz", @@ -7548,6 +7975,15 @@ "node": ">=4" } }, + "node_modules/possible-typed-array-names": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", + "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/postcss": { "version": "8.5.29", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz", @@ -7807,6 +8243,26 @@ "fsevents": "~2.3.2" } }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, "node_modules/scheduler": { "version": "0.28.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", @@ -7847,6 +8303,43 @@ "seroval": "^1.0" } }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/sha.js": { + "version": "2.4.12", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.12.tgz", + "integrity": "sha512-8LzC5+bvI45BjpfXU8V5fdU2mfeKiQe1D1gIMn7XUlF3OTUrpdJpPPH4EMAnF0DsHHdSZqCdSss5qCmJKuiO3w==", + "license": "(MIT AND BSD-3-Clause)", + "dependencies": { + "inherits": "^2.0.4", + "safe-buffer": "^5.2.1", + "to-buffer": "^1.2.0" + }, + "bin": { + "sha.js": "bin.js" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/sharp": { "version": "0.35.4", "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.4.tgz", @@ -7904,6 +8397,51 @@ "dev": true, "license": "ISC" }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, "node_modules/simple-swizzle": { "version": "0.2.4", "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz", @@ -8129,6 +8667,20 @@ "node": ">=14.0.0" } }, + "node_modules/to-buffer": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/to-buffer/-/to-buffer-1.2.2.tgz", + "integrity": "sha512-db0E3UJjcFhpDhAF4tLo03oli3pwl3dbnzXOUIlRKrp+ldk/VUxzpWYZENsw2SZiuBjHAk7DfB0VU7NKdpb6sw==", + "license": "MIT", + "dependencies": { + "isarray": "^2.0.5", + "safe-buffer": "^5.2.1", + "typed-array-buffer": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/trim-lines": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", @@ -8189,6 +8741,20 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/typed-array-buffer": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", + "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -8542,6 +9108,27 @@ "node": ">=12" } }, + "node_modules/which-typed-array": { + "version": "1.1.24", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.24.tgz", + "integrity": "sha512-wk4Mf4pR5mRP7eYuuTBCIQ9d0ud2Fv2jRLQpfgnRjbOxAFHmjKFValgTpitVKzJJS8ajnYQV2Du1SZ8j6b/EUQ==", + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/why-is-node-running": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", @@ -9100,6 +9687,12 @@ "@esbuild/win32-x64": "0.28.1" } }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, "node_modules/ws": { "version": "8.21.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", @@ -9246,6 +9839,7 @@ "cron-parser": "^5.10.1", "drizzle-orm": "^0.45.2", "hono": "^4.11.4", + "isomorphic-git": "^1.44.17", "json-rules-engine": "^7.3.1", "jsonpath-plus": "^10.3.0", "mustache": "^4.2.0", @@ -9265,7 +9859,7 @@ "tsx": "^4.23.15", "typescript": "^5.9.3", "vitest": "^3.2.4", - "wrangler": "^4.44.0", + "wrangler": "4.163.0", "yaml": "^2.9.1" } }, @@ -9280,6 +9874,823 @@ "typescript": "^5.9.3" } }, + "packages/api/node_modules/@cloudflare/unenv-preset": { + "version": "2.16.2", + "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.2.tgz", + "integrity": "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ==", + "dev": true, + "license": "MIT OR Apache-2.0", + "peerDependencies": { + "unenv": "2.0.0-rc.24", + "workerd": ">1.20260305.0 <2.0.0-0" + }, + "peerDependenciesMeta": { + "workerd": { + "optional": true + } + } + }, + "packages/api/node_modules/@cloudflare/workerd-darwin-64": { + "version": "1.20261116.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20261116.1.tgz", + "integrity": "sha512-+zzaR7CQXcT10Tbor784vI80+rO0NEy/jkTL7ZJP6PYmwjdDj2udk+sN9Ui1nqDs+frYYUtB+7nI7kycONFb0Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "packages/api/node_modules/@cloudflare/workerd-darwin-arm64": { + "version": "1.20261116.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20261116.1.tgz", + "integrity": "sha512-jOZBuQL3FdFC9FcVzfSDEWu1/jx3/asrQAU7TydMop8kdZWhqT4dslE3rC6cMait6w32XaglzEtV6OM1Ove9ZA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16" + } + }, + "packages/api/node_modules/@cloudflare/workerd-linux-64": { + "version": "1.20261116.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20261116.1.tgz", + "integrity": "sha512-/HnEV29Ykg3t9X6llrnlOJ9+N+cXFNsuPTTdRiE1L/hXIkI39o1RZVjEgj3GtyWtpuhsJ1mNLrNshrEjCvzk0w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "packages/api/node_modules/@cloudflare/workerd-linux-arm64": { + "version": "1.20261116.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20261116.1.tgz", + "integrity": "sha512-hH73ERVfyoQ19DzbjPv/Gp4klU6F7gpx99JIlkmelC3vfsXPpsJdJsNAJA8LIxILa+gfH7tfxSSciCzr+0vqOQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16" + } + }, + "packages/api/node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20261116.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20261116.1.tgz", + "integrity": "sha512-eUxFymDyGt3jYjE3/OsNZlSYM5jjCKx8h4nlGRdljtK1fRUT+llI8COE/1gaqMppS6x8qN6tc8vcyRXT4pxqxw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, + "packages/api/node_modules/@cloudflare/workers-types": { + "version": "5.20261119.1", + "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-5.20261119.1.tgz", + "integrity": "sha512-TSAVVAUehPUN1idYKaUwJTUhrdKBdlb1jdbA0+OaLQgHHCnOT32oAexu/Aw48CG2NpzSZ7kqi6nIFcO/+t6k5w==", + "dev": true, + "license": "MIT OR Apache-2.0" + }, + "packages/api/node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" + } + }, + "packages/api/node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "packages/api/node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.4" + } + }, + "packages/api/node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "packages/api/node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "packages/api/node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" + } + }, + "packages/api/node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.4" + } + }, + "packages/api/node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.4" + } + }, + "packages/api/node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" + } + }, + "packages/api/node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" + } + }, + "packages/api/node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "packages/api/node_modules/miniflare": { + "version": "5.20261116.0-beta", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261116.0-beta.tgz", + "integrity": "sha512-vQozfXz0eh4VlXJPsn/sxV3siRHmhl5kghZplFsTAt7+8gSPmjbZkYQEA4VudmcN9HTbI8pOqPynckIaIenwPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "0.8.1", + "sharp": "0.35.5", + "undici": "7.30.1", + "workerd": "1.20261116.1", + "ws": "8.21.0", + "youch": "4.1.0-beta.10" + }, + "engines": { + "node": ">=22.12.0" + }, + "peerDependencies": { + "kerberos": "^2.0.0" + }, + "peerDependenciesMeta": { + "kerberos": { + "optional": true + } + } + }, + "packages/api/node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "packages/api/node_modules/undici": { + "version": "7.30.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz", + "integrity": "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "packages/api/node_modules/workerd": { + "version": "1.20261116.1", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261116.1.tgz", + "integrity": "sha512-w3uPBuALjYs4n/p6x5SodorOe5y1bsBZ3RYeH1g0W5l73vT+yPGI7/WtxfzXbxZqpeCZ0/RfEwgD8Pc43uzu+w==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20261116.1", + "@cloudflare/workerd-darwin-arm64": "1.20261116.1", + "@cloudflare/workerd-linux-64": "1.20261116.1", + "@cloudflare/workerd-linux-arm64": "1.20261116.1", + "@cloudflare/workerd-windows-64": "1.20261116.1" + } + }, + "packages/api/node_modules/wrangler": { + "version": "4.163.0", + "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.163.0.tgz", + "integrity": "sha512-EBM/QOpQsce6LenEDv1nXsK+AX9BYfAhE5yHosriPhFZPj47Z0usk6oGYWgPpLPa5qYDzhm9EDzaDD/WI5lzOA==", + "dev": true, + "license": "MIT OR Apache-2.0", + "dependencies": { + "@cloudflare/kv-asset-handler": "0.5.0", + "@cloudflare/unenv-preset": "2.16.2", + "@cspotcode/source-map-support": "0.8.1", + "blake3-wasm": "2.1.5", + "esbuild": "0.28.2", + "miniflare": "5.20261116.0-beta", + "path-to-regexp": "6.3.0", + "unenv": "2.0.0-rc.24", + "workerd": "1.20261116.1" + }, + "bin": { + "cf-wrangler": "bin/cf-wrangler.js", + "wrangler": "bin/wrangler.js", + "wrangler2": "bin/wrangler.js" + }, + "engines": { + "node": ">=22.12.0" + }, + "optionalDependencies": { + "fsevents": "2.3.3" + }, + "peerDependencies": { + "@cloudflare/workers-types": "^5.20261116.1" + }, + "peerDependenciesMeta": { + "@cloudflare/workers-types": { + "optional": true + } + } + }, "packages/app": { "name": "factorize-app", "version": "0.1.0", diff --git a/package.json b/package.json index 11dc8bcc..32eb3d33 100644 --- a/package.json +++ b/package.json @@ -50,6 +50,7 @@ "esbuild@0.28.1": true, "sharp@0.33.5": true, "workerd@1.20251118.0": true, - "workerd@1.20260910.1": true + "workerd@1.20260910.1": true, + "workerd@1.20261116.1": true } } diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 02f8714a..a66711e7 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1536,6 +1536,78 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/skill-library": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Read skill repository settings + * @description Requires the skills:read scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + get: operations["get_api_v1_skill_library"]; + /** + * Select the authoritative skills repository + * @description Requires the skills:write scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + put: operations["put_api_v1_skill_library"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/skill-library/token": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Issue a one-hour repository write credential + * @description Requires the skills:write scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + post: operations["post_api_v1_skill_library_token"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/skill-library/sync": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Synchronize the tracked branch + * @description Requires the skills:write scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + post: operations["post_api_v1_skill_library_sync"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/skills": { parameters: { query?: never; @@ -6643,6 +6715,185 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_skill_library: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Read skill repository settings */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + source: ({ + /** @constant */ + kind: "managed"; + } | { + /** @constant */ + kind: "github"; + installationId: number; + repositoryId: number; + branch: string; + folder: string; + }) | null; + remote: string | null; + commit: string | null; + upstreamCommit: string | null; + error: 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_skill_library: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** @constant */ + kind: "managed"; + } | { + /** @constant */ + kind: "github"; + installationId: number; + repositoryId: number; + branch: string; + folder: string; + }; + }; + }; + responses: { + /** @description Select the authoritative skills repository */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + source: ({ + /** @constant */ + kind: "managed"; + } | { + /** @constant */ + kind: "github"; + installationId: number; + repositoryId: number; + branch: string; + folder: string; + }) | null; + remote: string | null; + commit: string | null; + upstreamCommit: string | null; + error: 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"]; + }; + }; + post_api_v1_skill_library_token: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Issue a one-hour repository write credential */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + remote: string; + token: string; + expiresAt: string; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_skill_library_sync: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Synchronize the tracked branch */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + source: ({ + /** @constant */ + kind: "managed"; + } | { + /** @constant */ + kind: "github"; + installationId: number; + repositoryId: number; + branch: string; + folder: string; + }) | null; + remote: string | null; + commit: string | null; + upstreamCommit: string | null; + error: string | null; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; get_api_v1_skills: { parameters: { query?: { @@ -7771,6 +8022,11 @@ export interface operations { [key: string]: unknown; }; prompt: string; + skillFiles?: { + path: string; + content: string; + executable: boolean; + }[]; harness: { executable: string; args: string[]; diff --git a/packages/api/migrations/0062_skill_libraries.sql b/packages/api/migrations/0062_skill_libraries.sql new file mode 100644 index 00000000..f97acdcd --- /dev/null +++ b/packages/api/migrations/0062_skill_libraries.sql @@ -0,0 +1,11 @@ +CREATE TABLE app.skill_libraries ( + tenant_id uuid PRIMARY KEY REFERENCES app.tenants(id) ON DELETE CASCADE, + repo text NOT NULL UNIQUE, + remote text NOT NULL, + source jsonb NOT NULL, + commit_sha text, + upstream_sha text, + error text, + checked_at timestamptz +); +ALTER TABLE app.skills ADD COLUMN encrypted_directory text; diff --git a/packages/api/package.json b/packages/api/package.json index c1bcab28..37dc87db 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -27,6 +27,7 @@ "cron-parser": "^5.10.1", "drizzle-orm": "^0.45.2", "hono": "^4.11.4", + "isomorphic-git": "^1.44.17", "json-rules-engine": "^7.3.1", "jsonpath-plus": "^10.3.0", "mustache": "^4.2.0", @@ -46,7 +47,7 @@ "tsx": "^4.23.15", "typescript": "^5.9.3", "vitest": "^3.2.4", - "wrangler": "^4.44.0", + "wrangler": "4.163.0", "yaml": "^2.9.1" } } diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index a4248518..d21295bf 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -1,3 +1,4 @@ +import { librarySource,libraryStatus,libraryToken } from "./skill-library-contract"; import { grantVmInput, vmGrantReceipt, apiReflection, apiPolicyList, apiPolicyInput, requestApiInput, requestApiResponse, readApiResponseInput, apiResponseChunk } from "./agent-api-contracts"; import { queryOf } from "./query-params"; import { launchPayloadResponse } from "./launch-payload"; @@ -812,6 +813,10 @@ export const API_ROUTES: RouteContract[] = [ route("GET", "/api/v1/projects/{projectId}/graph", "flows:read", { summary: "Get a project's workflow graph", description: "Returns every job in the project and configured lifecycle, idle, manual invocation permission, and external webhook source connections. Connections are derived from executable trigger configuration and current permission grants. Webhook edge labels are short readable provider or event names; details may include configured technical resource identifiers as secondary context.", responses: { "200": { description: "Complete project graph", content: { "application/json": { schema: jsonSchema(projectGraphResponse, "output") } } } } }, (service, { params }) => service.getProjectGraph(params.projectId)), route("PUT", "/api/v1/projects/{projectId}", "flows:write", { summary: "Update project", responses: { "200": { description: "Updated", content: { "application/json": { schema: jsonSchema(projectResponse, "output") } } } } }, (service, { params, body }) => service.updateProject(params.projectId, body), { body: projectInput }), route("DELETE", "/api/v1/projects/{projectId}", "flows:write", { summary: "Delete empty project", responses: { "200": { description: "Deleted" } } }, (service, { params }) => service.deleteProject(params.projectId)), + route("GET", "/api/v1/skill-library", "skills:read", { summary: "Read skill repository settings", responses: { "200": { description: "Read skill repository settings", content: { "application/json": { schema: jsonSchema(libraryStatus, "output") } } } } }, (service) => service.skillLibraryStatus()), + 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:librarySource}), + route("POST", "/api/v1/skill-library/token", "skills:write", { summary: "Issue a one-hour repository write credential", responses: { "200": { description: "Issue a one-hour repository write credential", 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", "skills:read", { summary: "Search global skills", responses: { "200": { description: "Skills", content: { "application/json": { schema: jsonSchema(skillPage, "output") } } } } }, (service, { query }) => service.listSkills(query), { query: skillQuery }), route("POST", "/api/v1/skills", "skills:write", { summary: "Create a global skill", responses: { "201": { description: "Created", content: { "application/json": { schema: jsonSchema(skillResponse, "output") } } } } }, (service, { body }) => service.createSkill(body), { body: skillInput }), route("POST", "/api/v1/skills/preview", "skills:read", { summary: "Preview a composed job prompt", responses: { "200": { description: "Prompt preview" } } }, (service, { body }) => service.previewJobPrompt(body), { body: previewSkillInput }), diff --git a/packages/api/src/cloudflare-entry.ts b/packages/api/src/cloudflare-entry.ts new file mode 100644 index 00000000..c10166e5 --- /dev/null +++ b/packages/api/src/cloudflare-entry.ts @@ -0,0 +1,28 @@ +import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers"; +import { databaseFor } from "./postgres/database"; +import { SkillLibrary } from "./skill-library"; +import type { Env } from "./types"; + +export { default, AlarmCoordinator } from "./worker"; + +type Push = { + type: "cf.artifacts.repo.pushed"; + source: { namespace: string; repoName: string }; + payload: { ref: string }; +}; + +export class SkillPushWorkflow extends WorkflowEntrypoint { + async run(event: WorkflowEvent, step: WorkflowStep) { + const { source, payload } = event.payload; + if (source.namespace !== "factorize-skills" || payload.ref !== "refs/heads/main") return; + await step.do("Publish skill directories", async () => { + const row = ( + await databaseFor(this.env).pool.query( + "SELECT tenant_id FROM app.skill_libraries WHERE repo=$1 AND source->>'kind'='managed'", + [source.repoName], + ) + ).rows[0]; + if (row) await new SkillLibrary(this.env, row.tenant_id).sync({ repo: source.repoName }); + }); + } +} diff --git a/packages/api/src/execution.ts b/packages/api/src/execution.ts index 9c8490f1..b5f49134 100644 --- a/packages/api/src/execution.ts +++ b/packages/api/src/execution.ts @@ -20,6 +20,7 @@ export interface LaunchRequest { runIdentity?: { backendOrigin: string }; /** The exact payload has been persisted for the VM to fetch with its vendor identity. */ fetchLaunchPayload?: boolean; + skillFiles?: import("./skill-files").SkillFile[]; traceSources?: TraceSources; harness?: { executable: string; args: string[]; env: Record }; code?: { script: string; context: Record }; diff --git a/packages/api/src/factorize-job-launcher.ts b/packages/api/src/factorize-job-launcher.ts index bdaea462..0129867b 100644 --- a/packages/api/src/factorize-job-launcher.ts +++ b/packages/api/src/factorize-job-launcher.ts @@ -1,5 +1,6 @@ /** Small guest-side supervisor shared by Fly and exe.dev execution backends. */ export const FACTORIZE_JOB_LAUNCHER = String.raw`#!/usr/bin/env python3 +import base64 import json import os import pathlib @@ -117,7 +118,19 @@ def launch(foreground=False, run_id=None): pathlib.Path(trace).parent.mkdir(mode=0o700, parents=True, exist_ok=True) pathlib.Path(trace).touch(mode=0o600, exist_ok=True) command, stdin, env = child_command(payload) - PAYLOAD.write_text(json.dumps({key: value for key, value in payload.items() if key != 'prompt'}), encoding='utf-8') + if payload.get('skillFiles'): + skills = pathlib.Path(tempfile.mkdtemp(prefix='skills-', dir=ROOT)) + for file in payload['skillFiles']: + parts = file['path'].split('/') + if len(parts) < 2 or any(not part or part in ('.', '..') or part.lower() == '.git' or '\\' in part for part in parts): + raise ValueError('invalid skill file path') + destination = skills.joinpath(*parts) + destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + with destination.open('xb') as stream: + stream.write(base64.b64decode(file['content'], validate=True)) + destination.chmod(0o700 if file['executable'] else 0o600) + env['FACTORIZE_SKILLS_DIR'] = str(skills) + PAYLOAD.write_text(json.dumps({key: value for key, value in payload.items() if key not in ('prompt', 'skillFiles')}), encoding='utf-8') input_path = ROOT / 'prompt.txt' input_path.write_bytes(stdin) save(STATE, {'state': 'starting'}) diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 30354fd3..59fbab8e 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -1,3 +1,5 @@ +import { SkillLibrary } from "./skill-library"; +import { librarySource } from "./skill-library-contract"; import { submitRun } from "./postgres/run-submission"; import type { DatabaseClient } from "./postgres/database"; import { startRunInput,projectRunDefaults } from "./flow-schemas"; @@ -343,11 +345,26 @@ export class ApiService { lastRunState: stats?.last_run_state ?? null, }); } + private library() { return new SkillLibrary(this.env,this.auth.tenantId); } + async skillLibraryStatus() { await this.authorize("skills:read"); return this.library().status(); } + async configureSkillLibrary(input: unknown) { + await this.authorize("skills:write"); + const source = librarySource.parse(input); + if (source.kind === "github") await this.authorize("integrations:write"); + try { return await this.library().configure(source); } + catch (e) { if (e instanceof SkillConflict) throw new ServiceError(409,"skill_conflict",e.message); throw e; } + } + async skillLibraryToken() { + await this.authorize("skills:write"); + try { return await this.library().token(); } + catch (e) { if (e instanceof SkillConflict) throw new ServiceError(409,"skill_conflict",e.message); throw e; } + } + async syncSkillLibrary() { await this.authorize("skills:write"); const library=this.library(); await library.sync(); return library.status(); } async listSkills(query: { q: string; limit: number; cursor?: string }) { await this.authorize("skills:read"); return publicValue(skillPage, await this.skills().list(query.q, query.limit, query.cursor)); } async getSkill(id: string) { await this.authorize("skills:read"); const value = await this.skills().get(id); if (!value) throw new ServiceError(404, "not_found", "Skill not found"); return publicValue(skillResponse, value); } - async createSkill(input: unknown) { await this.authorize("skills:write"); return publicValue(skillResponse, await this.skills().create(skillInput.parse(input).key, skillInput.parse(input).body)); } - async updateSkill(id: string, input: unknown) { await this.authorize("skills:write"); try { const value = await this.skills().update(id, skillUpdateInput.parse(input)); if (!value) throw new ServiceError(404, "not_found", "Skill not found"); return publicValue(skillResponse, value); } catch (e) { if (e instanceof SkillConflict) throw new ServiceError(409, "stale_skill", e.message); throw e; } } - async deleteSkill(id: string, expectedRevision: number) { await this.authorize("skills:write"); try { if (!await this.skills().remove(id, expectedRevision)) throw new ServiceError(404, "not_found", "Skill not found"); return { id, deleted: true }; } catch (e) { if (e instanceof SkillReferenced) throw new ServiceError(409, "skill_referenced", `${e.message} Jobs: ${e.jobs.map(job => job.name).join(", ")}`); if (e instanceof SkillConflict) throw new ServiceError(409, "stale_skill", e.message); throw e; } } + async 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} Jobs: ${e.jobs.map(job => job.name).join(", ")}`); if (e instanceof SkillConflict) throw new ServiceError(409, "stale_skill", e.message); throw e; } } async listSkillJobs(id: string) { await this.authorize("skills:read"); return publicValue(skillJobsResponse, { skillId: id, jobs: await this.skills().jobs(id) }); } async previewJobPrompt(input: unknown) { await this.authorize("skills:read"); const parsed = previewSkillInput.parse(input); const skills = await Promise.all(parsed.skillIds.map(async id => { const skill = await this.skills().get(id); if (!skill) throw new ServiceError(400, "invalid_request", "A selected skill is unavailable."); return skill; })); return { prompt: composePrompt(skills.map(skill => ({ body: skill.body ?? "" })), parsed.jobContext), skills: skills.map(skill => ({ id: skill.id, key: skill.key, revision: skill.revision })) }; } @@ -1018,7 +1035,7 @@ export class ApiService { const encryptedSkills = skill ? await encrypt( JSON.stringify([ - { id: skill.id, key: skill.key, revision: skill.revision, body: skill.body, order: 0 }, + { id: skill.id, key: skill.key, revision: skill.revision, body: skill.body, version: skill.version, order: 0 }, ]), this.env.CREDENTIAL_ENCRYPTION_KEY, ) diff --git a/packages/api/src/github.ts b/packages/api/src/github.ts index d7788c87..19798e93 100644 --- a/packages/api/src/github.ts +++ b/packages/api/src/github.ts @@ -24,10 +24,10 @@ function wrapPkcs1AsPkcs8(pkcs1: Uint8Array): Uint8Array { return Uint8Array.from([0x30, ...derLength(body.length), ...body]); } -export async function installationToken(env: { GITHUB_APP_ID?: string; GITHUB_APP_PRIVATE_KEY?: string }, installationId: number): Promise { +export async function installationToken(env: { GITHUB_APP_ID?: string; GITHUB_APP_PRIVATE_KEY?: string }, installationId: number, repositoryId?: number): Promise { if (!env.GITHUB_APP_ID || !env.GITHUB_APP_PRIVATE_KEY) throw new Error("GitHub App credentials are not configured"); const jwt = await createAppJwt(env.GITHUB_APP_ID, env.GITHUB_APP_PRIVATE_KEY.replaceAll("\\n", "\n")); - const response = await fetch(`https://api.github.com/app/installations/${installationId}/access_tokens`, { method: "POST", headers: githubHeaders(jwt) }); + const response = await fetch(`https://api.github.com/app/installations/${installationId}/access_tokens`, { method: "POST", headers: githubHeaders(jwt), ...(repositoryId ? { body: JSON.stringify({repository_ids:[repositoryId]}) } : {}) }); const body = await response.json() as { token?: string; message?: string }; if (!response.ok || !body.token) throw new Error(body.message ?? `GitHub token request failed (${response.status})`); return body.token; diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index 9aa26437..c9fa6f3a 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -1,3 +1,4 @@ +import { SkillLibrary } from "./skill-library"; import { executeAuth } from "./auth-api"; import { STATIC_CSP, staticApp } from "./static-app"; import { Hono } from "hono"; @@ -220,6 +221,7 @@ app.post("/webhooks/github", async (c) => { return c.body(null, 202); } if (registration.state !== "active") return c.body(null, 202); + if (eventName === "push") await new SkillLibrary(c.env,registration.tenant_id).sync({installationId,repositoryId:event.repository?.id,ref:event.ref}); await new WebhookService(databaseFor(c.env), c.env, registration.tenant_id).github(event, `github:${delivery}`, eventName); return c.body(null, 202); }); diff --git a/packages/api/src/job-domain.ts b/packages/api/src/job-domain.ts index 9b7c2454..cef9798d 100644 --- a/packages/api/src/job-domain.ts +++ b/packages/api/src/job-domain.ts @@ -38,7 +38,7 @@ export interface Trigger { updatedAt: string; } -export interface JobSkill { id: string; key: string; revision: number; body: string; position: number } +export interface JobSkill { version?: import("./skill-files").SkillVersion; id: string; key: string; revision: number; body: string; position: number } export interface Job { id: string; @@ -177,7 +177,7 @@ export class InvocationService { const createdAt = this.clock(); const invocation: Invocation = { id: this.makeId(), jobId, source: input.source, claimKey: input.claimKey, triggerId: input.triggerId, context: input.context, ...(input.sourceJobId ? { sourceJobId: input.sourceJobId } : {}), ...(input.sourceRunId ? { sourceRunId: input.sourceRunId } : {}), ...(input.occurrence ? { occurrence: input.occurrence } : {}), createdAt }; const selectedSkills = promptSkills(job); - const run: JobRun = { id: this.makeId(), jobId, invocationId: invocation.id, state: "queued", launchSkill: job.launchSkill, encryptedPrompt: await this.encryptPrompt(renderJobPrompt(job, input.context)), encryptedSkillSnapshot: selectedSkills.length ? await this.encryptSnapshot(JSON.stringify(selectedSkills.map((skill,order) => ({ id: skill.id, key: skill.key, revision: skill.revision, body: skill.body, order })))) : undefined, runName: (input.source === "manual" ? input.name?.trim() : undefined) || renderRunName(job.runNameTemplate ?? "", input.context, job.name), createdAt, updatedAt: createdAt }; + const run: JobRun = { id: this.makeId(), jobId, invocationId: invocation.id, state: "queued", launchSkill: job.launchSkill, encryptedPrompt: await this.encryptPrompt(renderJobPrompt(job, input.context)), 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(job.runNameTemplate ?? "", input.context, job.name), createdAt, updatedAt: createdAt }; if (!await this.repository.insertInvocationAndRun(invocation, run)) { const winner = await this.repository.findInvocation(jobId, input.claimKey); if (!winner) throw new Error("Invocation claim was lost without a persisted winner."); diff --git a/packages/api/src/launch-payload.ts b/packages/api/src/launch-payload.ts index 83b3d6aa..98d1f85b 100644 --- a/packages/api/src/launch-payload.ts +++ b/packages/api/src/launch-payload.ts @@ -1,3 +1,4 @@ +import { skillFile } from "./skill-files"; import { z } from "zod"; import type { LaunchRequest } from "./execution"; @@ -9,7 +10,7 @@ const fields = { traceSources: z.record(z.string(), z.unknown()).optional(), }; export const launchPayloadResponse = z.union([ - z.object({ ...fields, prompt: z.string(), harness: z.object({ + z.object({ ...fields, prompt: z.string(), skillFiles: z.array(skillFile).optional(), harness: z.object({ executable: z.string().min(1), args: z.array(z.string()), env: z.record(z.string(), z.string()), }).strict() }).strict(), z.object({ ...fields, code: z.object({ script: z.string(), context: z.record(z.string(), z.unknown()) }).strict() }).strict(), @@ -18,7 +19,7 @@ export const launchPayloadResponse = z.union([ /** Snapshot exactly what the scheduler would otherwise transfer inline. */ export function serializeLaunchPayload(request: LaunchRequest): string { const value = JSON.stringify({ version: 1, runId: request.runId, - ...(request.code ? { code: request.code } : { prompt: request.prompt, harness: request.harness }), + ...(request.code ? { code: request.code } : { prompt: request.prompt, skillFiles: request.skillFiles, harness: request.harness }), ...(request.traceSources ? { traceSources: request.traceSources } : {}), }); if (new TextEncoder().encode(value).byteLength > LAUNCH_PAYLOAD_LIMIT) throw new Error("Launch payload exceeds 32 MiB"); diff --git a/packages/api/src/machine-job-execution-backend.ts b/packages/api/src/machine-job-execution-backend.ts index 354a80ce..a54e173e 100644 --- a/packages/api/src/machine-job-execution-backend.ts +++ b/packages/api/src/machine-job-execution-backend.ts @@ -1,6 +1,7 @@ import type { ExecutionBackend, ExecutionObservation, LaunchReceipt, LaunchRequest, RunHandle } from "./execution"; export type JobMachine = { id: string; name?: string; state?: string; config?: { metadata?: Record } }; export type JobMachineConfig = Record & { metadata?: Record }; +import { serializeLaunchPayload } from "./launch-payload"; import { safeDiagnosticText } from "./harness-diagnostics"; import type { TraceChunkCollectionRequest, ArtifactCollectionRequest, ArtifactCollector, ExecutionTerminator, HarnessLogReader, JobFileCollectionRequest, JobFileCollector, JobResultReader } from "./execution"; import { sourceCommand } from "./trace-source"; @@ -114,7 +115,7 @@ export class MachineJobExecutionBackend implements ExecutionBackend, JobResultRe const started = await guest.run(["/bin/sh", "-c", "nohup node /run/factorize-identity/proxy.mjs >/tmp/factorize-identity-proxy.log 2>&1 /run/factorize-identity/pid; n=0; until curl --fail --silent http://127.0.0.1:18180/_factorize/ready >/dev/null; do n=$((n+1)); test $n -lt 50 || exit 1; sleep 0.1; done"]); if (!started.ok) throw new Error("Fly guest vendor identity helper did not become ready"); } - const payload = JSON.stringify({ version: 1, runId: request.runId, ...(request.code ? { code: request.code } : { prompt: request.prompt, harness: request.harness }), ...(request.traceSources ? { traceSources: request.traceSources } : {}) }); + const payload = serializeLaunchPayload(request); const launchCommand = request.runIdentity ? ["/usr/sbin/runuser", "-u", "exedev", "--", "/usr/bin/env", "FACTORIZE_PROXY_URL=http://127.0.0.1:18180", "/usr/local/bin/factorize-job", "launch"] : ["/usr/sbin/runuser", "-u", "exedev", "--", "/usr/local/bin/factorize-job", "launch"]; diff --git a/packages/api/src/postgres/job-repository.ts b/packages/api/src/postgres/job-repository.ts index 2c608a6b..317d3146 100644 --- a/packages/api/src/postgres/job-repository.ts +++ b/packages/api/src/postgres/job-repository.ts @@ -29,14 +29,14 @@ export class PostgresJobRepository implements JobRepository { if (db === this.database.orm) { [triggerRows, skillRows] = await Promise.all([ loadedTriggers ?? db.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, row.id), isNull(triggers.removedAt))).orderBy(triggers.position, triggers.createdAt, triggers.id), - loadedSkills?.filter(skill => skill.job_id === row.id) ?? this.database.pool.query("SELECT s.id,s.key,s.revision,s.encrypted_body,js.position,js.context_skill FROM app.job_skills js JOIN app.skills s ON s.tenant_id=js.tenant_id AND s.id=js.skill_id WHERE js.tenant_id=$1 AND js.job_id=$2 ORDER BY js.position", [this.tenantId, row.id]).then(result => result.rows), + loadedSkills?.filter(skill => skill.job_id === row.id) ?? this.database.pool.query("SELECT s.id,s.key,s.revision,s.encrypted_body,s.encrypted_directory,js.position,js.context_skill FROM app.job_skills js JOIN app.skills s ON s.tenant_id=js.tenant_id AND s.id=js.skill_id WHERE js.tenant_id=$1 AND js.job_id=$2 ORDER BY js.position", [this.tenantId, row.id]).then(result => result.rows), ]); } else { triggerRows = loadedTriggers ?? await db.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, row.id), isNull(triggers.removedAt))).orderBy(triggers.position, triggers.createdAt, triggers.id); - skillRows = loadedSkills?.filter(skill => skill.job_id === row.id) ?? (await db.execute(sql`SELECT s.id,s.key,s.revision,s.encrypted_body,js.position,js.context_skill FROM app.job_skills js JOIN app.skills s ON s.tenant_id=js.tenant_id AND s.id=js.skill_id WHERE js.tenant_id=${this.tenantId}::uuid AND js.job_id=${row.id}::uuid ORDER BY js.position`)).rows; + skillRows = loadedSkills?.filter(skill => skill.job_id === row.id) ?? (await db.execute(sql`SELECT s.id,s.key,s.revision,s.encrypted_body,s.encrypted_directory,js.position,js.context_skill FROM app.job_skills js JOIN app.skills s ON s.tenant_id=js.tenant_id AND s.id=js.skill_id WHERE js.tenant_id=${this.tenantId}::uuid AND js.job_id=${row.id}::uuid ORDER BY js.position`)).rows; } const skills = await Promise.all(skillRows.map(async skill => ({ - id:skill.id, key:skill.key, revision:skill.revision, position:skill.position, body:await this.decrypt(skill.encrypted_body), + id:skill.id, key:skill.key, revision:skill.revision, position:skill.position, version:skill.encrypted_directory ? JSON.parse(await this.decrypt(skill.encrypted_directory)) : undefined, body:await this.decrypt(skill.encrypted_body), }))); const launchSkill = skills.find(skill=>skill.id === row.executionConfig.launchSkillId); return { id: row.id, runScopes: row.runScopes ?? [...DEFAULT_RUN_SCOPES], projectId: row.projectId, name: row.name, description: row.description ?? "", slug: row.slug, promptTemplate: await this.decrypt(row.encryptedPromptTemplate), executionType: row.executionConfig.executionType ?? "agent", script: row.executionConfig.script, runNameTemplate: row.encryptedRunNameTemplate ? await this.decrypt(row.encryptedRunNameTemplate) : "", tags: row.tags ?? [], model: row.model, ...(row.effort ? { effort: row.effort } : {}), executionConfig: row.executionConfig, portableIntegrationIds: row.executionConfig.portableIntegrationIds ?? [], modelAccess: row.executionConfig.modelAccess ?? "native", modelAccountId: row.executionConfig.modelAccountId, githubInstallationIds: row.executionConfig.githubInstallationIds ?? [], linearConnectionId: row.executionConfig.linearConnectionId, xConnectionIds: row.executionConfig.xConnectionIds ?? [], concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, triggers: triggerRows.map(value => this.trigger(value)), launchSkill, selectedSkills: skills.filter((_,index)=>skillRows[index].context_skill !== false), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; diff --git a/packages/api/src/postgres/run-repository.ts b/packages/api/src/postgres/run-repository.ts index 93ae2e8e..4c1a50b4 100644 --- a/packages/api/src/postgres/run-repository.ts +++ b/packages/api/src/postgres/run-repository.ts @@ -7,7 +7,7 @@ import type { JobResult } from "../job-result"; export interface PersistedRun { tenantId: string; id: string; jobId: string | null; invocationId: string; state: ExecutionState; - encryptedPrompt: string; executionConfig: Record; executionHandle: RunHandle | null; + encryptedSkillSnapshot?: string; encryptedPrompt: string; executionConfig: Record; executionHandle: RunHandle | null; traceSources?: TraceSources | null; executionDiagnostics?: ExecutionDiagnostics | null; finalizationAttempt?: number; failureCode?: string | null; failureReason?: string | null; backendKind: string; capabilities: string[]; artifactState: string; resultProtocolVersion: number; createdAt: string; updatedAt: string; @@ -15,13 +15,13 @@ export interface PersistedRun { export interface RunFailure { source: "run" | "system"; code: string; reason: string } interface RunRow { - tenant_id: string; id: string; job_id: string | null; invocation_id: string; state: ExecutionState; encrypted_prompt: string; + tenant_id: string; id: string; job_id: string | null; invocation_id: string; state: ExecutionState; encrypted_skill_snapshot?: string; encrypted_prompt: string; execution_config: Record; execution_handle: RunHandle | null; execution_backend_kind: string; failure_code?: string | null; failure_reason?: string | null; trace_sources: TraceSources | null; execution_diagnostics: ExecutionDiagnostics | null; vm_cleanup_attempt: number; execution_capabilities: string[]; artifact_state: string; result_protocol_version: number; created_at: Date; updated_at: Date; } -const mapped = (row: RunRow): PersistedRun => ({ tenantId: row.tenant_id, id: row.id, jobId: row.job_id, invocationId: row.invocation_id, state: row.state, encryptedPrompt: row.encrypted_prompt, executionConfig: row.execution_config, traceSources: row.trace_sources, executionHandle: row.execution_handle, executionDiagnostics: row.execution_diagnostics, finalizationAttempt: row.vm_cleanup_attempt, failureCode: row.failure_code, failureReason: row.failure_reason, backendKind: row.execution_backend_kind, capabilities: row.execution_capabilities, artifactState: row.artifact_state, resultProtocolVersion: row.result_protocol_version, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }); +const mapped = (row: RunRow): PersistedRun => ({ tenantId: row.tenant_id, id: row.id, jobId: row.job_id, invocationId: row.invocation_id, state: row.state, encryptedPrompt: row.encrypted_prompt, encryptedSkillSnapshot: row.encrypted_skill_snapshot, executionConfig: row.execution_config, traceSources: row.trace_sources, executionHandle: row.execution_handle, executionDiagnostics: row.execution_diagnostics, finalizationAttempt: row.vm_cleanup_attempt, failureCode: row.failure_code, failureReason: row.failure_reason, backendKind: row.execution_backend_kind, capabilities: row.execution_capabilities, artifactState: row.artifact_state, resultProtocolVersion: row.result_protocol_version, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }); export class RunRepository { constructor(private database: Database) {} @@ -61,7 +61,7 @@ export class RunRepository { ), claimed AS ( UPDATE app.job_runs r SET state='starting',launch_lease_expires_at=now()+interval '5 minutes',updated_at=now() FROM candidate c WHERE r.tenant_id=c.tenant_id AND r.id=c.id RETURNING r.* - ) SELECT c.tenant_id,c.id,c.job_id,c.invocation_id,c.state,c.encrypted_prompt,x.execution_config,x.trace_sources,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.failure_code,x.failure_reason,x.vm_cleanup_attempt,x.artifact_state,x.result_protocol_version,c.created_at,c.updated_at + ) SELECT c.tenant_id,c.id,c.job_id,c.invocation_id,c.state,c.encrypted_prompt,c.encrypted_skill_snapshot,x.execution_config,x.trace_sources,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.failure_code,x.failure_reason,x.vm_cleanup_attempt,x.artifact_state,x.result_protocol_version,c.created_at,c.updated_at FROM claimed c JOIN app.runs x ON x.tenant_id=c.tenant_id AND x.id=c.id`, [candidate.tenant_id,candidate.id]); const row = result.rows[0]; if (!row) return null; diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index c92c1de8..9dd029bb 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -1,3 +1,4 @@ +import { snapshotFiles } from "../skill-files"; import { cleanupVmGrants } from "../vm-grants"; import { cleanupAgentResponses } from "../agent-api"; import { validateTraceSources, type TraceSource, type TraceSources } from "../trace-source"; @@ -200,10 +201,11 @@ export class RunScheduler { }); const sources = rolloutTraceSources(driverTraceSources(driver.kind, harness), run.tenantId, this.env); validateTraceSources(sources); + const skillFiles = run.encryptedSkillSnapshot ? snapshotFiles(JSON.parse(await decrypt(run.encryptedSkillSnapshot, this.env.CREDENTIAL_ENCRYPTION_KEY))) : undefined; const prompt = await decrypt(run.encryptedPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY); const reservation = backend.reserve?.(run.id) ?? null; if (reservation) await this.runs.recordLaunchHandle(run, reservation); - const launched = await this.launchBackend(run, backend, { runId: run.id, reservation: reservation ?? undefined, prompt: `${prompt}${JOB_RESULT_INSTRUCTIONS}${runAccessInstructions({ githubInstallationIds: run.executionConfig.githubInstallationIds ?? [], linear: run.executionConfig.linearConnectionId === "linear", model: run.executionConfig.modelAccess === "portable" && Boolean(run.executionConfig.modelAccountId), xConnectionIds: run.executionConfig.xConnectionIds ?? [] })}`, runIdentity: { backendOrigin: this.env.APP_ORIGIN }, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); + const launched = await this.launchBackend(run, backend, { runId: run.id, reservation: reservation ?? undefined, skillFiles, prompt: `${prompt}${skillFiles?.length ? "\n\nSelected skill directories are available under $FACTORIZE_SKILLS_DIR//." : ""}${JOB_RESULT_INSTRUCTIONS}${runAccessInstructions({ githubInstallationIds: run.executionConfig.githubInstallationIds ?? [], linear: run.executionConfig.linearConnectionId === "linear", model: run.executionConfig.modelAccess === "portable" && Boolean(run.executionConfig.modelAccountId), xConnectionIds: run.executionConfig.xConnectionIds ?? [] })}`, runIdentity: { backendOrigin: this.env.APP_ORIGIN }, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities, sources); if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation); } diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 92a866ba..ea6688aa 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -102,8 +102,13 @@ export const jobs = app.table("jobs", { export const vmImageVerifications = app.table("vm_image_verifications", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), jobId: uuid("job_id"), status: text("status").notNull(), phase: text("phase").notNull(), config: jsonb("config").$type>().notNull(), errorKind: text("error_kind"), error: text("error"), vmName: text("vm_name"), createdAt: createdAt(), updatedAt: updatedAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), check("vm_image_verifications_status_check", sql`${t.status} IN ('queued','creating','checking_ssh','checking_agent','cleaning_up','succeeded','failed','cleanup_failed')`), index("vm_image_verifications_status_idx").on(t.status, t.updatedAt), index("vm_image_verifications_retention").on(t.createdAt,t.tenantId,t.id).where(sql`${t.status} IN ('succeeded','failed')`)]); +export const skillLibraries = app.table("skill_libraries", { + tenantId: uuid("tenant_id").primaryKey().references(() => tenants.id, {onDelete:"cascade"}), + repo: text("repo").notNull().unique(), remote: text("remote").notNull(), source: jsonb("source").notNull(), + commitSha: text("commit_sha"), upstreamSha: text("upstream_sha"), error: text("error"), checkedAt: timestamp("checked_at",{withTimezone:true}), +}); export const skills = app.table("skills", { - tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), key: text("key").notNull(), encryptedBody: text("encrypted_body").notNull(), revision: integer("revision").notNull().default(1), createdAt: createdAt(), updatedAt: updatedAt(), + tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), id: uuid("id").notNull(), key: text("key").notNull(), encryptedBody: text("encrypted_body").notNull(), 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 jobSkills = app.table("job_skills", { contextSkill:boolean("context_skill").notNull().default(true), tenantId: uuid("tenant_id").notNull(), jobId: uuid("job_id").notNull(), skillId: uuid("skill_id").notNull(), position: integer("position").notNull() }, t => [primaryKey({ columns: [t.tenantId, t.jobId, t.skillId] }), unique().on(t.tenantId, t.jobId, t.position), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.skillId], foreignColumns: [skills.tenantId, skills.id] }).onDelete("restrict")]); export const triggers = app.table("triggers", { @@ -197,7 +202,7 @@ export const runRelations = relations(runs, ({ one, many }) => ({ export const databaseSchema = { schemaMigrations, tenants, oauthConnections, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, - connections, agentIntegrations, agentIdentities, vmGrants, agentProxyResponses, integrationCollections, integrationRecords, integrationChanges, modelDeviceAuthorizations, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runAuthorizations, runs, runArtifacts, runRetentionCleanup, + connections, agentIntegrations, agentIdentities, vmGrants, agentProxyResponses, integrationCollections, integrationRecords, integrationChanges, modelDeviceAuthorizations, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skillLibraries, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runAuthorizations, runs, runArtifacts, runRetentionCleanup, runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, lifecycleEvents, jobEditDeliveries, jobEvents, webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, runTraceCursors, runTraceChunks, runTraceProjections, traceReplayLimits, traceReplayOperations, diff --git a/packages/api/src/postgres/skill-repository.ts b/packages/api/src/postgres/skill-repository.ts index 991ecbf0..6a0d9319 100644 --- a/packages/api/src/postgres/skill-repository.ts +++ b/packages/api/src/postgres/skill-repository.ts @@ -1,24 +1,25 @@ -import type { Database } from "./database"; +import type { Database, DatabaseClient } from "./database"; import { decrypt, encrypt } from "../crypto"; export class SkillConflict extends Error {} export class SkillReferenced extends Error { constructor(public jobs: { id: string; name: string; slug: string; enabled: boolean; projectId: string }[]) { super("Skill is referenced by saved jobs."); } } -type SkillRow = { id: string; key: string; revision: number; encrypted_body: string; created_at: Date; updated_at: Date }; +type SkillRow = { id: string; key: string; revision: number; encrypted_body: string; encrypted_directory?: string; created_at: Date; updated_at: Date }; export class SkillRepository { - constructor(private db: Database, private tenantId: string, private encryptionKey: string) {} - private async map(row: SkillRow, usageCount = 0, body = false) { return { id: row.id, key: row.key, revision: row.revision, ...(body ? { body: await decrypt(row.encrypted_body, this.encryptionKey) } : {}), usageCount, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }; } - async list(q = "", limit = 30, cursor?: string) { const result = await this.db.pool.query(`SELECT s.*, count(js.job_id)::text usage_count FROM app.skills s LEFT JOIN app.job_skills js ON js.tenant_id=s.tenant_id AND js.skill_id=s.id WHERE s.tenant_id=$1 AND ($2='' OR s.key ILIKE '%'||$2||'%') AND ($3::uuid IS NULL OR s.id < $3::uuid) GROUP BY s.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 }; } + constructor(private db: Database, private tenantId: string, private encryptionKey: string, private client?: DatabaseClient) {} + 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 ? { body: await decrypt(row.encrypted_body, this.encryptionKey), version: row.encrypted_directory ? JSON.parse(await decrypt(row.encrypted_directory, this.encryptionKey)) as import("../skill-files").SkillVersion : undefined } : {}), 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.job_id)::text usage_count FROM app.skills s LEFT JOIN app.job_skills js ON js.tenant_id=s.tenant_id AND js.skill_id=s.id WHERE s.tenant_id=$1 AND ($2='' OR s.key ILIKE '%'||$2||'%') AND ($3::uuid IS NULL OR s.id < $3::uuid) GROUP BY s.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. const id = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(idOrKey) ? idOrKey : null; - const row = (await this.db.pool.query( + const row = (await this.sql.query( "SELECT * FROM app.skills WHERE tenant_id=$1 AND (id=$2::uuid OR key=$3::text) LIMIT 1", [this.tenantId, id, idOrKey], )).rows[0]; return row ? this.map(row, 0, includeBody) : null; } - async create(key: string, body: string) { try { const row = (await this.db.pool.query("INSERT INTO app.skills(tenant_id,id,key,encrypted_body) VALUES($1,$2,$3,$4) RETURNING *", [this.tenantId, crypto.randomUUID(), key, await encrypt(body, this.encryptionKey)])).rows[0]; return this.map(row, 0, true); } catch (e: any) { if (e.code === "23505") throw new SkillConflict("Skill key is already in use."); throw e; } } - async update(id: string, input: { key?: string; body?: string; expectedRevision: number }) { const row = (await this.db.pool.query("SELECT * FROM app.skills WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.tenantId, id])).rows[0]; if (!row) return null; if (row.revision !== input.expectedRevision) throw new SkillConflict("Skill changed since it was loaded."); try { const updated = (await this.db.pool.query("UPDATE app.skills SET key=COALESCE($3,key),encrypted_body=COALESCE($4,encrypted_body),revision=revision+1,updated_at=now() WHERE tenant_id=$1 AND id=$2 RETURNING *", [this.tenantId, id, input.key ?? null, input.body === undefined ? null : await encrypt(input.body, this.encryptionKey)])).rows[0]; return this.map(updated, 0, true); } catch (e: any) { if (e.code === "23505") throw new SkillConflict("Skill key is already in use."); throw e; } } - async remove(id: string, expectedRevision: number) { return this.db.transaction(async client => { const skill = (await client.query("SELECT * FROM app.skills WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.tenantId, id])).rows[0]; if (!skill) return false; if (skill.revision !== expectedRevision) throw new SkillConflict("Skill changed since it was loaded."); const refs = (await client.query("SELECT j.id,j.name,j.slug,j.enabled,j.project_id FROM app.jobs j JOIN app.job_skills js ON js.tenant_id=j.tenant_id AND js.job_id=j.id WHERE js.tenant_id=$1 AND js.skill_id=$2 ORDER BY j.name", [this.tenantId, id])).rows; if (refs.length) throw new SkillReferenced(refs); await client.query("DELETE FROM app.skills WHERE tenant_id=$1 AND id=$2", [this.tenantId, id]); return true; }); } - async jobs(id: string) { return (await this.db.pool.query("SELECT j.id,j.name,j.slug,j.enabled,j.project_id FROM app.jobs j JOIN app.job_skills js ON js.tenant_id=j.tenant_id AND js.job_id=j.id WHERE js.tenant_id=$1 AND js.skill_id=$2 ORDER BY j.name", [this.tenantId, id])).rows; } + async create(key: string, body: string) { try { const row = (await this.sql.query("INSERT INTO app.skills(tenant_id,id,key,encrypted_body) VALUES($1,$2,$3,$4) RETURNING *", [this.tenantId, crypto.randomUUID(), key, await encrypt(body, this.encryptionKey)])).rows[0]; return this.map(row, 0, true); } catch (e: any) { if (e.code === "23505") throw new SkillConflict("Skill key is already in use."); throw e; } } + async update(id: string, input: { key?: string; body?: string; expectedRevision: number }) { const row = (await this.sql.query("SELECT * FROM app.skills WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.tenantId, id])).rows[0]; if (!row) return null; if (row.revision !== input.expectedRevision) throw new SkillConflict("Skill changed since it was loaded."); try { const updated = (await this.sql.query("UPDATE app.skills SET key=COALESCE($3,key),encrypted_body=COALESCE($4,encrypted_body),revision=revision+1,updated_at=now() WHERE tenant_id=$1 AND id=$2 RETURNING *", [this.tenantId, id, input.key ?? null, input.body === undefined ? null : await encrypt(input.body, this.encryptionKey)])).rows[0]; return this.map(updated, 0, true); } catch (e: any) { if (e.code === "23505") throw new SkillConflict("Skill key is already in use."); throw e; } } + async remove(id: string, expectedRevision: number) { const remove = async (client: DatabaseClient) => { const skill = (await client.query("SELECT * FROM app.skills WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.tenantId, id])).rows[0]; if (!skill) return false; if (skill.revision !== expectedRevision) throw new SkillConflict("Skill changed since it was loaded."); const refs = (await client.query("SELECT j.id,j.name,j.slug,j.enabled,j.project_id FROM app.jobs j JOIN app.job_skills js ON js.tenant_id=j.tenant_id AND js.job_id=j.id WHERE js.tenant_id=$1 AND js.skill_id=$2 ORDER BY j.name", [this.tenantId, id])).rows; if (refs.length) throw new SkillReferenced(refs); await client.query("DELETE FROM app.skills WHERE tenant_id=$1 AND id=$2", [this.tenantId, id]); return true; }; return this.client ? remove(this.client) : this.db.transaction(remove); } + async jobs(id: string) { return (await this.sql.query("SELECT j.id,j.name,j.slug,j.enabled,j.project_id FROM app.jobs j JOIN app.job_skills js ON js.tenant_id=j.tenant_id AND js.job_id=j.id WHERE js.tenant_id=$1 AND js.skill_id=$2 ORDER BY j.name", [this.tenantId, id])).rows; } } diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index 04c09b01..bf41b336 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -1,3 +1,4 @@ +import { SkillContentError } from "./skill-files"; import { listenForOutcomes, outcomeRunId } from "./run-outcome-subscription"; import { authenticateVendorRunRequest } from "./vendor-run-auth"; import { Hono } from "hono"; @@ -19,6 +20,7 @@ import { matchApiOperation } from "./api-contract"; import { normalizeScopes } from "./access-tokens"; function errorResponse(error: unknown, origin?: string): Response { + if (error instanceof SkillContentError) return Response.json({ error: { code: "invalid_skill_directory", message: error.message } }, {status:409}); if (error instanceof AgentApiError) return Response.json({error: {code: error.code, message: error.message}}, {status: error.status, headers: error.code === "insufficient_scope" ? {"WWW-Authenticate": `Bearer error="insufficient_scope", scope="${error.scope}", resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"`} : undefined}); if (error instanceof ExeIntegrationError) return Response.json({ error: { code: "invalid_request", message: error.message } }, { status: 400 }); if (error instanceof URIError) return Response.json({ error: { code: "invalid_request", message: "Invalid path encoding" } }, { status: 400 }); diff --git a/packages/api/src/skill-files.ts b/packages/api/src/skill-files.ts new file mode 100644 index 00000000..d5cad5ee --- /dev/null +++ b/packages/api/src/skill-files.ts @@ -0,0 +1,73 @@ +import { z } from "zod"; +import { SKILL_KEY, SKILL_BODY_LIMIT } from "./skills"; + +export const skillFile = z.object({ + path: z.string().min(1).max(1024), + content: z.string(), + executable: z.boolean(), +}); +export class SkillContentError extends Error {} +export type SkillFile = z.infer; +export type Directory = { key: string; files: SkillFile[] }; +export type SkillVersion = { commit: string; files: SkillFile[] }; + +export function validPath(path: string) { + return ( + path.length <= 1024 && + !/[\\\x00-\x1f\x7f]/.test(path) && + path.split("/").every((part) => part && part !== "." && part !== ".." && part.toLowerCase() !== ".git") + ); +} + +export function base64(bytes: Uint8Array) { + let binary = ""; + for (let offset = 0; offset < bytes.length; offset += 8192) + binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192)); + return btoa(binary); +} +export function markdown(body: string): SkillFile { + return { path: "SKILL.md", content: base64(new TextEncoder().encode(body)), executable: false }; +} + +export function bodyOf(directory: Directory) { + const file = directory.files.find((file) => file.path === "SKILL.md"); + if (!file || !SKILL_KEY.test(directory.key)) + throw new SkillContentError("Each skill needs a valid key and SKILL.md"); + let body: string; + try { + body = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode( + Uint8Array.from(atob(file.content), (c) => c.charCodeAt(0)), + ); + } catch { + throw new SkillContentError("SKILL.md must contain UTF-8 text"); + } + if (body.length > SKILL_BODY_LIMIT) throw new SkillContentError("SKILL.md exceeds the skill body limit"); + return body; +} + +export function snapshotFiles(snapshot: { key: string; body: string; version?: SkillVersion }[]) { + return snapshot.flatMap((skill) => + (skill.version?.files ?? [markdown(skill.body)]).map((file) => ({ + ...file, + path: skill.key + "/" + file.path, + })), + ); +} + +export const SKILL_LIBRARY_BYTES = 8 * 1024 * 1024; +export const SKILL_LIBRARY_ENTRIES = 2000; + +export function validateLibrary(dirs: Directory[]) { + let count = 0, + bytes = 0; + for (const dir of dirs) { + bodyOf(dir); + for (const file of dir.files) { + bytes += + (file.content.length * 3) / 4 - + (file.content.endsWith("==") ? 2 : file.content.endsWith("=") ? 1 : 0); + if (++count > SKILL_LIBRARY_ENTRIES || bytes > SKILL_LIBRARY_BYTES || !validPath(file.path)) + throw new SkillContentError("Skills exceed the library limits"); + } + } +} diff --git a/packages/api/src/skill-git.ts b/packages/api/src/skill-git.ts new file mode 100644 index 00000000..37709ba3 --- /dev/null +++ b/packages/api/src/skill-git.ts @@ -0,0 +1,204 @@ +import fs from "node:fs"; +import { Buffer } from "node:buffer"; +import git, { type TreeEntry } from "isomorphic-git"; +import http from "isomorphic-git/http/web"; +import { + SkillContentError, + validateLibrary, + SKILL_LIBRARY_BYTES, + SKILL_LIBRARY_ENTRIES, + base64, + bodyOf, + validPath, + type Directory, + type SkillFile, +} from "./skill-files"; +import { SKILL_KEY } from "./skills"; + +export type GitRemote = { url: string; branch: string; headers: Record }; +const author = { name: "Factorize", email: "skills@factorize.sh" }; + +// Bound the shallow pack as well as the uncompressed skills copied into the launch payload. +const transport: typeof http = { + async request(options) { + const result = await http.request(options); + const stream = result.body; + if (!stream) return result; + async function* bounded() { + let total = 0; + for await (const bytes of stream!) { + total += bytes.byteLength; + if (total > 16 * 1024 * 1024) + throw new SkillContentError("Skill repository exceeds the shallow fetch limit"); + yield bytes; + } + } + return { ...result, body: bounded() }; + }, +}; + +export async function withSkillGit(remote: GitRemote, work: (repo: SkillGit) => Promise) { + const root = await fs.promises.mkdtemp("/tmp/factorize-skills-"); + try { + const repo = new SkillGit(root, remote); + await repo.open(); + return await work(repo); + } finally { + await fs.promises.rm(root, { recursive: true, force: true }); + } +} + +export class SkillGit { + private options; + private network; + head: string | null = null; + private tree: string | null = null; + constructor(dir: string, remote: GitRemote) { + this.options = { fs, dir }; + this.network = { + ...this.options, + http: transport, + url: remote.url, + ref: remote.branch, + headers: remote.headers, + }; + } + async open() { + const refs = await git.listServerRefs({ + ...this.network, + headers: { ...this.network.headers }, + prefix: "refs/heads/", + }); + const ref = refs.find((ref) => ref.ref === "refs/heads/" + this.network.ref); + if (!ref) { + if (refs.some((ref) => ref.ref.startsWith("refs/heads/"))) + throw new SkillContentError("Tracked branch does not exist"); + return; + } + this.head = ref.oid; + } + private async load() { + if (this.tree) return; + await git.init({ ...this.options, defaultBranch: this.network.ref }); + await git.addRemote({ ...this.options, remote: "origin", url: this.network.url }); + if (!this.head) return; + const result = await git.fetch({ + ...this.network, + headers: { ...this.network.headers }, + singleBranch: true, + depth: 1, + tags: false, + }); + if (!result.fetchHead) throw new SkillContentError("Unable to fetch skills branch"); + if (this.head !== result.fetchHead) + throw new SkillContentError("Tracked branch changed during synchronization"); + this.tree = (await git.readCommit({ ...this.options, oid: this.head })).commit.tree; + } + private async entries(oid: string | null) { + return oid ? (await git.readTree({ ...this.options, oid })).tree : []; + } + async directories(folder: string) { + await this.load(); + let tree = this.tree; + for (const part of folder.split("/").filter(Boolean)) { + const entry = (await this.entries(tree)).find((entry) => entry.path === part); + if (entry && entry.type !== "tree") throw new SkillContentError("Skills folder must be a directory"); + tree = entry?.oid ?? null; + } + const directories: Directory[] = []; + let count = 0, + size = 0; + const visit = async (oid: string, prefix: string, files: SkillFile[]) => { + for (const entry of await this.entries(oid)) { + const path = prefix + entry.path; + if (++count > SKILL_LIBRARY_ENTRIES || !validPath(path)) + throw new SkillContentError("Unsupported skill directory size or path"); + if (entry.type === "tree") { + await visit(entry.oid, path + "/", files); + continue; + } + if (!["100644", "100755"].includes(entry.mode)) + throw new SkillContentError("Skills may contain only regular files and directories"); + const { blob } = await git.readBlob({ ...this.options, oid: entry.oid }); + size += blob.length; + if (size > SKILL_LIBRARY_BYTES) throw new SkillContentError("Skills exceed the 8 MiB library limit"); + files.push({ path, content: base64(blob), executable: entry.mode === "100755" }); + } + }; + for (const entry of await this.entries(tree)) { + if (entry.type !== "tree") continue; + if (!SKILL_KEY.test(entry.path)) throw new SkillContentError("Invalid skill directory name"); + const directory: Directory = { key: entry.path, files: [] }; + await visit(entry.oid, "", directory.files); + bodyOf(directory); + directories.push(directory); + } + return directories; + } + async write(folder: string, directories: Directory[], message: string) { + validateLibrary(directories); + await this.load(); + // Replace only skill directories. Keep unrelated root files and other project paths. + const replace = async (oid: string | null, parts: string[]): Promise => { + const entries = await this.entries(oid); + if (parts.length) { + const [part, ...rest] = parts; + const previous = entries.find((entry) => entry.path === part); + const child = await replace(previous?.oid ?? null, rest); + return git.writeTree({ + ...this.options, + tree: [ + ...entries.filter((entry) => entry.path !== part), + { mode: "040000", type: "tree", path: part, oid: child }, + ], + }); + } + if (entries.some((entry) => entry.type !== "tree" && directories.some((dir) => dir.key === entry.path))) + throw new SkillContentError("A file already uses this skill directory name"); + const files = directories.flatMap((dir) => + dir.files.map((file) => ({ ...file, path: dir.key + "/" + file.path })), + ); + const build = async (items: SkillFile[], retained: TreeEntry[] = []): Promise => { + const children = new Map(); + const tree = [...retained]; + for (const file of items) { + const slash = file.path.indexOf("/"); + if (slash === -1) { + tree.push({ + path: file.path, + mode: file.executable ? "100755" : "100644", + type: "blob", + oid: await git.writeBlob({ ...this.options, blob: Buffer.from(file.content, "base64") }), + }); + } else { + const name = file.path.slice(0, slash); + const group = children.get(name) ?? []; + group.push({ ...file, path: file.path.slice(slash + 1) }); + children.set(name, group); + } + } + for (const [path, group] of children) + tree.push({ path, mode: "040000", type: "tree", oid: await build(group) }); + return git.writeTree({ ...this.options, tree }); + }; + return build( + files, + entries.filter((entry) => entry.type !== "tree"), + ); + }; + const tree = await replace(this.tree, folder.split("/").filter(Boolean)); + if (this.head && tree === this.tree) return this.head; + const oid = await git.commit({ + ...this.options, + tree, + parent: this.head ? [this.head] : [], + author, + message, + ref: this.network.ref, + }); + await git.push({ ...this.network, remoteRef: this.network.ref }); + this.head = oid; + this.tree = tree; + return oid; + } +} diff --git a/packages/api/src/skill-github.ts b/packages/api/src/skill-github.ts new file mode 100644 index 00000000..1622c684 --- /dev/null +++ b/packages/api/src/skill-github.ts @@ -0,0 +1,161 @@ +import { githubHeaders } from "./github"; +import { + validateLibrary, + SKILL_LIBRARY_BYTES, + SKILL_LIBRARY_ENTRIES, + bodyOf, + validPath, + type Directory, +} from "./skill-files"; +import { SkillConflict } from "./postgres/skill-repository"; +import { SKILL_KEY } from "./skills"; + +type Entry = { path: string; type: string; mode: string; sha: string; size?: number }; +type Tree = { tree: Entry[]; truncated: boolean }; +type Change = { path: string; mode: string; type: "blob"; sha: string | null }; + +/** Git Data reads pin every tree and blob to the observed commit. A large project + * can share its skills folder without cloning the rest of its working tree. */ +export class GitHubSkills { + head: string | null = null; + private root = ""; + constructor( + private base: string, + private token: string, + private branch: string, + ) {} + private async request(path: string, method = "GET", body?: unknown): Promise { + const result = await fetch(this.base + path, { + method, + headers: githubHeaders(this.token), + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + if (!result.ok) + throw new SkillConflict( + "GitHub " + + method + + " failed (" + + result.status + + "). Check repository access, branch protection, and the current branch head.", + ); + return result.json() as Promise; + } + async open() { + const ref = await this.request<{ object: { sha: string } }>( + "/git/ref/heads/" + this.branch.split("/").map(encodeURIComponent).join("/"), + ); + this.head = ref.object.sha; + } + private async entries(folder: string) { + const commit = await this.request<{ tree: { sha: string } }>("/git/commits/" + this.head); + this.root = commit.tree.sha; + let oid = this.root; + for (const part of folder.split("/").filter(Boolean)) { + const tree = await this.request("/git/trees/" + oid); + if (tree.truncated) throw new SkillConflict("GitHub truncated the directory listing"); + const dir = tree.tree.find((entry) => entry.path === part); + if (!dir) return []; + if (dir.type !== "tree") throw new SkillConflict("The tracked GitHub skills folder does not exist"); + oid = dir.sha; + } + const tree = await this.request("/git/trees/" + oid + "?recursive=1"); + if (tree.truncated || tree.tree.length > SKILL_LIBRARY_ENTRIES) + throw new SkillConflict("The GitHub skills folder exceeds 2000 entries"); + const keys = tree.tree.filter((entry) => !entry.path.includes("/") && entry.type === "tree"); + if ( + keys.some( + (key) => !tree.tree.some((entry) => entry.path === key.path + "/SKILL.md" && entry.type === "blob"), + ) + ) + throw new SkillConflict("Each skill directory needs a SKILL.md file"); + const entries = tree.tree.filter((entry) => entry.path.includes("/") && entry.type !== "tree"); + if ( + entries.some( + (entry) => + !validPath(entry.path) || + !SKILL_KEY.test(entry.path.split("/")[0]) || + !["100644", "100755"].includes(entry.mode) || + entry.type !== "blob" || + typeof entry.size !== "number", + ) + ) + throw new SkillConflict("The GitHub skills folder contains an unsupported path or file type"); + if (entries.reduce((size, file) => size + file.size!, 0) > SKILL_LIBRARY_BYTES) + throw new SkillConflict("The GitHub skills folder exceeds 8 MiB"); + return entries; + } + async directories(folder: string) { + const entries = await this.entries(folder); + const dirs = new Map(); + for (let i = 0; i < entries.length; i += 6) { + const files = await Promise.all( + entries.slice(i, i + 6).map(async (entry) => { + const blob = await this.request<{ encoding: string; content: string }>("/git/blobs/" + entry.sha); + if (blob.encoding !== "base64") + throw new SkillConflict("GitHub returned an unsupported blob encoding"); + const [key, ...path] = entry.path.split("/"); + return { + key, + file: { + path: path.join("/"), + executable: entry.mode === "100755", + content: blob.content.replace(/\s/g, ""), + }, + }; + }), + ); + for (const { key, file } of files) { + const dir = dirs.get(key) ?? { key, files: [] }; + dir.files.push(file); + dirs.set(key, dir); + } + } + for (const dir of dirs.values()) bodyOf(dir); + return [...dirs.values()]; + } + async write(folder: string, dirs: Directory[], message: string) { + validateLibrary(dirs); + const existing = new Map((await this.entries(folder)).map((entry) => [entry.path, entry])); + const changes: Change[] = []; + const prefix = folder ? folder + "/" : ""; + for (const dir of dirs) + for (const file of dir.files) { + const path = dir.key + "/" + file.path; + const old = existing.get(path); + existing.delete(path); + const bytes = Uint8Array.from(atob(file.content), (c) => c.charCodeAt(0)); + const header = new TextEncoder().encode("blob " + bytes.length + "\0"); + const object = new Uint8Array(header.length + bytes.length); + object.set(header); + object.set(bytes, header.length); + const oid = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-1", object)), (b) => + b.toString(16).padStart(2, "0"), + ).join(""); + const mode = file.executable ? "100755" : "100644"; + if (old?.sha === oid && old.mode === mode) continue; + const blob = await this.request<{ sha: string }>("/git/blobs", "POST", { + encoding: "base64", + content: file.content, + }); + changes.push({ path: prefix + path, mode, type: "blob", sha: blob.sha }); + } + for (const entry of existing.values()) + changes.push({ path: prefix + entry.path, mode: entry.mode, type: "blob", sha: null }); + if (!changes.length) return this.head!; + const tree = await this.request<{ sha: string }>("/git/trees", "POST", { + base_tree: this.root, + tree: changes, + }); + const commit = await this.request<{ sha: string }>("/git/commits", "POST", { + tree: tree.sha, + parents: [this.head], + message, + }); + await this.request( + "/git/refs/heads/" + this.branch.split("/").map(encodeURIComponent).join("/"), + "PATCH", + { sha: commit.sha, force: false }, + ); + return commit.sha; + } +} diff --git a/packages/api/src/skill-library-contract.ts b/packages/api/src/skill-library-contract.ts new file mode 100644 index 00000000..db12b7f1 --- /dev/null +++ b/packages/api/src/skill-library-contract.ts @@ -0,0 +1,32 @@ +import { z } from "zod"; +import { validPath } from "./skill-files"; + +export const librarySource = z.discriminatedUnion("kind", [ + z.object({ kind: z.literal("managed") }).strict(), + z + .object({ + kind: z.literal("github"), + installationId: z.number().int().positive(), + repositoryId: z.number().int().positive(), + branch: z + .string() + .min(1) + .max(255) + .regex(/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/) + .refine((value) => !value.includes("..") && validPath(value)), + folder: z + .string() + .max(512) + .refine((value) => value === "" || validPath(value)), + }) + .strict(), +]); +export type LibrarySource = z.infer; +export const libraryStatus = z.object({ + source: librarySource.nullable(), + remote: z.string().nullable(), + commit: z.string().nullable(), + upstreamCommit: z.string().nullable(), + error: z.string().nullable(), +}); +export const libraryToken = z.object({ remote: z.string(), token: z.string(), expiresAt: z.string() }); diff --git a/packages/api/src/skill-library.ts b/packages/api/src/skill-library.ts new file mode 100644 index 00000000..9f060141 --- /dev/null +++ b/packages/api/src/skill-library.ts @@ -0,0 +1,328 @@ +import { decrypt, encrypt } from "./crypto"; +import { githubHeaders, installationToken } from "./github"; +import { databaseFor, type DatabaseClient } from "./postgres/database"; +import { SkillConflict, SkillRepository } from "./postgres/skill-repository"; +import { SkillContentError, bodyOf, markdown, type Directory, type SkillVersion } from "./skill-files"; +import { withSkillGit, type GitRemote } from "./skill-git"; +import { GitHubSkills } from "./skill-github"; +import { librarySource, type LibrarySource } from "./skill-library-contract"; +import type { Env } from "./types"; + +type LibraryRow = { + repo: string; + remote: string; + source: LibrarySource; + commit_sha: string | null; + upstream_sha: string | null; + error: string | null; +}; +type Current = Directory & { id: string; body: string; version?: SkillVersion }; +const managedFolder = "skills"; + +export class SkillLibrary { + private db; + constructor( + private env: Env, + private tenant: string, + ) { + this.db = databaseFor(env); + } + private async locked(work: (client: DatabaseClient, row?: LibraryRow) => Promise) { + return this.db.transaction(async (client) => { + await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1,1))", [this.tenant]); + return work(client, await this.row(client)); + }); + } + private async row(client: DatabaseClient) { + return ( + await client.query("SELECT * FROM app.skill_libraries WHERE tenant_id=$1", [this.tenant]) + ).rows[0]; + } + async status() { + const row = await this.row(this.db.pool); + return { + source: row?.source ?? null, + remote: row?.source.kind === "managed" ? row.remote : null, + commit: row?.commit_sha ?? null, + upstreamCommit: row?.upstream_sha ?? null, + error: row?.error ?? null, + }; + } + private artifacts() { + if (!this.env.SKILL_ARTIFACTS) throw new Error("Skill Artifacts binding is unavailable"); + return this.env.SKILL_ARTIFACTS; + } + private async credentials(row: LibraryRow, scope: "read" | "write") { + const handle = await this.artifacts().get(row.repo); + try { + return await handle.createToken(scope, 3600); + } finally { + (handle as unknown as Partial)[Symbol.dispose]?.(); + } + } + async token() { + const row = await this.row(this.db.pool); + if (row?.source.kind !== "managed") + throw new SkillConflict("Select the Factorize-managed Git remote first"); + const token = await this.credentials(row, "write"); + return { remote: row.remote, token: token.plaintext, expiresAt: token.expiresAt }; + } + private async managed(row: LibraryRow, scope: "read" | "write"): Promise { + const token = await this.credentials(row, scope); + return { url: row.remote, branch: "main", headers: { Authorization: "Bearer " + token.plaintext } }; + } + private async github(client: DatabaseClient, source: Extract) { + const installation = await client.query( + "SELECT 1 FROM app.github_installations WHERE tenant_id=$1 AND installation_id=$2 AND state='active' FOR SHARE", + [this.tenant, source.installationId], + ); + if (!installation.rowCount) throw new SkillConflict("GitHub installation is unavailable"); + const token = await installationToken(this.env, source.installationId, source.repositoryId); + const response = await fetch("https://api.github.com/repositories/" + source.repositoryId, { + headers: githubHeaders(token), + }); + if (!response.ok) throw new SkillConflict("GitHub repository is unavailable to this installation"); + const repo = (await response.json()) as { id: number; full_name: string }; + if (repo.id !== source.repositoryId || !/^[\w.-]+\/[\w.-]+$/.test(repo.full_name)) + throw new Error("Invalid GitHub repository"); + const repoClient = new GitHubSkills( + "https://api.github.com/repos/" + repo.full_name, + token, + source.branch, + ); + await repoClient.open(); + return repoClient; + } + private async current(client: DatabaseClient): Promise { + const { rows } = await client.query( + "SELECT id,key,encrypted_body,encrypted_directory FROM app.skills WHERE tenant_id=$1 ORDER BY key FOR UPDATE", + [this.tenant], + ); + return Promise.all( + rows.map(async (row) => { + const version: SkillVersion | undefined = row.encrypted_directory + ? JSON.parse(await decrypt(row.encrypted_directory, this.env.CREDENTIAL_ENCRYPTION_KEY)) + : undefined; + const body = await decrypt(row.encrypted_body, this.env.CREDENTIAL_ENCRYPTION_KEY); + return { id: row.id, key: row.key, body, version, files: version?.files ?? [markdown(body)] }; + }), + ); + } + async configure(source: LibrarySource) { + await this.locked((client, previous) => this.initialize(client, source, previous)); + return this.status(); + } + private async initialize(client: DatabaseClient, source: LibrarySource, previous?: LibraryRow) { + if (previous && JSON.stringify(librarySource.parse(previous.source)) === JSON.stringify(source)) return; + // Independent repos prevent an outstanding managed write token from changing a GitHub mirror. + const name = "skills-" + crypto.randomUUID(); + const current = await this.current(client); + let directories: Directory[] = current; + let upstreamCommit: string | null = null; + if (source.kind === "github") { + const repo = await this.github(client, source); + const imported = await repo.directories(source.folder); + const keys = new Set(imported.map((dir) => dir.key)); + const missing = current.filter((dir) => !keys.has(dir.key)); + directories = [...imported, ...missing]; + // The selected branch supplies existing keys. Seed only absent skills, in one fast-forward commit. + upstreamCommit = missing.length + ? await repo.write(source.folder, directories, "Import existing Factorize skills") + : repo.head; + } + const created = await this.artifacts().create(name, { setDefaultBranch: "main" }); + const remote: GitRemote = { + url: created.remote, + branch: "main", + headers: { Authorization: "Bearer " + created.token }, + }; + let commit: string; + try { + commit = await withSkillGit(remote, (repo) => + repo.write(managedFolder, directories, "Initialize Factorize skills"), + ); + } catch (error) { + await this.artifacts().delete(name); + throw error; + } + await client.query( + `INSERT INTO app.skill_libraries(tenant_id,repo,remote,source) VALUES($1,$2,$3,$4) + ON CONFLICT(tenant_id) DO UPDATE SET repo=excluded.repo,remote=excluded.remote,source=excluded.source`, + [this.tenant, name, created.remote, source], + ); + await this.publish(client, current, directories, commit, upstreamCommit ?? commit); + } + private async publish( + client: DatabaseClient, + current: Current[], + dirs: Directory[], + revision: string | (() => Promise), + upstream: string, + ) { + const keys = new Set(dirs.map((dir) => dir.key)); + const previousByKey = new Map(current.map((item) => [item.key, item])); + const added = dirs.filter((dir) => !previousByKey.has(dir.key)); + const removed = current.filter((item) => !keys.has(item.key)); + // Git has no rename identity. Preserve an ID only for an unambiguous move of the exact directory. + const fingerprint = (dir: Directory) => + JSON.stringify( + dir.files + .map((f) => [f.path, f.content, f.executable]) + .sort((a, b) => String(a[0]).localeCompare(String(b[0]))), + ); + const addedPrints = added.map((dir) => ({ dir, print: fingerprint(dir) })); + const removedPrints = removed.map((dir) => ({ dir, print: fingerprint(dir) })); + for (const { dir: item, print } of removedPrints) { + const matches = addedPrints.filter((candidate) => candidate.print === print); + if ( + matches.length === 1 && + removedPrints.filter((candidate) => candidate.print === print).length === 1 + ) { + const key = matches[0].dir.key; + await client.query("UPDATE app.skills SET key=$3, revision=revision+1 WHERE tenant_id=$1 AND id=$2", [ + this.tenant, + item.id, + key, + ]); + previousByKey.set(key, item); + continue; + } + if ( + ( + await client.query("SELECT 1 FROM app.job_skills WHERE tenant_id=$1 AND skill_id=$2 LIMIT 1", [ + this.tenant, + item.id, + ]) + ).rowCount + ) + throw new SkillConflict("Cannot remove referenced skill " + item.key); + await client.query("DELETE FROM app.skills WHERE tenant_id=$1 AND id=$2", [this.tenant, item.id]); + } + const commit = typeof revision === "string" ? revision : await revision(); + for (const dir of dirs) { + const previous = previousByKey.get(dir.key); + const files = [...dir.files].sort((a, b) => a.path.localeCompare(b.path)); + const same = previous && fingerprint(dir) === fingerprint(previous); + if (same && previous.version?.commit === commit) continue; + const encrypted = await encrypt(JSON.stringify({ commit, files }), this.env.CREDENTIAL_ENCRYPTION_KEY); + await client.query( + `INSERT INTO app.skills(tenant_id,id,key,encrypted_body,encrypted_directory) VALUES($1,$2,$3,$4,$5) + ON CONFLICT(tenant_id,key) DO UPDATE SET encrypted_body=excluded.encrypted_body,encrypted_directory=excluded.encrypted_directory, + revision=app.skills.revision+$6,updated_at=now()`, + [ + this.tenant, + previous?.id ?? crypto.randomUUID(), + dir.key, + await encrypt(bodyOf(dir), this.env.CREDENTIAL_ENCRYPTION_KEY), + encrypted, + same ? 0 : 1, + ], + ); + } + await client.query( + "UPDATE app.skill_libraries SET commit_sha=$2,upstream_sha=$3,error=NULL,checked_at=now() WHERE tenant_id=$1", + [this.tenant, commit, upstream], + ); + } + async sync(match?: { repo?: string; installationId?: number; repositoryId?: number; ref?: string }) { + await this.locked(async (client, row) => { + if (!row) return; + const source = row.source; + if (match?.repo && (source.kind !== "managed" || row.repo !== match.repo)) return; + if ( + match?.installationId && + (source.kind !== "github" || + source.installationId !== match.installationId || + source.repositoryId !== match.repositoryId || + match.ref !== "refs/heads/" + source.branch) + ) + return; + await client.query("SAVEPOINT skill_sync"); + try { + const reconcile = async (repo: Pick) => { + if (!repo.head) throw new SkillConflict("The tracked branch is empty"); + if (repo.head === row.upstream_sha) { + await client.query( + "UPDATE app.skill_libraries SET error=NULL,checked_at=now() WHERE tenant_id=$1", + [this.tenant], + ); + return; + } + const current = await this.current(client); + const dirs = await repo.directories(source.kind === "managed" ? managedFolder : source.folder); + 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); + }; + if (source.kind === "managed") await withSkillGit(await this.managed(row, "read"), reconcile); + else await reconcile(await this.github(client, source)); + } catch (error) { + await client.query("ROLLBACK TO SAVEPOINT skill_sync"); + // Git transport errors can contain credentials. Only surface known local validation messages. + const message = + error instanceof SkillConflict || error instanceof SkillContentError + ? error.message + : "Sync failed. Check the tracked branch, skill directories, repository limits, and installation access."; + await client.query("UPDATE app.skill_libraries SET error=$2,checked_at=now() WHERE tenant_id=$1", [ + this.tenant, + message, + ]); + } + }); + } + + async edit(work: (repository: SkillRepository) => Promise) { + // Commit the migration separately. Even a rejected first edit leaves a valid baseline. + if (this.env.SKILL_ARTIFACTS && !(await this.row(this.db.pool))) + await this.locked(async (client, existing) => { + if (!existing) await this.initialize(client, { kind: "managed" }); + }); + return this.locked(async (client, row) => { + const store = new SkillRepository(this.db, this.tenant, this.env.CREDENTIAL_ENCRYPTION_KEY, client); + const result = await work(store); + if (!row || !result) return result; + const after = await this.current(client); + for (const dir of after) { + dir.files = dir.files.map((file) => + file.path === "SKILL.md" ? { ...markdown(dir.body), executable: file.executable } : file, + ); + } + const source = row.source; + const write = async (repo: Pick) => { + if (repo.head !== row.upstream_sha) + throw new SkillConflict("The repository changed. Sync before editing."); + return repo.write( + source.kind === "managed" ? managedFolder : source.folder, + after, + "Update Factorize skills", + ); + }; + const upstream = + source.kind === "managed" + ? await withSkillGit(await this.managed(row, "write"), write) + : await write(await this.github(client, source)); + const commit = + source.kind === "managed" + ? upstream + : await withSkillGit(await this.managed(row, "write"), (repo) => + repo.write(managedFolder, after, "Sync GitHub " + upstream), + ); + for (const dir of after) { + if (dir.version?.commit === commit) continue; + await client.query("UPDATE app.skills SET encrypted_directory=$3 WHERE tenant_id=$1 AND id=$2", [ + this.tenant, + dir.id, + await encrypt(JSON.stringify({ commit, files: dir.files }), this.env.CREDENTIAL_ENCRYPTION_KEY), + ]); + } + await client.query( + "UPDATE app.skill_libraries SET commit_sha=$2,upstream_sha=$3,error=NULL,checked_at=now() WHERE tenant_id=$1", + [this.tenant, commit, upstream], + ); + return result; + }); + } +} diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index b1c557ca..1efb68d2 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -28,6 +28,7 @@ export interface Env { POSTMARK_SERVER_TOKEN?: string; POSTMARK_FROM_EMAIL?: string; POSTMARK_MESSAGE_STREAM?: string; + SKILL_ARTIFACTS?: Artifacts; RUN_ARTIFACTS?: R2Bucket; /** Pause automatic retention and artifact-history deletion while retaining maintenance visibility. */ RUN_HISTORY_RETENTION_PAUSED?: string; diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index f4c96e3a..186b9735 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -1,3 +1,4 @@ +import { SkillLibrary } from "./skill-library"; import { authenticateVmGrant, VM_GRANT_HEADER } from "./vm-grants"; import { staticApp, securityHeaders } from "./static-app"; import { OAuthProvider, AuthorizationError, getOAuthApi, type AuthRequest, type OAuthProviderOptions } from "@cloudflare/workers-oauth-provider"; @@ -155,4 +156,11 @@ const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext) return response; } } satisfies ExportedHandler; -export default { async fetch(request: Request, env: Env, ctx: ExecutionContext) { return securityHeaders(request, await backend.fetch(request, env, ctx)); } } satisfies ExportedHandler; +export default { + async scheduled(_event: ScheduledController, env: Env) { + // Retry missed deliveries and refresh managed remotes in oldest-checked order. + const db = databaseFor(env); + const rows = await db.pool.query("SELECT tenant_id FROM app.skill_libraries WHERE checked_at IS NULL OR checked_at < now()-interval '5 minutes' ORDER BY checked_at NULLS FIRST LIMIT 10"); + for (const row of rows.rows) await new SkillLibrary(env,row.tenant_id).sync(); + }, + async fetch(request: Request, env: Env, ctx: ExecutionContext) { return securityHeaders(request, await backend.fetch(request, env, ctx)); } } satisfies ExportedHandler; diff --git a/packages/api/test/fixtures/agent-api-runtime-worker.ts b/packages/api/test/fixtures/agent-api-runtime-worker.ts index 31d62e24..9f77474d 100644 --- a/packages/api/test/fixtures/agent-api-runtime-worker.ts +++ b/packages/api/test/fixtures/agent-api-runtime-worker.ts @@ -1,3 +1,4 @@ +export { SkillPushWorkflow } from "../../src/cloudflare-entry"; import { RunScheduler } from "../../src/postgres/run-scheduler"; import { databaseFor } from "../../src/postgres/database"; import type {ExecutionBackend, JobResultReader} from "../../src/execution"; diff --git a/packages/api/test/skill-library.postgres.test.ts b/packages/api/test/skill-library.postgres.test.ts new file mode 100644 index 00000000..8ff8aa83 --- /dev/null +++ b/packages/api/test/skill-library.postgres.test.ts @@ -0,0 +1,224 @@ +import { createHmac } from "node:crypto"; +import { encrypt, decrypt } from "../src/crypto"; +import { PostgresJobRepository } from "../src/postgres/job-repository"; +import { InvocationService } from "../src/job-domain"; +import { SkillPushWorkflow } from "../src/cloudflare-entry"; +import app from "../src/index"; +import { afterEach, expect, it, vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { SkillLibrary } from "../src/skill-library"; +import { SkillRepository } from "../src/postgres/skill-repository"; +import { markdown, type Directory } from "../src/skill-files"; +import { withSkillGit } from "../src/skill-git"; +import { GitHubRepository } from "../src/postgres/github-repository"; +import { installationToken } from "../src/github"; +import { protectedApiFetch } from "../src/protected-api"; + +vi.mock("cloudflare:workers", () => ({ + WorkflowEntrypoint: class {}, + 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() })); +vi.mock("../src/github", async (original) => ({ + ...(await original()), + installationToken: vi.fn(), +})); +afterEach(() => { + vi.unstubAllGlobals(); + vi.clearAllMocks(); +}); + +it.skipIf(!process.env.AUTH_TEST_DATABASE_URL)( + "publishes GitHub pushes to an Artifacts mirror and preserves referenced IDs and accepted revisions", + async () => { + const f = await loadingFixture(process.env.AUTH_TEST_DATABASE_URL!); + try { + const store = new SkillRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + const initial = await store.create("sample", "One"); + await f.db.pool.query( + "INSERT INTO app.job_skills(tenant_id,job_id,skill_id,position) VALUES($1,$2,$3,0)", + [f.tenantId, f.jobIds[3], initial.id], + ); + const library = new SkillLibrary(f.env, f.tenantId); + let commit = "a".repeat(40), + key = "sample", + body = "One"; + let mirrorHead: string | null = null, + mirrored: Directory[] = []; + const token = { plaintext: "fixture", expiresAt: "2026-11-20T00:00:00Z" }; + f.env.SKILL_ARTIFACTS = { + create: vi.fn(async () => ({ remote: "https://fixture.test/library.git", token: "fixture" })), + get: async () => ({ createToken: async () => token }), + } as any; + vi.mocked(withSkillGit).mockImplementation(async (_remote, work) => + work({ + head: mirrorHead, + directories: async () => mirrored, + write: async (_folder: string, dirs: Directory[]) => { + mirrored = dirs; + mirrorHead = crypto.randomUUID(); + return mirrorHead; + }, + } as any), + ); + await new GitHubRepository(f.db, f.tenantId).save({ + installationId: 123, + accountLogin: "org", + accountType: "Organization", + state: "active", + }); + vi.mocked(installationToken).mockResolvedValue("github-fixture"); + vi.stubGlobal( + "fetch", + vi.fn(async (input: string) => { + const path = new URL(input).pathname; + if (path === "/repositories/42") return Response.json({ id: 42, full_name: "test/repo" }); + if (path.endsWith("/ref/heads/main")) return Response.json({ object: { sha: commit } }); + if (path.endsWith("/git/commits/" + commit)) return Response.json({ tree: { sha: "root" } }); + if (path.endsWith("/trees/root")) + return Response.json({ tree: [{ path: "skills", type: "tree", sha: "skills-dir" }] }); + if (path.endsWith("/trees/skills-dir")) + return Response.json({ + tree: key + ? [ + { path: key, type: "tree" }, + { path: key + "/SKILL.md", type: "blob", sha: "blob", mode: "100644", size: body.length }, + ] + : [], + }); + if (path.endsWith("/blobs/blob")) return Response.json({ encoding: "base64", content: btoa(body) }); + return new Response(null, { status: 404 }); + }), + ); + const input = { + kind: "github", + installationId: 123, + repositoryId: 42, + branch: "main", + folder: "skills", + } as const; + const url = f.env.APP_ORIGIN + "/api/v1/skill-library"; + const request = () => + new Request(url, { + method: "PUT", + headers: { "Content-Type": "application/json", Origin: f.env.APP_ORIGIN }, + body: JSON.stringify(input), + }); + expect( + ( + await protectedApiFetch( + request(), + f.env, + { ...f.auth, scopes: ["skills:write"] }, + {} as ExecutionContext, + ) + ).status, + ).toBe(403); + expect( + ( + await protectedApiFetch( + request(), + f.env, + { ...f.auth, scopes: ["skills:write", "integrations:write"] }, + {} as ExecutionContext, + ) + ).status, + ).toBe(200); + expect(installationToken).toHaveBeenCalledWith(f.env, 123, 42); + expect(await store.get(initial.id)).toMatchObject({ body: "One", revision: 1 }); + const crypt = (value: string) => encrypt(value, f.env.CREDENTIAL_ENCRYPTION_KEY); + const jobs = new PostgresJobRepository(f.db, f.tenantId, crypt, (value) => + decrypt(value, f.env.CREDENTIAL_ENCRYPTION_KEY), + ); + const selected = await jobs.getJob(f.jobIds[3]); + const queued = await new InvocationService(jobs, crypt).invoke(f.jobIds[3], { + source: "manual", + claimKey: "snapshot", + triggerId: selected!.triggers[0].id, + context: {}, + }); + const pinned = mirrorHead; + const match = { installationId: 123, repositoryId: 42, ref: "refs/heads/main" }; + body = "Two"; + commit = "b".repeat(40); + await library.sync({ ...match, repositoryId: 43 }); + expect((await library.status()).upstreamCommit).not.toBe(commit); + const raw = JSON.stringify({ + installation: { id: 123 }, + repository: { id: 42 }, + ref: match.ref, + after: commit, + }); + f.env.GITHUB_WEBHOOK_SECRET = "fixture-secret"; + const sign = createHmac("sha256", f.env.GITHUB_WEBHOOK_SECRET).update(raw).digest("hex"); + const delivery = (signature: string) => + app.fetch( + new Request(f.env.APP_ORIGIN + "/webhooks/github", { + method: "POST", + body: raw, + headers: { + "X-Hub-Signature-256": "sha256=" + signature, + "X-GitHub-Event": "push", + "X-GitHub-Delivery": "fixture-delivery", + }, + }), + f.env, + ); + expect((await delivery("invalid")).status).toBe(401); + expect((await library.status()).upstreamCommit).not.toBe(commit); + expect((await delivery(sign)).status).toBe(202); + await library.sync(match); + expect(await store.get(initial.id)).toMatchObject({ + body: "Two", + revision: 2, + version: { commit: mirrorHead }, + }); + expect(mirrored[0].files).toEqual([markdown("Two")]); + const saved = ( + await f.db.pool.query( + "SELECT encrypted_skill_snapshot FROM app.job_runs WHERE tenant_id=$1 AND id=$2", + [f.tenantId, queued.run.id], + ) + ).rows[0]; + expect( + JSON.parse(await decrypt(saved.encrypted_skill_snapshot, f.env.CREDENTIAL_ENCRYPTION_KEY))[0].version, + ).toEqual({ commit: pinned, files: [markdown("One")] }); + key = "renamed"; + commit = "c".repeat(40); + await library.sync(match); + expect(await store.get(initial.id)).toMatchObject({ key: "renamed", revision: 3 }); + key = ""; + commit = "d".repeat(40); + await library.sync(match); + expect((await library.status()).error).toContain("referenced"); + expect((await library.status()).upstreamCommit).toBe("c".repeat(40)); + expect(await store.get(initial.id)).toMatchObject({ body: "Two", revision: 3 }); + expect((await new SkillLibrary(f.env, f.otherTenant).status()).source).toBeNull(); + await library.configure({ kind: "managed" }); + const row = ( + await f.db.pool.query("SELECT repo FROM app.skill_libraries WHERE tenant_id=$1", [f.tenantId]) + ).rows[0]; + mirrorHead = "e".repeat(40); + mirrored = [{ key: "renamed", files: [markdown("Managed push")] }]; + const workflow = Object.assign(Object.create(SkillPushWorkflow.prototype), { env: f.env }); + await workflow.run( + { + payload: { + source: { namespace: "factorize-skills", repoName: row.repo }, + payload: { ref: "refs/heads/main" }, + }, + }, + { do: (_label: string, run: () => Promise) => run() }, + ); + expect(await store.get(initial.id)).toMatchObject({ body: "Managed push", revision: 4 }); + } finally { + await f.cleanup(); + } + }, +); diff --git a/packages/api/test/skill-library.test.ts b/packages/api/test/skill-library.test.ts new file mode 100644 index 00000000..51b08663 --- /dev/null +++ b/packages/api/test/skill-library.test.ts @@ -0,0 +1,148 @@ +import { execFileSync } from "node:child_process"; +import { createServer } from "node:http"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, it } from "vitest"; +import { withSkillGit } from "../src/skill-git"; +import { markdown, snapshotFiles } from "../src/skill-files"; +import { librarySource } from "../src/skill-library-contract"; +import { API_ROUTES } from "../src/api-contract"; +import { FACTORIZE_JOB_LAUNCHER } from "../src/factorize-job-launcher"; + +it("round trips skill directories through a real Git HTTPS-protocol backend and stages pinned bytes", async () => { + const root = await mkdtemp(join(tmpdir(), "skills-git-")); + const remotePath = join(root, "skills.git"); + execFileSync("git", ["init", "--bare", "-q", "-b", "main", remotePath]); + execFileSync("git", ["-C", remotePath, "config", "http.receivepack", "true"]); + const server = createServer(async (req, res) => { + const url = new URL(req.url!, "http://localhost"); + const chunks: Buffer[] = []; + for await (const chunk of req) chunks.push(chunk); + const response = execFileSync("git", ["http-backend"], { + input: Buffer.concat(chunks), + env: { + ...process.env, + GIT_PROJECT_ROOT: root, + GIT_HTTP_EXPORT_ALL: "yes", + PATH_INFO: url.pathname, + QUERY_STRING: url.search.slice(1), + REQUEST_METHOD: req.method, + CONTENT_TYPE: req.headers["content-type"], + HTTP_GIT_PROTOCOL: req.headers["git-protocol"] as string, + }, + }); + const split = response.toString("latin1").indexOf("\r\n\r\n"); + for (const line of response.subarray(0, split).toString().split("\r\n")) { + const index = line.indexOf(": "); + res.setHeader(line.slice(0, index), line.slice(index + 2)); + } + res.end(response.subarray(split + 4)); + }); + try { + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const url = "http://127.0.0.1:" + (server.address() as { port: number }).port + "/skills.git"; + const remote = { url, branch: "main", headers: {} }; + const files = [ + markdown("One"), + { path: "scripts/count", executable: true, content: btoa("#!/bin/sh\nprintf staged") }, + ]; + const first = await withSkillGit(remote, (repo) => + repo.write("skills", [{ key: "example", files }], "first"), + ); + const snapshot = snapshotFiles([{ key: "example", body: "One", version: { commit: first, files } }]); + await withSkillGit(remote, async (repo) => { + expect(repo.head).toBe(first); + expect(await repo.directories("skills")).toEqual([{ key: "example", files }]); + await repo.write("skills", [{ key: "example", files: [markdown("Two")] }], "second"); + }); + expect( + execFileSync("git", ["-C", remotePath, "show", "main:skills/example/SKILL.md"], { encoding: "utf8" }), + ).toBe("Two"); + const launcher = FACTORIZE_JOB_LAUNCHER.replace("/home/exedev/.factorize-job", join(root, "guest")); + const payload = { + version: 1, + runId: "fixture", + prompt: "", + skillFiles: snapshot, + harness: { + executable: "sh", + args: [ + "-c", + 'cat "$FACTORIZE_SKILLS_DIR/example/SKILL.md"; "$FACTORIZE_SKILLS_DIR/example/scripts/count"', + ], + env: {}, + }, + }; + expect( + execFileSync("python3", ["-c", launcher, "launch", "--foreground"], { + input: JSON.stringify(payload), + encoding: "utf8", + }), + ).toBe("Onestaged"); + } finally { + await new Promise((resolve) => server.close(resolve)); + await rm(root, { force: true, recursive: true }); + } +}); + +it("protects skill repository operations and validates directory selection", () => { + const routes = API_ROUTES.filter((route) => route.path.startsWith("/api/v1/skill-library")); + expect(routes).toHaveLength(4); + for (const route of routes) + expect(route.scope).toBe(route.method === "GET" ? "skills:read" : "skills:write"); + expect( + librarySource.safeParse({ + kind: "github", + branch: "main", + folder: "../private", + installationId: 1, + repositoryId: 2, + }).success, + ).toBe(false); +}); + +it("updates only the configured GitHub folder and uses a non-forced ref update anchored to the observed head", async () => { + const { GitHubSkills } = await import("../src/skill-github"); + const { vi } = await import("vitest"); + const calls: { path: string; body: any }[] = []; + const stub = vi.spyOn(globalThis, "fetch").mockImplementation(async (url, options) => { + const path = new URL(String(url)).pathname.replace("/repos/org/repo", ""); + const body = options?.body && JSON.parse(String(options.body)); + calls.push({ path, body }); + if (path === "/git/ref/heads/team/main") return Response.json({ object: { sha: "parent" } }); + if (path === "/git/commits/parent") return Response.json({ tree: { sha: "root" } }); + if (path === "/git/trees/root") + return Response.json({ tree: [{ path: "skills", type: "tree", sha: "subtree" }], truncated: false }); + if (path === "/git/trees/subtree") + return Response.json({ + tree: [{ path: "review/SKILL.md", type: "blob", mode: "100644", sha: "old", size: 4 }], + truncated: false, + }); + if (path === "/git/blobs") return Response.json({ sha: "new-blob" }); + if (path === "/git/trees") return Response.json({ sha: "new-tree" }); + if (path === "/git/commits") return Response.json({ sha: "new-head" }); + if (path === "/git/refs/heads/team/main") return new Response(null, { status: 422 }); + throw new Error("Unexpected GitHub request " + path); + }); + try { + const repo = new GitHubSkills("https://api.github.com/repos/org/repo", "installation-token", "team/main"); + await repo.open(); + await expect( + repo.write("skills", [{ key: "review", files: [markdown("New")] }], "Edit skill"), + ).rejects.toThrow("422"); + expect(calls.slice(-3)).toEqual([ + { + path: "/git/trees", + body: { + base_tree: "root", + tree: [{ path: "skills/review/SKILL.md", type: "blob", mode: "100644", sha: "new-blob" }], + }, + }, + { path: "/git/commits", body: { tree: "new-tree", parents: ["parent"], message: "Edit skill" } }, + { path: "/git/refs/heads/team/main", body: { sha: "new-head", force: false } }, + ]); + } finally { + stub.mockRestore(); + } +}); diff --git a/packages/api/wrangler.jsonc b/packages/api/wrangler.jsonc index 27a29fd2..be1dd59c 100644 --- a/packages/api/wrangler.jsonc +++ b/packages/api/wrangler.jsonc @@ -1,12 +1,15 @@ { "$schema": "../../node_modules/wrangler/config-schema.json", "name": "factorize", - "main": "src/worker.ts", + "main": "src/cloudflare-entry.ts", "compatibility_date": "2026-09-10", - "compatibility_flags": ["global_fetch_strictly_public"], + "compatibility_flags": ["global_fetch_strictly_public", "nodejs_compat"], "assets": { "directory": "../app/dist", "binding": "ASSETS", "run_worker_first": true, "not_found_handling": "none" }, "kv_namespaces": [{ "binding": "OAUTH_KV", "id": "cacbf744337747ffbb9c0153329aad4f" }], "hyperdrive": [{ "binding": "HYPERDRIVE", "id": "9b6c8a09921d4ee18cdf3723135c82ad" }], + "artifacts": [{ "binding": "SKILL_ARTIFACTS", "namespace": "factorize-skills", "remote": false }], + "workflows": [{ "binding": "SKILL_PUSH", "name": "factorize-skill-push", "class_name": "SkillPushWorkflow" }], + "triggers": { "crons": ["*/5 * * * *"], "events": [{ "type": "cf.artifacts.repo.pushed", "filter": { "namespace": "factorize-skills" }, "targets": [{ "type": "workflow", "workflow_name": "factorize-skill-push" }] }] }, "r2_buckets": [{ "binding": "RUN_ARTIFACTS", "bucket_name": "factorize-run-artifacts" }], "durable_objects": { "bindings": [{ "name": "SCHEDULER", "class_name": "AlarmCoordinator" }] diff --git a/packages/app/src/features/skills/detail.tsx b/packages/app/src/features/skills/detail.tsx index bac91807..79ae35c3 100644 --- a/packages/app/src/features/skills/detail.tsx +++ b/packages/app/src/features/skills/detail.tsx @@ -4,14 +4,14 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api } from "factorize-api-client"; import { Breadcrumb, Button, Card, Input, Label, Page, PageHeader, Textarea } from "../../shared/ui"; import { messageOf } from "../auth/session"; -import { skillQuery, skillsQuery } from "./queries"; +import { skillQuery } from "./queries"; export function SkillDetail() { const { skillId } = useParams({ from: "/skills/$skillId" }); const skill = useQuery(skillQuery(skillId)); const cache = useQueryClient(); const [editing, setEditing] = useState(false), [key, setKey] = useState(""), [body, setBody] = useState(""); - const edit = useMutation({ mutationFn: async () => { const result = await api.PUT("/api/v1/skills/{skillId}", { params: { path: { skillId } }, body: { key, body, expectedRevision: skill.data!.revision } }); if (!result.data || result.error) throw new Error(messageOf(result.error)); return result.data; }, onSuccess: async updated => { cache.setQueryData(skillQuery(skillId).queryKey, updated); await cache.invalidateQueries({ queryKey: skillsQuery().queryKey }); setEditing(false); } }); + const edit = useMutation({ mutationFn: async () => { const result = await api.PUT("/api/v1/skills/{skillId}", { params: { path: { skillId } }, body: { key, body, expectedRevision: skill.data!.revision } }); if (!result.data || result.error) throw new Error(messageOf(result.error)); return result.data; }, onSuccess: async updated => { cache.setQueryData(skillQuery(skillId).queryKey, updated); await Promise.all([cache.invalidateQueries({ queryKey: ["skills"] }), cache.invalidateQueries({ queryKey: ["skill-library"] })]); setEditing(false); } }); const startEditing = () => { if (!skill.data) return; setKey(skill.data.key); setBody(skill.data.body); setEditing(true); }; return Skills{skill.data?.key ?? "Skill"}{skill.isPending &&

Loading skill…

}{skill.error &&

{skill.error.message}

}{skill.data && <>View runs{editing ?
{ event.preventDefault(); edit.mutate(); }}>