mirror of
https://github.com/anomalyco/opencode.git
synced 2026-10-08 16:25:33 +00:00
Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f2b10993d | ||
|
|
8f4861875f | ||
|
|
6861df7638 | ||
|
|
53533fd0bf | ||
|
|
3b684acd8d | ||
|
|
5d05835023 | ||
|
|
0d07f915d2 | ||
|
|
216c311744 | ||
|
|
6297cd5a0b | ||
|
|
c28e9ec311 | ||
|
|
46c69bc35c | ||
|
|
be19c7612f | ||
|
|
162bc6922b | ||
|
|
87a1ebcc97 | ||
|
|
2138bfd02a | ||
|
|
98d57d0dd2 | ||
|
|
fcad1319bf | ||
|
|
e3419d47ee | ||
|
|
d016db856c | ||
|
|
613ef8ba87 | ||
|
|
b8d3c92985 | ||
|
|
8587f817cc | ||
|
|
a98adc1ab0 | ||
|
|
31bdd8e8f7 | ||
|
|
cab7e2c242 | ||
|
|
56be008756 | ||
|
|
554e7c2341 | ||
|
|
5183ea45c3 | ||
|
|
053e534e5a | ||
|
|
8bd8960154 | ||
|
|
d5154fb74e | ||
|
|
70c6c8cbc5 | ||
|
|
e2979039f1 |
No files matched your search
@@ -131,6 +131,7 @@
|
||||
"@opencode/util": "workspace:*",
|
||||
"@opentui/core": "catalog:",
|
||||
"@opentui/solid": "catalog:",
|
||||
"@opentunnel/client": "0.2.0",
|
||||
"@parcel/watcher": "2.5.1",
|
||||
"@silvia-odwyer/photon-node": "0.3.4",
|
||||
"diff": "catalog:",
|
||||
@@ -638,8 +639,8 @@
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opencode/theme": "workspace:*",
|
||||
"@opentui/core": ">=0.5.14",
|
||||
"@opentui/solid": ">=0.5.14",
|
||||
"@opentui/core": ">=0.5.16",
|
||||
"@opentui/solid": ">=0.5.16",
|
||||
"solid-js": ">=1.9.0",
|
||||
},
|
||||
"optionalPeers": [
|
||||
@@ -966,6 +967,7 @@
|
||||
"name": "@opencode/ui",
|
||||
"version": "2.0.24",
|
||||
"dependencies": {
|
||||
"@kitlangton/solid-motion": "0.2.2",
|
||||
"@kobalte/core": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@solid-primitives/event-listener": "catalog:",
|
||||
@@ -1156,9 +1158,9 @@
|
||||
"@npmcli/arborist": "9.4.0",
|
||||
"@octokit/rest": "22.0.0",
|
||||
"@openauthjs/openauth": "0.0.0-20250322224806",
|
||||
"@opentui/core": "0.5.14",
|
||||
"@opentui/keymap": "0.5.14",
|
||||
"@opentui/solid": "0.5.14",
|
||||
"@opentui/core": "0.5.16",
|
||||
"@opentui/keymap": "0.5.16",
|
||||
"@opentui/solid": "0.5.16",
|
||||
"@pierre/diffs": "1.5.1",
|
||||
"@playwright/test": "1.59.1",
|
||||
"@sentry/solid": "10.71.0",
|
||||
@@ -2018,6 +2020,8 @@
|
||||
|
||||
"@jsx-email/text": ["@jsx-email/text@1.0.2", "", { "peerDependencies": { "react": "^18.2.0" } }, "sha512-0zzwEwrKtY6tfjPJF0r3krKCDpP/ySYDvkn4+MvIFrIH5RZKmn3XDa5o/3hkbxMwpLn4MsXGIXn9XzMTaqTfUA=="],
|
||||
|
||||
"@kitlangton/solid-motion": ["@kitlangton/solid-motion@0.2.2", "", { "dependencies": { "motion-dom": "14.0.0", "motion-utils": "14.0.0" }, "peerDependencies": { "solid-js": "^1.8.0" } }, "sha512-Fp7T8gJta3aRGJakBPQ6WIWmF6U6TmWhT6sGNNgkBiJ8cOVfuKkF9yYXzhvgRtKpo7WfzxtNLku907dLHhTDtw=="],
|
||||
|
||||
"@kobalte/core": ["@kobalte/core@0.13.13", "", { "dependencies": { "@floating-ui/dom": "^1.5.1", "@internationalized/number": "^3.2.1", "@kobalte/utils": "^0.9.2", "@solid-primitives/props": "^3.1.8", "@solid-primitives/resize-observer": "^2.0.26", "solid-presence": "^0.2.0", "solid-prevent-scroll": "^0.1.11" }, "peerDependencies": { "solid-js": "^1.9.8" } }, "sha512-czBC+IQdOgJoW7DJjeh0rht7SPmTPgWsKg7Jo3RHMfwx028WxJtDylx9dJuJuD/GUae15+E4nYafu8LwuixFYQ=="],
|
||||
|
||||
"@kobalte/utils": ["@kobalte/utils@0.9.2", "", { "dependencies": { "@solid-primitives/event-listener": "^2.2.14", "@solid-primitives/keyed": "^1.2.0", "@solid-primitives/map": "^0.4.7", "@solid-primitives/media": "^2.2.4", "@solid-primitives/props": "^3.1.8", "@solid-primitives/refs": "^1.0.5", "@solid-primitives/utils": "^6.2.1" }, "peerDependencies": { "solid-js": "^1.8.8" } }, "sha512-jRVXr+zsVHxzDXRoh+CDeXzvCsFJ6uiHhqqNQ26Cw9ZsZ3D6nqPUBt1gGVtj2ZPmRL3a9Uk1v8D1aJ8/I12Dow=="],
|
||||
@@ -2302,27 +2306,31 @@
|
||||
|
||||
"@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.43.0", "", {}, "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg=="],
|
||||
|
||||
"@opentui/core": ["@opentui/core@0.5.14", "", { "dependencies": { "bun-ffi-structs": "0.3.1", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0", "strip-ansi": "7.1.2" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.5.14", "@opentui/core-darwin-x64": "0.5.14", "@opentui/core-linux-arm64": "0.5.14", "@opentui/core-linux-arm64-musl": "0.5.14", "@opentui/core-linux-x64": "0.5.14", "@opentui/core-linux-x64-musl": "0.5.14", "@opentui/core-win32-arm64": "0.5.14", "@opentui/core-win32-x64": "0.5.14" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-tfQ+PWQyeBnYloB3diEcPqbILv14xemH5jjAEICfPuyNDtGBqrjhUtThrhbvFRuPMcj6IEeXrAk6VE8e91h0kg=="],
|
||||
"@opentui/core": ["@opentui/core@0.5.16", "", { "dependencies": { "bun-ffi-structs": "0.3.1", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0", "strip-ansi": "7.1.2" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.5.16", "@opentui/core-darwin-x64": "0.5.16", "@opentui/core-linux-arm64": "0.5.16", "@opentui/core-linux-arm64-musl": "0.5.16", "@opentui/core-linux-x64": "0.5.16", "@opentui/core-linux-x64-musl": "0.5.16", "@opentui/core-win32-arm64": "0.5.16", "@opentui/core-win32-x64": "0.5.16" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-RDVip7Ih8Lg5tFkwTDGFqc0TXx8A+rRvm3UuDAqd9YayDx4fIsECBjSS8FDPLYvq5KP1gJB4oY8iGM8WgTbNqw=="],
|
||||
|
||||
"@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.5.14", "", { "os": "darwin", "cpu": "arm64" }, "sha512-wWmw41wRMBoI0lN9mgyzGRwYujwwfNkBP6jYM99k4Bx2XkeSZ3sCeu5bwX9vEJPYqjiBShbDhc0NnVSP7NwzVg=="],
|
||||
"@opentui/core-darwin-arm64": ["@opentui/core-darwin-arm64@0.5.16", "", { "os": "darwin", "cpu": "arm64" }, "sha512-mbdp/A2KJOv7hI0b0ezqZx/5vh5G6LwhZnjRW4K3hNcoZM4yC55y/D+L8J960rT4o7QRB3cNXr3NSlnVi1btZA=="],
|
||||
|
||||
"@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.5.14", "", { "os": "darwin", "cpu": "x64" }, "sha512-7smHKDH8IhUaBsgYuAClMl2mHWu+yjpMrtdw3wEvBVtCzKMrHi/TJ5PtydO+IfUzR3BXpVubdbR1irD8BTcR/w=="],
|
||||
"@opentui/core-darwin-x64": ["@opentui/core-darwin-x64@0.5.16", "", { "os": "darwin", "cpu": "x64" }, "sha512-D1oA0VBitDHOYrg58GaxQQNAXJ1nSFwu2HQMZklL/LkrqZLX23K/oxgutH/GKvLsyRQNsIVfsXmGZ2LtGiGpxA=="],
|
||||
|
||||
"@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.5.14", "", { "os": "linux", "cpu": "arm64" }, "sha512-xH1hP+NaLySEJeZkl21NlkZBMddMfQ1jU8NeX1AEBc2GNBOvDXU4Ud/xw87SrAvU1xG9K7/9C4oy4AmIMEpVGg=="],
|
||||
"@opentui/core-linux-arm64": ["@opentui/core-linux-arm64@0.5.16", "", { "os": "linux", "cpu": "arm64" }, "sha512-ghu4tKIR3wZMZ8Ih/VLeyyG/C7kQgAZuKoGKRSUPcVEF6Qr99yHhtIixBrBoFXfqVm63n5lGimS6KKqbdUQ1yA=="],
|
||||
|
||||
"@opentui/core-linux-arm64-musl": ["@opentui/core-linux-arm64-musl@0.5.14", "", { "os": "linux", "cpu": "arm64" }, "sha512-mnBBAuTb92NiRLAjOD755tS8/tNQemDztbg9tMvoCT90G52FtVrRb31Ge6OrYqfm0c9DkZGhEBOhunsId/4zSA=="],
|
||||
"@opentui/core-linux-arm64-musl": ["@opentui/core-linux-arm64-musl@0.5.16", "", { "os": "linux", "cpu": "arm64" }, "sha512-t1vppHpf6iR7k+JF6kQtcLKr11gIxm2nH1h9y3eawrG4NCXDQbOvn7XtC6KsT3I1iy0A2Yy+nM0heISziORZlQ=="],
|
||||
|
||||
"@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.5.14", "", { "os": "linux", "cpu": "x64" }, "sha512-Hkk4kaDGMcn9bmJFJPW3/QOGGbPuWe3sCFV/CkiVb4+bCvcTm7EXQr4QTAA63BYy2dKE5bUFUi1zZlyeMkWpnA=="],
|
||||
"@opentui/core-linux-x64": ["@opentui/core-linux-x64@0.5.16", "", { "os": "linux", "cpu": "x64" }, "sha512-y63M7JrjfAQPUwTXogDGqBjS46DfC51LebBUQYVE01/N2F1inybD08qEfxUAFx/Omlf7CXef6liLDdRyTLaohw=="],
|
||||
|
||||
"@opentui/core-linux-x64-musl": ["@opentui/core-linux-x64-musl@0.5.14", "", { "os": "linux", "cpu": "x64" }, "sha512-ngJ+U2grOGEteeQvZdAJNqn09M+At5mfWInauK5aS427bea1yLo+e6hor/CRmbn9SxEEF+SwoyekaOrLPWyU7w=="],
|
||||
"@opentui/core-linux-x64-musl": ["@opentui/core-linux-x64-musl@0.5.16", "", { "os": "linux", "cpu": "x64" }, "sha512-lQ1kRwFPBRElG2uFl0afWzpHyUwVEizbV2Ue1IA8DXH15sRCOd7KqeOltpzuKJYIyLey7vLF8SofAe8K1JNnTg=="],
|
||||
|
||||
"@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.5.14", "", { "os": "win32", "cpu": "arm64" }, "sha512-T9kNqKXg2jysmTsyyZ1A8LBQotFBM+iPjzyRslxyexqrs8a1UcmxbApEo+COtxQuqukMTbvwyqEdAT8vcmxEkQ=="],
|
||||
"@opentui/core-win32-arm64": ["@opentui/core-win32-arm64@0.5.16", "", { "os": "win32", "cpu": "arm64" }, "sha512-cML9+1tqEe+SaB5xlx9jKcYAIG15Eg9sImH/LYyMbm+al7dRBNy5IzdFCldXfwC50blM/goiyzLN1CjTo02vCQ=="],
|
||||
|
||||
"@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.5.14", "", { "os": "win32", "cpu": "x64" }, "sha512-mqKSkab8VdMLSmMdocna7+BTyMoIutkVXOV9lfmPrBO2g7Np5c6c4SJ4QIVZqPvast11XyT0/7FfXOYLKAS72w=="],
|
||||
"@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.5.16", "", { "os": "win32", "cpu": "x64" }, "sha512-1QZ9yHK9xTZBNXVgjPfbdQ94nfw0/KZic9XkuAsNBzUGTkYmfGKZSvPB1YKomBt/1lipRoCdMAnihlS/R7g5eg=="],
|
||||
|
||||
"@opentui/keymap": ["@opentui/keymap@0.5.14", "", { "dependencies": { "@opentui/core": "0.5.14" }, "peerDependencies": { "@opentui/react": "0.5.14", "@opentui/solid": "0.5.14", "react": ">=19.2.0", "solid-js": "1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-YGTAvRrpQTbRNV7GH0UxRuCSPxwnSooVdB+qPHHP+3ywc93+lhekljgP8dRivl32f3CiMqqm96Uj2PgwKxkC0Q=="],
|
||||
"@opentui/keymap": ["@opentui/keymap@0.5.16", "", { "dependencies": { "@opentui/core": "0.5.16" }, "peerDependencies": { "@opentui/react": "0.5.16", "@opentui/solid": "0.5.16", "react": ">=19.2.0", "solid-js": "1.9.12" }, "optionalPeers": ["@opentui/react", "@opentui/solid", "react", "solid-js"] }, "sha512-W78sDuTHMjHa8NwYmoGx5Xy0ztcGsuzrUa/1d24jADj9JCYEJQjABnrWZBRSExsNjiFYV3SxeCKwAPhJli0M3g=="],
|
||||
|
||||
"@opentui/solid": ["@opentui/solid@0.5.14", "", { "dependencies": { "@babel/core": "7.28.0", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.5.14", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.12", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "1.9.12" } }, "sha512-bBRl34mZ0wFGhjHX6y1VNiZmJ3DSm2DVPm0PNSVDpvq9qxRHuywEPTCn/Lgte0C9450tgf11cDqcE3pR9cZwVA=="],
|
||||
"@opentui/solid": ["@opentui/solid@0.5.16", "", { "dependencies": { "@babel/core": "7.29.7", "@babel/preset-typescript": "7.27.1", "@opentui/core": "0.5.16", "babel-plugin-module-resolver": "5.0.2", "babel-preset-solid": "1.9.12", "entities": "7.0.1", "s-js": "^0.4.9" }, "peerDependencies": { "solid-js": "1.9.12" } }, "sha512-gCULWG+HORd5IVydiCchlmULgY1PQccODJvJKDNYJHDmhwyg9/sNSFUxoYajEXLZ40pUIL8ENAK+6p34Z9m/JQ=="],
|
||||
|
||||
"@opentunnel/client": ["@opentunnel/client@0.2.0", "", { "dependencies": { "@opentunnel/protocol": "0.2.0", "effect": "4.0.0-rc.112" } }, "sha512-UHbLK+y2aPdcTuu4FaCz3Ezcm52Z4TxGp5Hdy9aLYLsz9GUlPpPFaYXjdq8pFyfQlA9qAyI/z5zx5FlZx3aSbw=="],
|
||||
|
||||
"@opentunnel/protocol": ["@opentunnel/protocol@0.2.0", "", { "dependencies": { "effect": "4.0.0-rc.112" } }, "sha512-XQAm3InG70HysML+NiSPxCCfoP+ZzWuxXcCFFFh/qxrvMxuJyOrxsPT49vTo2rDCgrYYdbiFqpz8oXIJh0BYXw=="],
|
||||
|
||||
"@oslojs/asn1": ["@oslojs/asn1@1.0.0", "", { "dependencies": { "@oslojs/binary": "1.0.0" } }, "sha512-zw/wn0sj0j0QKbIXfIlnEcTviaCzYOY3V5rAyjR6YtOByFtJiT574+8p9Wlach0lZH9fddD4yb9laEAIl4vXQA=="],
|
||||
|
||||
@@ -4790,9 +4798,9 @@
|
||||
|
||||
"motion": ["motion@12.34.5", "", { "dependencies": { "framer-motion": "^12.34.5", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-N06NLJ9IeBHeielRqIvYvjPfXuRdyTxa+9++BgpGa+hY2D7TcMkI6QzV3jaRuv0aZRXgMa7cPy9YcBUBisPzAQ=="],
|
||||
|
||||
"motion-dom": ["motion-dom@12.43.0", "", { "dependencies": { "motion-utils": "^12.39.0" } }, "sha512-azKON4d9S65PEoFUiQTMTgPheEmzf2QngdRc50AKfJp9Q9mmcBVw22c8eMq9k8kxOFHdL7+WZY7N/5F/lwiDag=="],
|
||||
"motion-dom": ["motion-dom@14.0.0", "", { "dependencies": { "motion-utils": "14.0.0" } }, "sha512-aU3ApXo1yTpeUi3JU+jbDk2TELjxPE3MbBMUP7nZHlARb6RweJK+ojmLjpuB0YsY6zhbBl1YWGo8LMsI1/Llqw=="],
|
||||
|
||||
"motion-utils": ["motion-utils@12.39.0", "", {}, "sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ=="],
|
||||
"motion-utils": ["motion-utils@14.0.0", "", {}, "sha512-jBsyjVxTTRZNeuvd/v+btVXr90LQkYl4HhRu9T2ARc+PMnvkmjsjRVeAg4Qm10b6TlTw+kykWI8gu/6LuvpLSQ=="],
|
||||
|
||||
"mrmime": ["mrmime@2.0.1", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="],
|
||||
|
||||
@@ -6292,8 +6300,6 @@
|
||||
|
||||
"@opentui/core/marked": ["marked@17.0.1", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-boeBdiS0ghpWcSwoNm/jJBwdpFaMnZWRzjA6SkUMYb40SVaN1x7mmfGKp0jvexGcx+7y2La5zRZsYFZI6Qpypg=="],
|
||||
|
||||
"@opentui/solid/@babel/core": ["@babel/core@7.28.0", "", { "dependencies": { "@ampproject/remapping": "^2.2.0", "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.0", "@babel/helper-compilation-targets": "^7.27.2", "@babel/helper-module-transforms": "^7.27.3", "@babel/helpers": "^7.27.6", "@babel/parser": "^7.28.0", "@babel/template": "^7.27.2", "@babel/traverse": "^7.28.0", "@babel/types": "^7.28.0", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-UlLAnTPrFdNGoFtbSXwcGFQBtQZJCNjaN6hQNP3UPvuNXT1i82N26KL3dZeIpNalWywr9IuQuncaAfUaS1g6sQ=="],
|
||||
|
||||
"@opentui/solid/babel-preset-solid": ["babel-preset-solid@1.9.12", "", { "dependencies": { "babel-plugin-jsx-dom-expressions": "^0.40.6" }, "peerDependencies": { "@babel/core": "^7.0.0", "solid-js": "^1.9.12" }, "optionalPeers": ["solid-js"] }, "sha512-LLqnuKVDlKpyBlMPcH6qEvs/wmS9a+NczppxJ3ryS/c0O5IiSFOIBQi9GzyiGDSbcJpx4Gr87jyFTos1MyEuWg=="],
|
||||
|
||||
"@oslojs/jwt/@oslojs/encoding": ["@oslojs/encoding@0.4.1", "", {}, "sha512-hkjo6MuIK/kQR5CrGNdAPZhS01ZCXuWDRJ187zh6qqF2+yMHZpD9fAYpX8q2bOO6Ryhl3XpCT6kUX76N8hhm4Q=="],
|
||||
@@ -7184,8 +7190,6 @@
|
||||
|
||||
"@opentelemetry/instrumentation/@opentelemetry/api-logs/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="],
|
||||
|
||||
"@opentui/solid/@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
|
||||
|
||||
"@oxc-resolver/binding-wasm32-wasi/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA=="],
|
||||
|
||||
"@pierre/trees/react-dom/scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
|
||||
@@ -7466,6 +7470,10 @@
|
||||
|
||||
"minipass-pipeline/minipass/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="],
|
||||
|
||||
"motion/framer-motion/motion-dom": ["motion-dom@12.43.0", "", { "dependencies": { "motion-utils": "^12.39.0" } }, "sha512-azKON4d9S65PEoFUiQTMTgPheEmzf2QngdRc50AKfJp9Q9mmcBVw22c8eMq9k8kxOFHdL7+WZY7N/5F/lwiDag=="],
|
||||
|
||||
"motion/framer-motion/motion-utils": ["motion-utils@12.39.0", "", {}, "sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ=="],
|
||||
|
||||
"openid-client/lru-cache/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="],
|
||||
|
||||
"p-locate/p-limit/yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="],
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
exact = true
|
||||
# Only install newly resolved package versions published at least 3 days ago.
|
||||
minimumReleaseAge = 259200
|
||||
minimumReleaseAgeExcludes = ["@ai-sdk/amazon-bedrock", "@ai-sdk/anthropic", "@brendonovich/vite-plugin-opencode", "@opencode/sdk", "@opencode-ai/pty", "@opencode-ai/pty-darwin-arm64", "@opencode-ai/pty-darwin-x64", "@opencode-ai/pty-linux-arm64-gnu", "@opencode-ai/pty-linux-arm64-musl", "@opencode-ai/pty-linux-x64-gnu", "@opencode-ai/pty-linux-x64-musl", "@opentui/core", "@opentui/core-darwin-arm64", "@opentui/core-darwin-x64", "@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@opentui/core-win32-arm64", "@opentui/core-win32-x64", "@opentui/keymap", "@opentui/solid", "opentui-spinner", "gitlab-ai-provider", "opencode-gitlab-auth", "@ff-labs/fff-node", "@ff-labs/fff-bun", "@ff-labs/fff-bin-darwin-arm64", "@ff-labs/fff-bin-darwin-x64", "@ff-labs/fff-bin-linux-arm64-gnu", "@ff-labs/fff-bin-linux-arm64-musl", "@ff-labs/fff-bin-linux-x64-gnu", "@ff-labs/fff-bin-linux-x64-musl", "@ff-labs/fff-bin-win32-arm64", "@ff-labs/fff-bin-win32-x64", "@pierre/diffs", "@pierre/theming", "app-builder-lib", "dmg-builder", "electron", "electron-builder", "electron-publish", "blume", "mermaid"]
|
||||
minimumReleaseAgeExcludes = ["@ai-sdk/amazon-bedrock", "@ai-sdk/anthropic", "@brendonovich/vite-plugin-opencode", "@kitlangton/solid-motion", "@opencode/sdk", "@opencode-ai/pty", "@opencode-ai/pty-darwin-arm64", "@opencode-ai/pty-darwin-x64", "@opencode-ai/pty-linux-arm64-gnu", "@opencode-ai/pty-linux-arm64-musl", "@opencode-ai/pty-linux-x64-gnu", "@opencode-ai/pty-linux-x64-musl", "@opentui/core", "@opentui/core-darwin-arm64", "@opentui/core-darwin-x64", "@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@opentui/core-win32-arm64", "@opentui/core-win32-x64", "@opentui/keymap", "@opentui/solid", "@opentunnel/client", "@opentunnel/protocol", "opentui-spinner", "gitlab-ai-provider", "opencode-gitlab-auth", "@ff-labs/fff-node", "@ff-labs/fff-bun", "@ff-labs/fff-bin-darwin-arm64", "@ff-labs/fff-bin-darwin-x64", "@ff-labs/fff-bin-linux-arm64-gnu", "@ff-labs/fff-bin-linux-arm64-musl", "@ff-labs/fff-bin-linux-x64-gnu", "@ff-labs/fff-bin-linux-x64-musl", "@ff-labs/fff-bin-win32-arm64", "@ff-labs/fff-bin-win32-x64", "@pierre/diffs", "@pierre/theming", "app-builder-lib", "dmg-builder", "electron", "electron-builder", "electron-publish", "blume", "mermaid"]
|
||||
|
||||
[test]
|
||||
root = "./do-not-run-tests-from-root"
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"nodeModules": {
|
||||
"x86_64-linux": "sha256-vzF5I8/QHutYM6j0R73ghqBCRntL6/fegzivyDTO9Ro=",
|
||||
"aarch64-linux": "sha256-foy1hI+cewpLJvNqTZCCNTqV4tnQSDK55ZRs87MvnI8=",
|
||||
"aarch64-darwin": "sha256-wl6+Omz25VxLRMsh0rvFZCqBErk0o3mh9cjuUYsYAP4="
|
||||
"x86_64-linux": "sha256-m8XFudp6AwHWDZO7rDXCTkNF0XzgdnWUAg0VCgmGoDQ=",
|
||||
"aarch64-linux": "sha256-CQmS4coITqsMmtgi/g4Xivy/d6sDIklAE8duCUkAazs=",
|
||||
"aarch64-darwin": "sha256-fSeacvDBLUCSKIeGCTgZsmqfo2rohARHvFgYLaNXHi8="
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -53,9 +53,9 @@
|
||||
"@octokit/rest": "22.0.0",
|
||||
"@hono/standard-validator": "0.2.0",
|
||||
"@hono/zod-validator": "0.4.2",
|
||||
"@opentui/core": "0.5.14",
|
||||
"@opentui/keymap": "0.5.14",
|
||||
"@opentui/solid": "0.5.14",
|
||||
"@opentui/core": "0.5.16",
|
||||
"@opentui/keymap": "0.5.16",
|
||||
"@opentui/solid": "0.5.16",
|
||||
"@tanstack/solid-virtual": "3.13.37",
|
||||
"@shikijs/stream": "4.4.3",
|
||||
"@standard-schema/spec": "1.1.0",
|
||||
|
||||
@@ -33,7 +33,7 @@ const Options = Schema.Struct({
|
||||
store: lenient(Schema.Boolean),
|
||||
thinkingLevel: lenient(ThinkingLevel),
|
||||
thinkingSummaries: lenient(knownString<"auto" | "none">()),
|
||||
serviceTier: lenient(knownString<"standard" | "flex" | "priority">()),
|
||||
serviceTier: lenient(knownString<"standard" | "flex" | "priority" | "deferred">()),
|
||||
})
|
||||
export type OptionsInput = typeof Options.Encoded
|
||||
export type ProviderOptionsInput = OptionsInput
|
||||
|
||||
@@ -37,7 +37,8 @@ export const defaultChain = (options: DefaultChainOptions): Effect.Effect<Creden
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const { fromNodeProviderChain } = await import("@aws-sdk/credential-providers")
|
||||
const identity = await fromNodeProviderChain(options.profile === undefined ? {} : { profile: options.profile })()
|
||||
// ignoreCache re-reads shared config and SSO token files, so `aws sso login` takes effect without a restart.
|
||||
const identity = await fromNodeProviderChain({ ignoreCache: true, profile: options.profile })()
|
||||
return {
|
||||
region: options.region,
|
||||
accessKeyId: identity.accessKeyId,
|
||||
|
||||
@@ -9,7 +9,8 @@ export type OpenAITextVerbosity = OpenResponsesOptions.TextVerbosity
|
||||
// in lockstep with `openai-node/src/resources/responses/responses.ts`.
|
||||
export const OpenAIResponseIncludables = OpenResponsesOptions.ResponseIncludables
|
||||
export type OpenAIResponseIncludable = OpenResponsesOptions.ResponseIncludable
|
||||
export const OpenAIServiceTiers = [...OpenResponsesOptions.ServiceTiers, "scale"] as const
|
||||
// Mirrors OpenAI's `ServiceTier` union from the official SDK.
|
||||
export const OpenAIServiceTiers = [...OpenResponsesOptions.ServiceTiers, "scale", "fast", "ultrafast"] as const
|
||||
export type OpenAIServiceTier = (typeof OpenAIServiceTiers)[number] | (string & {})
|
||||
|
||||
export const OpenAIReasoningEffort = OpenResponsesOptions.ReasoningEffort
|
||||
|
||||
@@ -9,6 +9,7 @@ LLM.request({ model: selected, prompt: "Hello", providerOptions: { reasoningEffo
|
||||
LLM.request({ model: selected, prompt: "Hello", providerOptions: { textVerbosity: "low" } })
|
||||
LLM.request({ model: selected, prompt: "Hello", providerOptions: { textVerbosity: "verbose" } })
|
||||
LLM.request({ model: selected, prompt: "Hello", providerOptions: { serviceTier: "scale" } })
|
||||
LLM.request({ model: selected, prompt: "Hello", providerOptions: { serviceTier: "ultrafast" } })
|
||||
LLM.request({ model: selected, prompt: "Hello", providerOptions: { serviceTier: "future-tier" } })
|
||||
LLM.request({ model: chat, prompt: "Hello", providerOptions: { reasoningEffort: "max" } })
|
||||
LLM.request({ model: chat, prompt: "Hello", providerOptions: { reasoningEffort: "experimental" } })
|
||||
|
||||
@@ -325,11 +325,13 @@ describe("OpenAI Responses route", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("passes through provider-defined service tiers", () =>
|
||||
it.effect("passes through provider-defined and future service tiers", () =>
|
||||
Effect.gen(function* () {
|
||||
const prepared = yield* compileRequest(LLMRequest.update(request, { providerOptions: { serviceTier: "scale" } }))
|
||||
for (const serviceTier of ["scale", "ultrafast", "future-tier"]) {
|
||||
const prepared = yield* compileRequest(LLMRequest.update(request, { providerOptions: { serviceTier } }))
|
||||
|
||||
expect(prepared.body.service_tier).toBe("scale")
|
||||
expect(prepared.body.service_tier).toBe(serviceTier)
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@@ -213,7 +213,18 @@ test("keeps a narrow session composer contained when invoking a built-in", async
|
||||
await page.getByRole("menuitem", { name: "Commands" }).click()
|
||||
await page.locator('[data-suggestion-id="model.choose"]').click()
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Select model", exact: true })
|
||||
const search = dialog.getByRole("searchbox", { name: "Search models", exact: true })
|
||||
await expect(search).toBeFocused()
|
||||
await expect(editor).toHaveText("keep me")
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(dialog).toBeHidden()
|
||||
|
||||
await editor.fill("/model")
|
||||
await expect(page.locator('[data-suggestion-id="model.choose"]')).toHaveAttribute("data-active", "")
|
||||
await editor.press("Enter")
|
||||
await expect(search).toBeFocused()
|
||||
await expect(editor).toBeEmpty()
|
||||
})
|
||||
|
||||
test("lists slash commands in their built-in order", async ({ page }) => {
|
||||
|
||||
@@ -1012,6 +1012,99 @@ test.describe("background shortcut", () => {
|
||||
await expect(backgroundCard).toContainText("Background task (background)")
|
||||
})
|
||||
|
||||
for (const fixture of [
|
||||
{ name: "from far below", before: 40, searches: 40, after: 80 },
|
||||
// The collapsed timeline fits the viewport, so it only becomes scrollable once the group opens.
|
||||
{ name: "that opens the last row", before: 0, searches: 40, after: 0 },
|
||||
// Reaching the shell lands on the end of the timeline, which would otherwise follow new content again.
|
||||
{ name: "at the end of the timeline", before: 40, searches: 0, after: 0 },
|
||||
]) {
|
||||
test(`holds a revealed shell ${fixture.name} just under its stuck group header`, async ({ page }) => {
|
||||
const timeline = await setupTimeline(page, {
|
||||
settings: { timelineDetail: detailed },
|
||||
sessionStatus: { [sessionID]: { type: "busy" } },
|
||||
messages: [
|
||||
userMessage(),
|
||||
assistantMessage(
|
||||
[
|
||||
...(fixture.before ? [textPart("prt_earlier", notes("Earlier", fixture.before))] : []),
|
||||
...searches(0, 42 - fixture.searches),
|
||||
toolPart(
|
||||
"prt_far_shell",
|
||||
"shell",
|
||||
"completed",
|
||||
{ command: "sleep 120" },
|
||||
{ output: "working", metadata: { shellID: "shell_far", status: "running" } },
|
||||
),
|
||||
// The open group outgrows the viewport, so aligning the group instead of the shell misses it.
|
||||
...searches(42 - fixture.searches, fixture.searches),
|
||||
...(fixture.after ? [textPart("prt_follow_up", notes("Follow-up", fixture.after))] : []),
|
||||
],
|
||||
{ completed: false },
|
||||
),
|
||||
],
|
||||
})
|
||||
|
||||
await timeline.transport.send({
|
||||
id: "evt_far_shell_created",
|
||||
created: 3,
|
||||
type: "shell.created",
|
||||
location: { directory },
|
||||
data: {
|
||||
info: {
|
||||
id: "shell_far",
|
||||
status: "running",
|
||||
command: "sleep 120",
|
||||
cwd: directory,
|
||||
shell: "bash",
|
||||
file: "/tmp/far.out",
|
||||
metadata: { sessionID },
|
||||
time: { started: 2 },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const group = page
|
||||
.locator('[data-component="collapsed-tool-group"]')
|
||||
.locator(':scope > [data-component="collapsible"] > [data-slot="collapsible-trigger"]')
|
||||
|
||||
const shellTrigger = page.locator('[data-timeline-part-id="prt_far_shell"] [data-slot="collapsible-trigger"]')
|
||||
|
||||
const aligned = () =>
|
||||
expect
|
||||
.poll(async () => {
|
||||
const [header, shell] = await Promise.all([group.boundingBox(), shellTrigger.boundingBox()])
|
||||
|
||||
return header && shell ? Math.round(shell.y - (header.y + header.height)) : undefined
|
||||
})
|
||||
.toBe(0)
|
||||
|
||||
await expect(
|
||||
fixture.after ? page.getByText(`Follow-up note ${fixture.after}.`, { exact: true }) : group,
|
||||
).toBeInViewport()
|
||||
await expect(shellTrigger).toHaveCount(0)
|
||||
await page.getByRole("button", { name: "1 running", exact: true }).click()
|
||||
await page
|
||||
.getByRole("menu", { name: "1 running", exact: true })
|
||||
.getByRole("menuitem", { name: /sleep 120/ })
|
||||
.click()
|
||||
|
||||
await expect(group).toHaveAttribute("aria-expanded", "true")
|
||||
await expect(shellTrigger).toHaveAttribute("aria-expanded", "true")
|
||||
await expect(shellTrigger).toBeInViewport()
|
||||
|
||||
// A shell at the very end cannot rise under the header until more content arrives below it.
|
||||
if (fixture.searches) await aligned()
|
||||
// Nothing covers the row, so it takes the next click.
|
||||
await shellTrigger.click({ trial: true })
|
||||
|
||||
// The agent keeps writing below the shell; the shell stays where it was revealed.
|
||||
await timeline.send(partUpdated(textPart("prt_late", notes("Late", 30))))
|
||||
await expect(page.getByText("Late note 30.", { exact: true })).toBeAttached()
|
||||
await aligned()
|
||||
})
|
||||
}
|
||||
|
||||
test("hides the running switcher when viewing the only running subagent", async ({ page }) => {
|
||||
const childID = "ses_only_running_child"
|
||||
|
||||
@@ -1735,6 +1828,16 @@ function pauseExitAnimations(locator: Locator) {
|
||||
})
|
||||
}
|
||||
|
||||
function notes(label: string, count: number) {
|
||||
return Array.from({ length: count }, (_, index) => `${label} note ${index + 1}.`).join("\n\n")
|
||||
}
|
||||
|
||||
function searches(from: number, count: number) {
|
||||
return Array.from({ length: count }, (_, index) =>
|
||||
toolPart(`prt_search_${from + index}`, "grep", "completed", { pattern: `needle_${from + index}` }),
|
||||
)
|
||||
}
|
||||
|
||||
function runningSubagent(): SessionMessageAssistant {
|
||||
return {
|
||||
...completed,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCommand, type CommandOption } from "@/shell/commands/command"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { DialogSelectModel } from "@/providers/models/select-dialog"
|
||||
import { useLocal, type ModelSelection } from "@/providers/models/selection"
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { getCursorPosition, setCursorPosition } from "./editor/dom"
|
||||
@@ -33,7 +34,7 @@ export const useComposerCommands = (input: { model?: ModelSelection } = {}) => {
|
||||
void dialog.show(() => <DialogConnectProvider directory={workspace().directory} />)
|
||||
}
|
||||
|
||||
const chooseModel = async () => {
|
||||
const chooseModel = () => {
|
||||
const owner = sessionOwnership.capture()
|
||||
const editor = document.querySelector<HTMLElement>('[data-component="composer-editor"]')
|
||||
const selection = window.getSelection()
|
||||
@@ -54,7 +55,6 @@ export const useComposerCommands = (input: { model?: ModelSelection } = {}) => {
|
||||
})
|
||||
}
|
||||
|
||||
const { DialogSelectModel } = await import("@/providers/models/select-dialog")
|
||||
owner.run(() => {
|
||||
void dialog.show(() => <DialogSelectModel model={model} />, restoreComposer)
|
||||
})
|
||||
|
||||
@@ -204,7 +204,7 @@ export function createComposerEditor(input: {
|
||||
const action = event.type === "popover.select" ? input.onSuggestionSelect?.(event.item) : undefined
|
||||
|
||||
if (event.type === "popover.select") {
|
||||
if (!action || state.popover.type !== "command-menu") result.commands.forEach(execute)
|
||||
if (!action) result.commands.forEach(execute)
|
||||
|
||||
if (action && event.item.kind === "command" && state.popover.type !== "command-menu") {
|
||||
draft.setPrompt(draft.state.prompt.filter(isAttachment), 0)
|
||||
|
||||
@@ -7,14 +7,23 @@ import type {
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { usePlatform } from "@/runtime/platform/platform"
|
||||
import { useServerSDK } from "@/runtime/server/client"
|
||||
import { formatServerError } from "@/runtime/server/errors"
|
||||
import { useData } from "@/runtime/server/current"
|
||||
import { createEffect, createMemo, on, onCleanup } from "solid-js"
|
||||
import { createStore, produce } from "solid-js/store"
|
||||
|
||||
export type ProviderConnectMethod = Extract<IntegrationMethod, { type: "key" | "oauth" }>
|
||||
export type ProviderConnectMethod = Extract<IntegrationMethod, { type: "key" | "oauth" | "external" }>
|
||||
|
||||
type Authorization = IntegrationOauthConnectOutput["data"]
|
||||
|
||||
type Polling = {
|
||||
generation: number
|
||||
timer?: ReturnType<typeof setTimeout>
|
||||
disposed: boolean
|
||||
// An attempt the server still considers open; cancelled when the dialog goes away.
|
||||
attempt?: Authorization
|
||||
}
|
||||
|
||||
// OpenCode Go and OpenCode Zen both bill through the OpenCode Console, so the
|
||||
// Console sign-in is the connection method for both providers.
|
||||
export const CONSOLE_INTEGRATION = "opencode"
|
||||
@@ -35,7 +44,7 @@ export function providerFormDefaults(fields: ProviderConnectMethod["form"]) {
|
||||
if (actual === undefined) return false
|
||||
|
||||
const equal = Array.isArray(actual)
|
||||
? typeof condition.value === "string" && actual.includes(condition.value)
|
||||
? actual.some((item) => item === condition.value)
|
||||
: actual === condition.value
|
||||
|
||||
return condition.op === "eq" ? equal : !equal
|
||||
@@ -43,7 +52,7 @@ export function providerFormDefaults(fields: ProviderConnectMethod["form"]) {
|
||||
|
||||
if (!active) return answer
|
||||
|
||||
return { ...answer, [field.key]: field.default }
|
||||
return Object.assign(answer, { [field.key]: field.default })
|
||||
}, {})
|
||||
}
|
||||
|
||||
@@ -74,9 +83,8 @@ export function createProviderConnectionController(options: {
|
||||
|
||||
// Not createResource: the dialog is owned by whichever page opened it, so reading a pending
|
||||
// resource here would suspend that page's <Suspense> and blank the screen behind the dialog.
|
||||
const [integration, setIntegration] = createStore({
|
||||
const [integration, setIntegration] = createStore<{ loading: boolean; latest?: IntegrationInfo }>({
|
||||
loading: true,
|
||||
latest: undefined as IntegrationInfo | undefined,
|
||||
})
|
||||
|
||||
createEffect(
|
||||
@@ -100,7 +108,8 @@ export function createProviderConnectionController(options: {
|
||||
|
||||
const methods = createMemo<ProviderConnectMethod[]>(() => {
|
||||
const values = integration.latest?.methods.filter(
|
||||
(method): method is ProviderConnectMethod => method.type === "key" || method.type === "oauth",
|
||||
(method): method is ProviderConnectMethod =>
|
||||
method.type === "key" || method.type === "oauth" || method.type === "external",
|
||||
)
|
||||
|
||||
if (values?.length) return [...values]
|
||||
@@ -108,14 +117,19 @@ export function createProviderConnectionController(options: {
|
||||
return [{ type: "key", label: language.t("provider.connect.method.apiKey") }]
|
||||
})
|
||||
|
||||
const [store, setStore] = createStore({
|
||||
methodIndex: undefined as number | undefined,
|
||||
authorization: undefined as Authorization | undefined,
|
||||
formAnswer: undefined as FormAnswer | undefined,
|
||||
const [store, setStore] = createStore<{
|
||||
methodIndex?: number
|
||||
authorization?: Authorization
|
||||
formAnswer?: FormAnswer
|
||||
// Nothing is in flight until a method is selected; `busy()` reads this, so a truthy initial
|
||||
// value would keep multi-method providers on the spinner instead of the method list.
|
||||
state: undefined as "pending" | "waiting" | "refreshing" | "ready" | "error" | "form" | undefined,
|
||||
error: undefined as string | undefined,
|
||||
state?: "pending" | "waiting" | "refreshing" | "ready" | "error" | "form"
|
||||
error?: string
|
||||
auto: boolean
|
||||
connected: boolean
|
||||
browserFailed: boolean
|
||||
statusFailed: boolean
|
||||
}>({
|
||||
auto: false,
|
||||
// The credential is stored; a retry only needs to reload the catalogs.
|
||||
connected: false,
|
||||
@@ -124,12 +138,9 @@ export function createProviderConnectionController(options: {
|
||||
statusFailed: false,
|
||||
})
|
||||
|
||||
const polling = {
|
||||
const polling: Polling = {
|
||||
generation: 0,
|
||||
timer: undefined as ReturnType<typeof setTimeout> | undefined,
|
||||
disposed: false,
|
||||
// An attempt the server still considers open; cancelled when the dialog goes away.
|
||||
attempt: undefined as Authorization | undefined,
|
||||
}
|
||||
|
||||
const currentMethod = createMemo(() =>
|
||||
@@ -206,8 +217,6 @@ export function createProviderConnectionController(options: {
|
||||
)
|
||||
}
|
||||
|
||||
const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error))
|
||||
|
||||
const cancelAttempt = () => {
|
||||
const attempt = polling.attempt
|
||||
polling.attempt = undefined
|
||||
@@ -276,7 +285,9 @@ export function createProviderConnectionController(options: {
|
||||
setStore("statusFailed", true)
|
||||
dispatch({
|
||||
type: "auth.error",
|
||||
error: isConsole() ? language.t("provider.connect.console.statusFailed") : errorMessage(result.error),
|
||||
error: isConsole()
|
||||
? language.t("provider.connect.console.statusFailed")
|
||||
: formatServerError(result.error, language.t),
|
||||
})
|
||||
|
||||
return
|
||||
@@ -358,8 +369,6 @@ export function createProviderConnectionController(options: {
|
||||
return
|
||||
}
|
||||
|
||||
if (selected.type !== "oauth") return
|
||||
|
||||
if (selected.form?.some((field) => field.type !== "string")) {
|
||||
dispatch({ type: "auth.error", error: language.t("provider.connect.error.unsupportedFields") })
|
||||
|
||||
@@ -368,11 +377,35 @@ export function createProviderConnectionController(options: {
|
||||
|
||||
dispatch({ type: "auth.pending" })
|
||||
|
||||
if (selected.type === "external") {
|
||||
const saved = await serverSDK.api.integration.connect
|
||||
.external({
|
||||
integrationID: options.provider(),
|
||||
methodID: selected.id,
|
||||
answer: Object.keys(merged).length ? merged : undefined,
|
||||
location: location(),
|
||||
})
|
||||
.then(() => ({ ok: true as const }))
|
||||
.catch((error) => ({ ok: false as const, error }))
|
||||
|
||||
if (polling.disposed || generation !== polling.generation) return
|
||||
|
||||
if (!saved.ok) {
|
||||
dispatch({ type: "auth.error", error: formatServerError(saved.error, language.t) })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
await finish()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const result = await serverSDK.api.integration.oauth
|
||||
.connect({
|
||||
integrationID: options.provider(),
|
||||
methodID: selected.id,
|
||||
...(Object.keys(merged).length ? { answer: merged } : {}),
|
||||
answer: Object.keys(merged).length ? merged : undefined,
|
||||
location: location(),
|
||||
})
|
||||
.then((response) => {
|
||||
@@ -404,7 +437,9 @@ export function createProviderConnectionController(options: {
|
||||
if (!result.ok) {
|
||||
dispatch({
|
||||
type: "auth.error",
|
||||
error: isConsole() ? language.t("provider.connect.console.startFailed") : errorMessage(result.error),
|
||||
error: isConsole()
|
||||
? language.t("provider.connect.console.startFailed")
|
||||
: formatServerError(result.error, language.t),
|
||||
})
|
||||
|
||||
return
|
||||
@@ -448,7 +483,7 @@ export function createProviderConnectionController(options: {
|
||||
integrationID: options.keyProvider?.() ?? options.provider(),
|
||||
location: location(),
|
||||
key,
|
||||
...(store.formAnswer ? { answer: store.formAnswer } : {}),
|
||||
answer: store.formAnswer,
|
||||
})
|
||||
await finish()
|
||||
}
|
||||
@@ -468,7 +503,8 @@ export function createProviderConnectionController(options: {
|
||||
.then(() => ({ ok: true as const }))
|
||||
.catch((error) => ({ ok: false as const, error }))
|
||||
|
||||
if (!result.ok) return errorMessage(result.error) || language.t("provider.connect.oauth.code.invalid")
|
||||
if (!result.ok)
|
||||
return formatServerError(result.error, language.t, language.t("provider.connect.oauth.code.invalid"))
|
||||
await finish()
|
||||
|
||||
return undefined
|
||||
@@ -496,11 +532,13 @@ export function createProviderConnectionController(options: {
|
||||
authorization: () => store.authorization,
|
||||
browserFailed: () => store.browserFailed,
|
||||
// True while nothing useful can be shown yet: the integration is loading, a method is
|
||||
// about to be picked automatically, or the authorization request is in flight.
|
||||
// about to be picked automatically, the authorization request is in flight, or an external
|
||||
// method, which has no view of its own, is refreshing the catalogs after saving.
|
||||
busy: () =>
|
||||
integration.loading ||
|
||||
(store.methodIndex === undefined && !store.auto && autoIndex() !== undefined) ||
|
||||
store.state === "pending",
|
||||
store.state === "pending" ||
|
||||
(store.state === "refreshing" && currentMethod()?.type === "external"),
|
||||
auth: {
|
||||
state: () => store.state,
|
||||
error: () => store.error,
|
||||
|
||||
@@ -110,7 +110,14 @@ export function createTimelineVirtualizer(input: Input) {
|
||||
{ defer: true },
|
||||
),
|
||||
)
|
||||
const [rendering, setRendering] = createStore({ initialTail: coldBottomMount, scrollAdjustment: 0 })
|
||||
|
||||
const [rendering, setRendering] = createStore<{
|
||||
initialTail: boolean
|
||||
scrollAdjustment: number
|
||||
/** A revealed tool whose top edge stays put until the user scrolls. */
|
||||
anchor?: { key: string; partID: string }
|
||||
}>({ initialTail: coldBottomMount, scrollAdjustment: 0 })
|
||||
|
||||
const rows = input.projection.rows
|
||||
const rowByKey = input.projection.rowByKey
|
||||
|
||||
@@ -137,6 +144,7 @@ export function createTimelineVirtualizer(input: Input) {
|
||||
const id = input.projection.activeMessageID()
|
||||
const active = id ? (input.projection.messageLastRowIndex().get(id) ?? -1) : -1
|
||||
const initialTail = rendering.initialTail && input.pinned()
|
||||
const anchored = rendering.anchor ? rowKeys().indexOf(rendering.anchor.key) : -1
|
||||
|
||||
return (range: Range) => {
|
||||
// Batch a bounded cheap suffix, but stop before unknown/large content.
|
||||
@@ -164,7 +172,7 @@ export function createTimelineVirtualizer(input: Input) {
|
||||
: defaultRangeExtractor({ ...range, overscan: 2 })
|
||||
|
||||
return filterVirtualIndexes(
|
||||
[...new Set([...indexes, ...(active < 0 ? [] : [active])])].sort((a, b) => a - b),
|
||||
[...new Set([...indexes, ...[active, anchored].filter((index) => index >= 0)])].sort((a, b) => a - b),
|
||||
range.count,
|
||||
)
|
||||
}
|
||||
@@ -336,6 +344,7 @@ export function createTimelineVirtualizer(input: Input) {
|
||||
})
|
||||
})
|
||||
batchingColdSizes = false
|
||||
pinAnchor()
|
||||
|
||||
if (coldPending) pinColdBottom()
|
||||
settleColdBottom()
|
||||
@@ -403,19 +412,60 @@ export function createTimelineVirtualizer(input: Input) {
|
||||
|
||||
const key = found.group.key
|
||||
|
||||
setToolOpen(
|
||||
found.group.type === "context"
|
||||
? { [`context:${key}`]: true, [`${key}:tool:${found.partID}`]: true }
|
||||
: { [key]: true },
|
||||
)
|
||||
input.onUnpin()
|
||||
prepareNavigation()
|
||||
virtualizer.scrollToIndex(found.index, { align: "center" })
|
||||
// Opening the group and anchoring its row render the tool synchronously, wherever the row is.
|
||||
batch(() => {
|
||||
setToolOpen(
|
||||
found.group.type === "context"
|
||||
? { [`context:${key}`]: true, [`${key}:tool:${found.partID}`]: true }
|
||||
: { [key]: true },
|
||||
)
|
||||
setRendering("anchor", { key: TimelineRow.key(rows()[found.index]!), partID: found.partID })
|
||||
})
|
||||
// Until its ResizeObserver delivers, the opened row keeps its collapsed size, so the timeline may not scroll yet
|
||||
// (and cannot unpin) or ends above the tool. Commit the real size first.
|
||||
const opened = virtualContent?.querySelector<HTMLElement>(`[data-index="${found.index}"]`)
|
||||
|
||||
if (opened) resizeItem(found.index, opened.offsetHeight)
|
||||
input.onUnpin()
|
||||
pinAnchor()
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Puts the anchored tool's top edge at its scroll margin, just below the headers that stick above it. Its own
|
||||
// growth extends downward, so only size changes at or above its row can move it; each of those calls this again.
|
||||
function pinAnchor() {
|
||||
const anchor = rendering.anchor
|
||||
const root = listRoot()
|
||||
|
||||
if (!anchor || !root) return
|
||||
const element = virtualContent?.querySelector<HTMLElement>(`[data-timeline-part-id="${CSS.escape(anchor.partID)}"]`)
|
||||
|
||||
// Following the end is a different position to hold.
|
||||
if (!element || !active() || input.pinned()) return releaseAnchor()
|
||||
|
||||
const offset = Math.min(
|
||||
root.scrollHeight - root.clientHeight,
|
||||
Math.max(
|
||||
0,
|
||||
root.scrollTop +
|
||||
element.getBoundingClientRect().top -
|
||||
root.getBoundingClientRect().top -
|
||||
parseFloat(getComputedStyle(element).scrollMarginTop),
|
||||
),
|
||||
)
|
||||
|
||||
if (Math.abs(offset - root.scrollTop) > 1) virtualizer.scrollToOffset(offset)
|
||||
}
|
||||
|
||||
function releaseAnchor() {
|
||||
if (rendering.anchor) setRendering("anchor", undefined)
|
||||
}
|
||||
|
||||
function prepareNavigation() {
|
||||
releaseAnchor()
|
||||
|
||||
if (touchStart === undefined) touchScrolling = false
|
||||
flushTouchAdjustment()
|
||||
}
|
||||
@@ -600,6 +650,7 @@ export function createTimelineVirtualizer(input: Input) {
|
||||
// Upward input is the one intent geometry cannot recover: nudging up while still a pixel from
|
||||
// the end must stop following, even though the resulting position still looks like the end.
|
||||
const handleListWheel = (event: WheelEvent & { currentTarget: HTMLDivElement }) => {
|
||||
releaseAnchor()
|
||||
input.onUserScroll(event.target)
|
||||
|
||||
if (event.deltaY < 0) input.onUnpin()
|
||||
@@ -607,6 +658,7 @@ export function createTimelineVirtualizer(input: Input) {
|
||||
|
||||
const handleListTouchStart = (event: TouchEvent) => {
|
||||
clearTouchTarget()
|
||||
releaseAnchor()
|
||||
input.onUserScroll(event.target)
|
||||
touchScrolling = true
|
||||
touchStart = event.touches[0]?.clientY
|
||||
@@ -663,6 +715,7 @@ export function createTimelineVirtualizer(input: Input) {
|
||||
// Drag-selecting past the edge and dragging the scrollbar both scroll without a wheel or key,
|
||||
// so a held pointer is what separates those from the virtualizer's own measurement adjustments.
|
||||
const handleListPointerDown = (event: PointerEvent & { currentTarget: HTMLDivElement }) => {
|
||||
releaseAnchor()
|
||||
input.onUserScroll(event.target)
|
||||
pointerHeld = true
|
||||
}
|
||||
@@ -688,6 +741,7 @@ export function createTimelineVirtualizer(input: Input) {
|
||||
if (!isScrollKeyTarget(event.target, key)) return
|
||||
|
||||
if (scrollKeyOwner(event.currentTarget, event.target, key) !== event.currentTarget) return
|
||||
releaseAnchor()
|
||||
input.onUserScroll(event.currentTarget)
|
||||
|
||||
if (upwardKeys.has(key)) input.onUnpin()
|
||||
@@ -706,7 +760,8 @@ export function createTimelineVirtualizer(input: Input) {
|
||||
const atEnd = maxScroll - scrollTop <= endEpsilon
|
||||
const arrived = scrollTop > previousTop + endEpsilon || maxScroll < previousMaxScroll
|
||||
|
||||
if (maxScroll <= 1 || (atEnd && arrived)) input.onPin()
|
||||
// An anchor holds its tool even when reaching it lands at the end; only the user's own scroll lets it go.
|
||||
if (maxScroll <= 1 || (atEnd && arrived && !rendering.anchor)) input.onPin()
|
||||
else if ((pointerHeld || touchScrolling) && scrollTop < previousTop - endEpsilon) input.onUnpin()
|
||||
settleColdBottom()
|
||||
input.onScheduleScrollState(root)
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
"@opencode/util": "workspace:*",
|
||||
"@opentui/core": "catalog:",
|
||||
"@opentui/solid": "catalog:",
|
||||
"@opentunnel/client": "0.2.0",
|
||||
"@parcel/watcher": "2.5.1",
|
||||
"@silvia-odwyer/photon-node": "0.3.4",
|
||||
"diff": "catalog:",
|
||||
|
||||
@@ -7,6 +7,7 @@ import { Script } from "@opencode/script"
|
||||
import { createSolidTransformPlugin } from "@opentui/solid/bun-plugin"
|
||||
import type { BunPlugin } from "bun"
|
||||
import pkg from "../package.json"
|
||||
import { discoverPluginRuntimeSpecifiers, pluginRuntimeLoaderCode } from "@opencode/plugin/runtime-modules"
|
||||
import { buildAppArchive } from "./app-assets"
|
||||
import { verifyArtifact, verifySimulationGraph } from "./verify-artifact"
|
||||
import { resolveOpencodePty } from "./opencode-pty"
|
||||
@@ -82,6 +83,30 @@ export default () => readFileSync(archive)`,
|
||||
}))
|
||||
},
|
||||
}
|
||||
const pluginRuntimeEntries = discoverPluginRuntimeSpecifiers()
|
||||
const pluginRuntimeModulesSource = [
|
||||
"export const resolveHostPackageRoots = () => []",
|
||||
"const modules = {",
|
||||
...[...pluginRuntimeEntries.keys()].map(
|
||||
(specifier) => ` ${JSON.stringify(specifier)}: ${pluginRuntimeLoaderCode(specifier, pluginRuntimeEntries)},`,
|
||||
),
|
||||
"}",
|
||||
"export const loadRuntimeModules = () => modules",
|
||||
].join("\n")
|
||||
const pluginRuntimePlugin: BunPlugin = {
|
||||
name: "opencode-plugin-runtime",
|
||||
setup(build) {
|
||||
build.onLoad({ filter: /plugin[/\\]src[/\\]runtime-modules\.ts$/ }, () => ({
|
||||
contents: pluginRuntimeModulesSource,
|
||||
loader: "ts",
|
||||
}))
|
||||
build.onLoad({ filter: /[/\\]internal[/\\]httpApi(?:Scalar|Swagger)\.js$/ }, () => ({
|
||||
contents:
|
||||
'export const css = ""; export const javascript = \'document.body.textContent = "Scalar/Swagger UI assets are not bundled in OpenCode"\'',
|
||||
loader: "js",
|
||||
}))
|
||||
},
|
||||
}
|
||||
|
||||
for (const item of targets) {
|
||||
const opencodePty = await resolveOpencodePty({
|
||||
@@ -128,7 +153,14 @@ export default { path: file, version: ${JSON.stringify(opencodePty.version)}, sh
|
||||
const result = await Bun.build({
|
||||
entrypoints: ["./src/index.ts"],
|
||||
tsconfig: "./tsconfig.json",
|
||||
plugins: [appAssetsPlugin, solidPlugin, parcelWatcherPlugin, opencodePtyPlugin, simulationGraphPlugin],
|
||||
plugins: [
|
||||
appAssetsPlugin,
|
||||
solidPlugin,
|
||||
parcelWatcherPlugin,
|
||||
opencodePtyPlugin,
|
||||
pluginRuntimePlugin,
|
||||
simulationGraphPlugin,
|
||||
],
|
||||
external: ["node-gyp"],
|
||||
format: "esm",
|
||||
minify: true,
|
||||
|
||||
@@ -116,6 +116,10 @@ function copyBinary(source) {
|
||||
|
||||
function resolveBinary(name) {
|
||||
const packagePath = require.resolve(`${name}/package.json`)
|
||||
// Package managers keep an older platform package when the matching version is not yet on the registry,
|
||||
// which would silently install the previous release under the new launcher.
|
||||
const version = JSON.parse(fs.readFileSync(packagePath, "utf8")).version
|
||||
if (version !== dependencies[name]) throw new Error(`${name} is ${version}, expected ${dependencies[name]}`)
|
||||
return path.join(path.dirname(packagePath), "bin", sourceBinary)
|
||||
}
|
||||
|
||||
|
||||
@@ -73,18 +73,8 @@ const Root = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME
|
||||
},
|
||||
}),
|
||||
Spec.make("uninstall", {
|
||||
description: "Uninstall OpenCode and remove all related files",
|
||||
description: "Uninstall OpenCode, keeping session data, configuration, and state",
|
||||
params: {
|
||||
keepConfig: Flag.boolean("keep-config").pipe(
|
||||
Flag.withAlias("c"),
|
||||
Flag.withDescription("Keep configuration files"),
|
||||
Flag.withDefault(false),
|
||||
),
|
||||
keepData: Flag.boolean("keep-data").pipe(
|
||||
Flag.withAlias("d"),
|
||||
Flag.withDescription("Keep session data and snapshots"),
|
||||
Flag.withDefault(false),
|
||||
),
|
||||
dryRun: Flag.boolean("dry-run").pipe(
|
||||
Flag.withDescription("Show what would be removed without removing"),
|
||||
Flag.withDefault(false),
|
||||
@@ -540,6 +530,10 @@ const Root = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME
|
||||
),
|
||||
Flag.optional,
|
||||
),
|
||||
remote: Flag.boolean("remote").pipe(
|
||||
Flag.withDescription("Pair through the OpenTunnel remote address, enabling remote access if needed"),
|
||||
Flag.withDefault(false),
|
||||
),
|
||||
},
|
||||
}),
|
||||
Spec.make("serve", {
|
||||
|
||||
@@ -127,9 +127,29 @@ const authenticate = Effect.fn("cli.auth.login.authenticate")(function* (
|
||||
) {
|
||||
if (method.type === "key") return yield* keyLogin(client, integration, method, answer)
|
||||
if (method.type === "command") return yield* commandLogin(client, integration, method)
|
||||
if (method.type === "external") return yield* externalLogin(client, integration, method, answer)
|
||||
return yield* oauthLogin(client, integration, method, answer)
|
||||
})
|
||||
|
||||
const externalLogin = Effect.fn("cli.auth.login.external")(function* (
|
||||
client: OpenCodeClient,
|
||||
integration: IntegrationInfo,
|
||||
method: Extract<ConnectMethod, { type: "external" }>,
|
||||
answer?: FormAnswer,
|
||||
) {
|
||||
const progress = spinner()
|
||||
progress.start("Saving credential...")
|
||||
yield* request((signal) =>
|
||||
client.integration.connect.external(
|
||||
{ integrationID: integration.id, methodID: method.id, answer, location },
|
||||
{ signal },
|
||||
),
|
||||
).pipe(
|
||||
Effect.tap(() => Effect.sync(() => progress.stop(`Connected to ${integration.name}`))),
|
||||
Effect.tapCause(() => Effect.sync(() => progress.stop("Authentication failed", 1))),
|
||||
)
|
||||
})
|
||||
|
||||
const keyLogin = Effect.fn("cli.auth.login.key")(function* (
|
||||
client: OpenCodeClient,
|
||||
integration: IntegrationInfo,
|
||||
|
||||
@@ -1,24 +1,28 @@
|
||||
import { EOL } from "os"
|
||||
import { Effect, Option } from "effect"
|
||||
import { Effect, Option, Schedule } from "effect"
|
||||
import { Service } from "@opencode/client/effect/service"
|
||||
import { OpenCode } from "@opencode/client/promise"
|
||||
import { renderUnicodeCompact } from "uqr"
|
||||
import { Commands } from "../commands"
|
||||
import { Runtime } from "../../framework/runtime"
|
||||
import { RemoteTunnel } from "../../services/remote-tunnel"
|
||||
import { ServiceConfig } from "../../services/service-config"
|
||||
|
||||
export default Runtime.handler(
|
||||
Commands.commands.pair,
|
||||
Effect.fn("cli.pair")(function* (input: Runtime.Input<typeof Commands.commands.pair>) {
|
||||
if ((yield* ServiceConfig.read()).disabled === true)
|
||||
const config = yield* ServiceConfig.read()
|
||||
if (config.disabled === true)
|
||||
return yield* Effect.fail(
|
||||
new Error("Pairing requires the background service; run `opencode service unset disabled` first"),
|
||||
)
|
||||
if (input.remote && Option.isSome(input.url))
|
||||
return yield* Effect.fail(new Error("--remote cannot be combined with --url"))
|
||||
// Changing the setting restarts the service, and the ensure below starts it again with the tunnel.
|
||||
if (input.remote && config.remote !== true) yield* ServiceConfig.set("remote", "true")
|
||||
const endpoint = yield* Service.ensure(yield* ServiceConfig.options())
|
||||
const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
|
||||
const urls = Option.isSome(input.url)
|
||||
? [input.url.value]
|
||||
: (yield* Effect.tryPromise(() => client.server.info())).urls
|
||||
const urls = yield* pairingURLs(client, input)
|
||||
const pairing = yield* Effect.tryPromise(() => client.server.pair())
|
||||
const links = urls.map((url) => new URL(`/auth/connect/${pairing.code}`, url).href)
|
||||
// Loopback URLs are useless to the scanning device, so the QR code only carries reachable addresses.
|
||||
@@ -45,7 +49,7 @@ export default Runtime.handler(
|
||||
].join(EOL) + EOL,
|
||||
)
|
||||
|
||||
if (Option.isSome(input.url)) return
|
||||
if (input.remote || Option.isSome(input.url)) return
|
||||
const url = new URL(endpoint.url)
|
||||
if (!["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) return
|
||||
process.stderr.write(
|
||||
@@ -61,6 +65,34 @@ export default Runtime.handler(
|
||||
}),
|
||||
)
|
||||
|
||||
const pairingURLs = Effect.fnUntraced(function* (
|
||||
client: ReturnType<typeof OpenCode.make>,
|
||||
input: Runtime.Input<typeof Commands.commands.pair>,
|
||||
) {
|
||||
if (input.remote) return [yield* remoteURL(client)]
|
||||
if (Option.isSome(input.url)) return [input.url.value]
|
||||
return (yield* Effect.tryPromise(() => client.server.info())).urls
|
||||
})
|
||||
|
||||
// The service attaches the tunnel in the background, so wait for its URL to appear in server info.
|
||||
const remoteURL = Effect.fnUntraced(function* (client: ReturnType<typeof OpenCode.make>) {
|
||||
const tunnelURL = Effect.gen(function* () {
|
||||
const hostname = yield* RemoteTunnel.hostname()
|
||||
const info = yield* Effect.tryPromise(() => client.server.info())
|
||||
const url = info.urls.find((candidate) => hostname !== undefined && new URL(candidate).hostname === hostname)
|
||||
if (url === undefined) return yield* Effect.fail(new Error("Remote tunnel is not ready"))
|
||||
return url
|
||||
})
|
||||
return yield* tunnelURL.pipe(
|
||||
Effect.retry({ schedule: Schedule.spaced("1 second") }),
|
||||
Effect.timeoutOrElse({
|
||||
duration: "3 minutes",
|
||||
orElse: () =>
|
||||
Effect.fail(new Error("Timed out waiting for the remote tunnel; run `opencode pair --remote` again to retry")),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
function isLoopback(hostname: string) {
|
||||
return (
|
||||
hostname === "localhost" || hostname.endsWith(".localhost") || hostname.startsWith("127.") || hostname === "[::1]"
|
||||
|
||||
@@ -20,13 +20,8 @@ export default Runtime.handler(
|
||||
const updater = yield* Updater.Service
|
||||
const method = yield* updater.method()
|
||||
const removal = method ? updater.removal(method) : undefined
|
||||
const directories = [
|
||||
{ path: global.data, label: "Data", keep: input.keepData },
|
||||
{ path: global.cache, label: "Cache", keep: false },
|
||||
{ path: global.config, label: "Config", keep: input.keepConfig },
|
||||
{ path: global.state, label: "State", keep: false },
|
||||
]
|
||||
// All channels share these directories. Stop their owners before deleting state or data.
|
||||
// Data, config, and state hold sessions, credentials, settings, and prompt history; uninstall only removes the cache.
|
||||
// All channels share the cache. Stop background services before deleting it.
|
||||
// Read registrations directly: ServiceConfig.options() can migrate files even during a dry run.
|
||||
const services = (yield* fs.exists(global.state))
|
||||
? (yield* fs.readDirectory(global.state)).filter((name) => /^service(?:-.*)?\.json$/.test(name))
|
||||
@@ -35,12 +30,7 @@ export default Runtime.handler(
|
||||
|
||||
log.info(`Installation method: ${method ?? "unknown"}`)
|
||||
log.message("The following global files will be removed (shared by OpenCode versions and channels):")
|
||||
yield* Effect.forEach(directories, (directory) =>
|
||||
Effect.gen(function* () {
|
||||
if (!(yield* fs.exists(directory.path))) return
|
||||
log.info(` ${directory.label}: ${directory.path}${directory.keep ? " (keeping)" : ""}`)
|
||||
}),
|
||||
)
|
||||
if (yield* fs.exists(global.cache)) log.info(` Cache: ${global.cache}`)
|
||||
services.forEach((name) =>
|
||||
log.info(` Stop background service and persistent terminals: ${path.join(global.state, name)}`),
|
||||
)
|
||||
@@ -83,26 +73,21 @@ export default Runtime.handler(
|
||||
// Links that keep an older OpenCode replaceable may still run; move them so the cache can go.
|
||||
if (process.platform === "win32") yield* RetainedImage.relocate(global.cache, global.tmp)
|
||||
const errors: string[] = []
|
||||
yield* Effect.forEach(directories, (directory) =>
|
||||
Effect.gen(function* () {
|
||||
if (directory.keep) return
|
||||
progress.start(`Removing ${directory.label}...`)
|
||||
yield* fs.remove(directory.path, { recursive: true, force: true }).pipe(
|
||||
// Windows reports a terminated service as gone before it releases its database
|
||||
// and log handles, so the first removal can race that teardown.
|
||||
Effect.retry({
|
||||
while: (error) => process.platform === "win32" && error.reason._tag === "Busy",
|
||||
schedule: Schedule.max([Schedule.spaced("250 millis"), Schedule.recurs(40)]),
|
||||
}),
|
||||
Effect.tap(() => Effect.sync(() => progress.stop(`Removed ${directory.label}`))),
|
||||
Effect.catch((error) =>
|
||||
Effect.sync(() => {
|
||||
progress.stop(`Failed to remove ${directory.label}`, 1)
|
||||
errors.push(`${directory.label}: ${errorMessage(error)}`)
|
||||
}),
|
||||
),
|
||||
)
|
||||
progress.start("Removing Cache...")
|
||||
yield* fs.remove(global.cache, { recursive: true, force: true }).pipe(
|
||||
// Windows reports a terminated service as gone before it releases its file handles,
|
||||
// so the first removal can race that teardown.
|
||||
Effect.retry({
|
||||
while: (error) => process.platform === "win32" && error.reason._tag === "Busy",
|
||||
schedule: Schedule.max([Schedule.spaced("250 millis"), Schedule.recurs(40)]),
|
||||
}),
|
||||
Effect.tap(() => Effect.sync(() => progress.stop("Removed Cache"))),
|
||||
Effect.catch((error) =>
|
||||
Effect.sync(() => {
|
||||
progress.stop("Failed to remove Cache", 1)
|
||||
errors.push(`Cache: ${errorMessage(error)}`)
|
||||
}),
|
||||
),
|
||||
)
|
||||
yield* Effect.forEach(shell, (file) =>
|
||||
fs.readFileString(file).pipe(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { ensurePluginRuntime } from "@opencode/plugin/runtime"
|
||||
import { NodeRuntime, NodeServices } from "@effect/platform-node"
|
||||
import { Cause, Effect } from "effect"
|
||||
import { getErrorReported } from "effect/Runtime"
|
||||
@@ -17,6 +18,8 @@ import { EffectFlock } from "@opencode/util/effect-flock"
|
||||
import { Heap } from "./heap"
|
||||
import { CpuProfile } from "./cpu-profile"
|
||||
|
||||
ensurePluginRuntime()
|
||||
|
||||
if (process.env.OPENCODE_SSH_ASKPASS_PORT) {
|
||||
const { askpass } = await import("./ssh-askpass")
|
||||
process.exit(await Effect.runPromise(askpass.pipe(Effect.provide(NodeServices.layer))))
|
||||
|
||||
@@ -14,6 +14,7 @@ import { Env } from "./env"
|
||||
import { ServiceConfig } from "./services/service-config"
|
||||
import { RetainedImage } from "./services/retained-image"
|
||||
import { ServiceRegistration } from "./services/service-registration"
|
||||
import { RemoteTunnel } from "./services/remote-tunnel"
|
||||
import { WebUi } from "./services/web-ui"
|
||||
import { databasePath } from "./database-path"
|
||||
|
||||
@@ -88,6 +89,7 @@ const processEffect = Effect.fnUntraced(function* (options: Options) {
|
||||
if (!password) return yield* Effect.fail(new Error("Missing server password"))
|
||||
const instanceID = randomUUID()
|
||||
const transform = yield* WebUi.handler()
|
||||
const remote = { urls: [] as ReadonlyArray<string> }
|
||||
const launch = start(
|
||||
{
|
||||
app: {
|
||||
@@ -144,6 +146,7 @@ const processEffect = Effect.fnUntraced(function* (options: Options) {
|
||||
}),
|
||||
},
|
||||
transform,
|
||||
() => remote.urls,
|
||||
)
|
||||
const server = yield* launch.pipe(
|
||||
Effect.catch((error) => {
|
||||
@@ -170,6 +173,19 @@ const processEffect = Effect.fnUntraced(function* (options: Options) {
|
||||
}),
|
||||
)
|
||||
if (server === undefined) return
|
||||
if (serviceOptions !== undefined && config.remote === true && server.address._tag === "TcpAddress") {
|
||||
const bound = server.address.hostname
|
||||
// A wildcard bind also listens on loopback, which is all the tunnel needs to reach.
|
||||
const host = bound === "0.0.0.0" || bound === "::" ? "127.0.0.1" : bound.includes(":") ? `[${bound}]` : bound
|
||||
yield* Effect.forkScoped(
|
||||
RemoteTunnel.run({
|
||||
target: `${host}:${server.address.port}`,
|
||||
onURL: (url) => {
|
||||
remote.urls = url === undefined ? [] : [url]
|
||||
},
|
||||
}),
|
||||
)
|
||||
}
|
||||
const url = HttpServer.formatAddress(server.address)
|
||||
console.log(options.mode === "stdio" ? JSON.stringify({ url }) : `server listening on ${url}`)
|
||||
if (foreground && !environmentPassword) console.log(`server password ${password}`)
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
export * as RemoteTunnel from "./remote-tunnel"
|
||||
|
||||
import type { OpenTunnelError } from "@opentunnel/client/effect"
|
||||
import { Cause, Effect, Schedule } from "effect"
|
||||
import { EOL } from "os"
|
||||
import { OPENCODE_CHANNEL } from "../version"
|
||||
|
||||
// OpenTunnel keeps one tunnel per device in its default profile, shared by the opentunnel CLI and every app
|
||||
// using the SDK; each claims its own routes. The service claims a subdomain rather than the tunnel hostname,
|
||||
// which the CLI may route, and each channel's service gets its own subdomain.
|
||||
export function route(channel = OPENCODE_CHANNEL) {
|
||||
if (channel === "latest") return "opencode"
|
||||
return `opencode-${channel.toLowerCase().replace(/[^a-z0-9-]/g, "-")}`.slice(0, 63).replace(/-+$/, "")
|
||||
}
|
||||
|
||||
// Holds the route for the life of the service. The SDK reconnects through network failures itself, so only
|
||||
// setup failures reach the retry here; a rejected token or failed certificate stops it for good.
|
||||
export const run = Effect.fnUntraced(function* (input: {
|
||||
readonly target: string
|
||||
readonly onURL: (url: string | undefined) => void
|
||||
}) {
|
||||
const { OpenTunnelClient, OpenTunnelAttachError } = yield* Effect.promise(() => import("@opentunnel/client/effect"))
|
||||
const fatal = (error: OpenTunnelError) =>
|
||||
error._tag === "OpenTunnelClientError" &&
|
||||
(error.cause instanceof OpenTunnelAttachError || error.message.startsWith("Certificate issuance failed"))
|
||||
yield* Effect.gen(function* () {
|
||||
const client = yield* OpenTunnelClient
|
||||
const connection = yield* client.tunnel.connect({ routes: { [route()]: input.target } })
|
||||
input.onURL(`https://${route()}.${connection.tunnel.hostname}`)
|
||||
yield* connection.closed
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.ensuring(Effect.sync(() => input.onURL(undefined))),
|
||||
Effect.tapError((error) =>
|
||||
fatal(error) ? Effect.void : Effect.logWarning("remote access tunnel unavailable; retrying", { cause: error }),
|
||||
),
|
||||
Effect.retry({
|
||||
while: (error) => !fatal(error),
|
||||
schedule: Schedule.min([Schedule.exponential("1 second"), Schedule.spaced("30 seconds")]),
|
||||
}),
|
||||
Effect.provide(OpenTunnelClient.layer()),
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.failCause(cause)
|
||||
: Effect.logError("remote access tunnel stopped; run `opencode service set remote true` to retry", { cause }),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
// A device without a tunnel creates its shared one here, in the foreground, because issuing the certificate
|
||||
// takes a while; the service then only attaches its route on start. An interrupted issuance resumes next time.
|
||||
export const ensure = Effect.fnUntraced(function* () {
|
||||
const { OpenTunnelClient } = yield* Effect.promise(() => import("@opentunnel/client/effect"))
|
||||
return yield* Effect.gen(function* () {
|
||||
const client = yield* OpenTunnelClient
|
||||
if ((yield* client.tunnel.get()) === undefined)
|
||||
process.stderr.write("Setting up remote access; this can take a minute..." + EOL)
|
||||
return `${route()}.${(yield* client.tunnel.ensure()).hostname}`
|
||||
}).pipe(
|
||||
Effect.provide(OpenTunnelClient.layer()),
|
||||
Effect.timeoutOrElse({
|
||||
duration: "5 minutes",
|
||||
orElse: () => Effect.fail(new Error("Timed out creating the remote access tunnel; run the command again to resume")),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
// The tunnel hostname is persisted once the certificate is ready, so this is undefined until then.
|
||||
export const hostname = Effect.fnUntraced(function* () {
|
||||
const { OpenTunnelStorage } = yield* Effect.promise(() => import("@opentunnel/client/effect"))
|
||||
const identity = yield* OpenTunnelStorage.xdg().load("default")
|
||||
return identity === undefined ? undefined : `${route()}.${identity.hostname}`
|
||||
})
|
||||
@@ -6,6 +6,7 @@ import { Effect, FileSystem, Option, Schema } from "effect"
|
||||
import { randomBytes } from "crypto"
|
||||
import path from "path"
|
||||
import { selfCommand } from "../util/process"
|
||||
import { RemoteTunnel } from "./remote-tunnel"
|
||||
|
||||
// The CLI's service configuration file, plus the Service.EnsureOptions binding that
|
||||
// points the client package's service operations at this CLI: which
|
||||
@@ -13,6 +14,7 @@ import { selfCommand } from "../util/process"
|
||||
|
||||
export const Info = Schema.Struct({
|
||||
disabled: Schema.optional(Schema.Boolean),
|
||||
remote: Schema.optional(Schema.Boolean),
|
||||
hostname: Schema.optional(Schema.String),
|
||||
port: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(65_535))),
|
||||
password: Schema.optional(Schema.String),
|
||||
@@ -21,7 +23,7 @@ export const Info = Schema.Struct({
|
||||
})
|
||||
export type Info = typeof Info.Type
|
||||
|
||||
const keys = ["disabled", "hostname", "port", "password", "cors", "env"] as const
|
||||
const keys = ["disabled", "remote", "hostname", "port", "password", "cors", "env"] as const
|
||||
type Key = (typeof keys)[number]
|
||||
|
||||
const decodeInfo = Schema.decodeUnknownEffect(Schema.fromJsonString(Info))
|
||||
@@ -81,6 +83,7 @@ export const migrateConfig = Effect.fnUntraced(function* (legacy: string, file:
|
||||
function configKey(key: string): Key {
|
||||
if (
|
||||
key === "disabled" ||
|
||||
key === "remote" ||
|
||||
key === "hostname" ||
|
||||
key === "port" ||
|
||||
key === "password" ||
|
||||
@@ -163,6 +166,9 @@ export const get = Effect.fn("cli.service-config.get")(function* (key?: string,
|
||||
case "disabled": {
|
||||
return String((yield* read()).disabled ?? false)
|
||||
}
|
||||
case "remote": {
|
||||
return String((yield* read()).remote ?? false)
|
||||
}
|
||||
case "hostname": {
|
||||
return (yield* read()).hostname ?? ""
|
||||
}
|
||||
@@ -195,6 +201,14 @@ export const set = Effect.fn("cli.service-config.set")(function* (key: string, v
|
||||
yield* write({ ...(yield* read()), disabled: value === "true" })
|
||||
return
|
||||
}
|
||||
case "remote": {
|
||||
if (value !== "true" && value !== "false") throw new Error("Remote must be true or false")
|
||||
// A tunnel that cannot be created leaves remote access off instead of a service that keeps retrying.
|
||||
if (value === "true") yield* RemoteTunnel.ensure()
|
||||
yield* Service.stop(yield* options())
|
||||
yield* write({ ...(yield* read()), remote: value === "true" })
|
||||
return
|
||||
}
|
||||
case "hostname": {
|
||||
yield* Service.stop(yield* options())
|
||||
yield* write({ ...(yield* read()), hostname: value })
|
||||
@@ -244,6 +258,12 @@ export const unset = Effect.fn("cli.service-config.unset")(function* (key: strin
|
||||
yield* write(next)
|
||||
return
|
||||
}
|
||||
case "remote": {
|
||||
yield* Service.stop(yield* options())
|
||||
const { remote: _remote, ...next } = yield* read()
|
||||
yield* write(next)
|
||||
return
|
||||
}
|
||||
case "hostname": {
|
||||
yield* Service.stop(yield* options())
|
||||
const { hostname: _hostname, ...next } = yield* read()
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { validateRoutes } from "@opentunnel/client/effect"
|
||||
import { expect, test } from "bun:test"
|
||||
import { RemoteTunnel } from "../src/services/remote-tunnel"
|
||||
|
||||
test("each channel serves remote access on its own valid subdomain of the shared tunnel", () => {
|
||||
const channels = ["latest", "dev", "beta", "Preview/Feature_X.1", "a".repeat(80), "trailing-"]
|
||||
const routes = channels.map((channel) => RemoteTunnel.route(channel))
|
||||
|
||||
expect(routes.slice(0, 3)).toEqual(["opencode", "opencode-dev", "opencode-beta"])
|
||||
expect(new Set(routes).size).toBe(routes.length)
|
||||
// The SDK rejects invalid route names, which would keep the service from ever attaching.
|
||||
expect(() => validateRoutes(Object.fromEntries(routes.map((name) => [name, "127.0.0.1:4096"])))).not.toThrow()
|
||||
})
|
||||
@@ -43,6 +43,26 @@ test("service disabled accepts only booleans without changing configuration on i
|
||||
}
|
||||
})
|
||||
|
||||
// Enabling remote creates a real tunnel, so only the paths that stay local are covered here.
|
||||
test("service remote accepts only booleans and persists across set and unset", async () => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-remote-config-"))
|
||||
const layer = Global.layerWith({ config: path.join(root, "config"), state: path.join(root, "state") })
|
||||
const run = <A, E>(effect: Effect.Effect<A, E, Global.Service | FileSystem.FileSystem>) =>
|
||||
Effect.runPromise(effect.pipe(Effect.provide(layer), Effect.provide(NodeFileSystem.layer)))
|
||||
try {
|
||||
expect(await run(ServiceConfig.get("remote"))).toBe("false")
|
||||
await expect(run(ServiceConfig.set("remote", "on"))).rejects.toThrow("Remote must be true or false")
|
||||
expect(await run(ServiceConfig.read())).toEqual({})
|
||||
await run(ServiceConfig.set("remote", "false"))
|
||||
expect(await run(ServiceConfig.read())).toEqual({ remote: false })
|
||||
expect(await run(ServiceConfig.get("remote"))).toBe("false")
|
||||
await run(ServiceConfig.unset("remote"))
|
||||
expect(await run(ServiceConfig.read())).toEqual({})
|
||||
} finally {
|
||||
await fs.rm(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("local channel stores service config with the local service filename", async () => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-"))
|
||||
try {
|
||||
|
||||
@@ -118,7 +118,6 @@ export type SessionListInput = {
|
||||
readonly order?: "asc" | "desc" | undefined
|
||||
readonly search?: string | undefined
|
||||
readonly parentID?: Session.ID | null | undefined
|
||||
readonly archived?: boolean | undefined
|
||||
readonly directory?: AbsolutePath | undefined
|
||||
readonly project?: Project.ID | undefined
|
||||
readonly subpath?: RelativePath | undefined
|
||||
@@ -255,7 +254,6 @@ export type SessionUpdateInput = {
|
||||
readonly title?: string | undefined
|
||||
readonly metadata?: Session.Metadata | undefined
|
||||
readonly permissions?: Permission.Ruleset | undefined
|
||||
readonly archived?: boolean | undefined
|
||||
}
|
||||
export type SessionUpdateOutput = void
|
||||
export type SessionUpdateOperation<E = never> = (input: SessionUpdateInput) => Effect.Effect<SessionUpdateOutput, E>
|
||||
@@ -572,34 +570,6 @@ export type SessionLogOutput =
|
||||
| undefined
|
||||
readonly data: { readonly sessionID: Session.ID; readonly idle: number }
|
||||
}
|
||||
| {
|
||||
readonly id: Event.ID
|
||||
readonly created: number
|
||||
readonly metadata?: { readonly [x: string]: unknown } | undefined
|
||||
readonly type: "session.archived"
|
||||
readonly durable: { readonly aggregateID: string; readonly seq: Event.Seq; readonly version: Event.Version }
|
||||
readonly location?:
|
||||
| {
|
||||
readonly directory: AbsolutePath
|
||||
readonly workspaceID?: (string & Brand.Brand<"Workspace.ID">) | undefined
|
||||
}
|
||||
| undefined
|
||||
readonly data: { readonly sessionID: Session.ID }
|
||||
}
|
||||
| {
|
||||
readonly id: Event.ID
|
||||
readonly created: number
|
||||
readonly metadata?: { readonly [x: string]: unknown } | undefined
|
||||
readonly type: "session.unarchived"
|
||||
readonly durable: { readonly aggregateID: string; readonly seq: Event.Seq; readonly version: Event.Version }
|
||||
readonly location?:
|
||||
| {
|
||||
readonly directory: AbsolutePath
|
||||
readonly workspaceID?: (string & Brand.Brand<"Workspace.ID">) | undefined
|
||||
}
|
||||
| undefined
|
||||
readonly data: { readonly sessionID: Session.ID }
|
||||
}
|
||||
| {
|
||||
readonly id: Event.ID
|
||||
readonly created: number
|
||||
@@ -1627,6 +1597,18 @@ export type IntegrationConnectKeyOperation<E = never> = (
|
||||
input: IntegrationConnectKeyInput,
|
||||
) => Effect.Effect<IntegrationConnectKeyOutput, E>
|
||||
|
||||
export type IntegrationConnectExternalInput = {
|
||||
readonly integrationID: Integration.ID
|
||||
readonly location?: { readonly directory?: string | undefined } | undefined
|
||||
readonly methodID: Integration.MethodID
|
||||
readonly answer?: Form.Answer | undefined
|
||||
readonly label?: string | undefined
|
||||
}
|
||||
export type IntegrationConnectExternalOutput = void
|
||||
export type IntegrationConnectExternalOperation<E = never> = (
|
||||
input: IntegrationConnectExternalInput,
|
||||
) => Effect.Effect<IntegrationConnectExternalOutput, E>
|
||||
|
||||
export type IntegrationOauthConnectInput = {
|
||||
readonly integrationID: Integration.ID
|
||||
readonly location?: { readonly directory?: string | undefined } | undefined
|
||||
@@ -1717,7 +1699,10 @@ export interface IntegrationApi<E = never> {
|
||||
readonly list: IntegrationListOperation<E>
|
||||
readonly get: IntegrationGetOperation<E>
|
||||
readonly wellknown: { readonly add: IntegrationWellknownAddOperation<E> }
|
||||
readonly connect: { readonly key: IntegrationConnectKeyOperation<E> }
|
||||
readonly connect: {
|
||||
readonly key: IntegrationConnectKeyOperation<E>
|
||||
readonly external: IntegrationConnectExternalOperation<E>
|
||||
}
|
||||
readonly oauth: {
|
||||
readonly connect: IntegrationOauthConnectOperation<E>
|
||||
readonly status: IntegrationOauthStatusOperation<E>
|
||||
|
||||
@@ -127,6 +127,8 @@ import type {
|
||||
IntegrationWellknownAddOutput,
|
||||
IntegrationConnectKeyInput,
|
||||
IntegrationConnectKeyOutput,
|
||||
IntegrationConnectExternalInput,
|
||||
IntegrationConnectExternalOutput,
|
||||
IntegrationOauthConnectInput,
|
||||
IntegrationOauthConnectOutput,
|
||||
IntegrationOauthStatusInput,
|
||||
@@ -366,7 +368,6 @@ const EndpointSessionList = (raw: RawClient["server.session"]) => (input?: Sessi
|
||||
order: input?.["order"],
|
||||
search: input?.["search"],
|
||||
parentID: input?.["parentID"],
|
||||
archived: input?.["archived"],
|
||||
directory: input?.["directory"],
|
||||
project: input?.["project"],
|
||||
subpath: input?.["subpath"],
|
||||
@@ -475,12 +476,7 @@ const EndpointSessionUpdate = (raw: RawClient["server.session"]) => (input: Sess
|
||||
preserveEffect<SessionUpdateOutput>()(
|
||||
raw["session.update"]({
|
||||
params: { sessionID: input["sessionID"] },
|
||||
payload: {
|
||||
title: input["title"],
|
||||
metadata: input["metadata"],
|
||||
permissions: input["permissions"],
|
||||
archived: input["archived"],
|
||||
},
|
||||
payload: { title: input["title"], metadata: input["metadata"], permissions: input["permissions"] },
|
||||
}).pipe(Effect.mapError(mapClientError)),
|
||||
)
|
||||
|
||||
@@ -903,6 +899,16 @@ const EndpointIntegrationConnectKey = (raw: RawClient["server.integration"]) =>
|
||||
}).pipe(Effect.mapError(mapClientError)),
|
||||
)
|
||||
|
||||
const EndpointIntegrationConnectExternal =
|
||||
(raw: RawClient["server.integration"]) => (input: IntegrationConnectExternalInput) =>
|
||||
preserveEffect<IntegrationConnectExternalOutput>()(
|
||||
raw["integration.connect.external"]({
|
||||
params: { integrationID: input["integrationID"] },
|
||||
query: { location: input["location"] },
|
||||
payload: { methodID: input["methodID"], answer: input["answer"], label: input["label"] },
|
||||
}).pipe(Effect.mapError(mapClientError)),
|
||||
)
|
||||
|
||||
const EndpointIntegrationOauthConnect =
|
||||
(raw: RawClient["server.integration"]) => (input: IntegrationOauthConnectInput) =>
|
||||
preserveEffect<IntegrationOauthConnectOutput>()(
|
||||
@@ -971,7 +977,7 @@ const adaptGroupIntegration = (raw: RawClient["server.integration"]) => ({
|
||||
list: EndpointIntegrationList(raw),
|
||||
get: EndpointIntegrationGet(raw),
|
||||
wellknown: { add: EndpointIntegrationWellknownAdd(raw) },
|
||||
connect: { key: EndpointIntegrationConnectKey(raw) },
|
||||
connect: { key: EndpointIntegrationConnectKey(raw), external: EndpointIntegrationConnectExternal(raw) },
|
||||
oauth: {
|
||||
connect: EndpointIntegrationOauthConnect(raw),
|
||||
status: EndpointIntegrationOauthStatus(raw),
|
||||
|
||||
@@ -121,6 +121,8 @@ import type {
|
||||
IntegrationWellknownAddOutput,
|
||||
IntegrationConnectKeyInput,
|
||||
IntegrationConnectKeyOutput,
|
||||
IntegrationConnectExternalInput,
|
||||
IntegrationConnectExternalOutput,
|
||||
IntegrationOauthConnectInput,
|
||||
IntegrationOauthConnectOutput,
|
||||
IntegrationOauthStatusInput,
|
||||
@@ -543,7 +545,6 @@ export function make(options: ClientOptions) {
|
||||
order: input?.["order"],
|
||||
search: input?.["search"],
|
||||
parentID: input?.["parentID"],
|
||||
archived: input?.["archived"],
|
||||
directory: input?.["directory"],
|
||||
project: input?.["project"],
|
||||
subpath: input?.["subpath"],
|
||||
@@ -692,12 +693,7 @@ export function make(options: ClientOptions) {
|
||||
{
|
||||
method: "PATCH",
|
||||
path: `/api/session/${encodeURIComponent(input.sessionID)}`,
|
||||
body: {
|
||||
title: input["title"],
|
||||
metadata: input["metadata"],
|
||||
permissions: input["permissions"],
|
||||
archived: input["archived"],
|
||||
},
|
||||
body: { title: input["title"], metadata: input["metadata"], permissions: input["permissions"] },
|
||||
successStatus: 204,
|
||||
declaredStatuses: [400, 401, 404],
|
||||
empty: true,
|
||||
@@ -1234,6 +1230,19 @@ export function make(options: ClientOptions) {
|
||||
},
|
||||
requestOptions,
|
||||
),
|
||||
external: (input: IntegrationConnectExternalInput, requestOptions?: RequestOptions) =>
|
||||
request<IntegrationConnectExternalOutput>(
|
||||
{
|
||||
method: "POST",
|
||||
path: `/api/integration/${encodeURIComponent(input.integrationID)}/connect/external`,
|
||||
query: { location: input["location"] },
|
||||
body: { methodID: input["methodID"], answer: input["answer"], label: input["label"] },
|
||||
successStatus: 204,
|
||||
declaredStatuses: [400, 401, 404],
|
||||
empty: true,
|
||||
},
|
||||
requestOptions,
|
||||
),
|
||||
},
|
||||
oauth: {
|
||||
connect: (input: IntegrationOauthConnectInput, requestOptions?: RequestOptions) =>
|
||||
|
||||
@@ -623,26 +623,6 @@ export type SessionViewed = {
|
||||
data: { sessionID: string; idle: number }
|
||||
}
|
||||
|
||||
export type SessionArchived = {
|
||||
id: string
|
||||
created: number
|
||||
metadata?: { [x: string]: any }
|
||||
type: "session.archived"
|
||||
durable: { aggregateID: string; seq: number; version: 1 }
|
||||
location?: LocationRef
|
||||
data: { sessionID: string }
|
||||
}
|
||||
|
||||
export type SessionUnarchived = {
|
||||
id: string
|
||||
created: number
|
||||
metadata?: { [x: string]: any }
|
||||
type: "session.unarchived"
|
||||
durable: { aggregateID: string; seq: number; version: 1 }
|
||||
location?: LocationRef
|
||||
data: { sessionID: string }
|
||||
}
|
||||
|
||||
export type SessionDeleted = {
|
||||
id: string
|
||||
created: number
|
||||
@@ -2220,7 +2200,11 @@ export type ConfigEntry =
|
||||
experimental?: {
|
||||
portable_shell_scanner?: boolean
|
||||
subagent_depth?: number
|
||||
policies?: Array<{ action: "provider.use" | "permission"; resource: string; effect: "allow" | "deny" }>
|
||||
policies?: Array<{
|
||||
action: "provider.use" | "tool.use" | "integration.use"
|
||||
resource: string
|
||||
effect: "allow" | "deny"
|
||||
}>
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2334,6 +2318,8 @@ export type IntegrationOAuthMethod = { id: string; type: "oauth"; label: string;
|
||||
|
||||
export type IntegrationKeyMethod = { type: "key"; label?: string; form?: FormFields }
|
||||
|
||||
export type IntegrationExternalMethod = { id: string; type: "external"; label: string; form?: FormFields }
|
||||
|
||||
export type CredentialEntry = {
|
||||
id: string
|
||||
integrationID: string
|
||||
@@ -2371,6 +2357,7 @@ export type IntegrationMethod =
|
||||
| IntegrationOAuthMethod
|
||||
| IntegrationCommandMethod
|
||||
| IntegrationKeyMethod
|
||||
| IntegrationExternalMethod
|
||||
| IntegrationEnvMethod
|
||||
|
||||
export type FormCreated = {
|
||||
@@ -2398,8 +2385,6 @@ export type SessionEventDurable =
|
||||
| SessionMetadataUpdated
|
||||
| SessionPermissions
|
||||
| SessionViewed
|
||||
| SessionArchived
|
||||
| SessionUnarchived
|
||||
| SessionDeleted
|
||||
| SessionForked
|
||||
| SessionInboxDelivered
|
||||
@@ -2463,8 +2448,6 @@ export type V2Event =
|
||||
| SessionMetadataUpdated
|
||||
| SessionPermissions
|
||||
| SessionViewed
|
||||
| SessionArchived
|
||||
| SessionUnarchived
|
||||
| SessionUsageUpdated
|
||||
| SessionDeleted
|
||||
| SessionForked
|
||||
@@ -2847,7 +2830,6 @@ export type SessionListInput = {
|
||||
readonly order?: "asc" | "desc" | undefined
|
||||
readonly search?: string | undefined
|
||||
readonly parentID?: string | null | undefined
|
||||
readonly archived?: boolean | undefined
|
||||
readonly directory?: string | undefined
|
||||
readonly project?: string | undefined
|
||||
readonly subpath?: string | undefined
|
||||
@@ -2858,7 +2840,6 @@ export type SessionListInput = {
|
||||
readonly order?: "asc" | "desc" | undefined
|
||||
readonly search?: string | undefined
|
||||
readonly parentID?: string | null | undefined
|
||||
readonly archived?: boolean | undefined
|
||||
readonly directory?: string | undefined
|
||||
readonly project?: string | undefined
|
||||
readonly subpath?: string | undefined
|
||||
@@ -2869,7 +2850,6 @@ export type SessionListInput = {
|
||||
readonly order?: "asc" | "desc" | undefined
|
||||
readonly search?: string | undefined
|
||||
readonly parentID?: string | null | undefined
|
||||
readonly archived?: boolean | undefined
|
||||
readonly directory?: string | undefined
|
||||
readonly project?: string | undefined
|
||||
readonly subpath?: string | undefined
|
||||
@@ -2880,29 +2860,16 @@ export type SessionListInput = {
|
||||
readonly order?: "asc" | "desc" | undefined
|
||||
readonly search?: string | undefined
|
||||
readonly parentID?: string | null | undefined
|
||||
readonly archived?: boolean | undefined
|
||||
readonly directory?: string | undefined
|
||||
readonly project?: string | undefined
|
||||
readonly subpath?: string | undefined
|
||||
readonly cursor?: string | undefined
|
||||
}["parentID"]
|
||||
readonly archived?: {
|
||||
readonly limit?: number | undefined
|
||||
readonly order?: "asc" | "desc" | undefined
|
||||
readonly search?: string | undefined
|
||||
readonly parentID?: string | null | undefined
|
||||
readonly archived?: boolean | undefined
|
||||
readonly directory?: string | undefined
|
||||
readonly project?: string | undefined
|
||||
readonly subpath?: string | undefined
|
||||
readonly cursor?: string | undefined
|
||||
}["archived"]
|
||||
readonly directory?: {
|
||||
readonly limit?: number | undefined
|
||||
readonly order?: "asc" | "desc" | undefined
|
||||
readonly search?: string | undefined
|
||||
readonly parentID?: string | null | undefined
|
||||
readonly archived?: boolean | undefined
|
||||
readonly directory?: string | undefined
|
||||
readonly project?: string | undefined
|
||||
readonly subpath?: string | undefined
|
||||
@@ -2913,7 +2880,6 @@ export type SessionListInput = {
|
||||
readonly order?: "asc" | "desc" | undefined
|
||||
readonly search?: string | undefined
|
||||
readonly parentID?: string | null | undefined
|
||||
readonly archived?: boolean | undefined
|
||||
readonly directory?: string | undefined
|
||||
readonly project?: string | undefined
|
||||
readonly subpath?: string | undefined
|
||||
@@ -2924,7 +2890,6 @@ export type SessionListInput = {
|
||||
readonly order?: "asc" | "desc" | undefined
|
||||
readonly search?: string | undefined
|
||||
readonly parentID?: string | null | undefined
|
||||
readonly archived?: boolean | undefined
|
||||
readonly directory?: string | undefined
|
||||
readonly project?: string | undefined
|
||||
readonly subpath?: string | undefined
|
||||
@@ -2935,7 +2900,6 @@ export type SessionListInput = {
|
||||
readonly order?: "asc" | "desc" | undefined
|
||||
readonly search?: string | undefined
|
||||
readonly parentID?: string | null | undefined
|
||||
readonly archived?: boolean | undefined
|
||||
readonly directory?: string | undefined
|
||||
readonly project?: string | undefined
|
||||
readonly subpath?: string | undefined
|
||||
@@ -4166,7 +4130,6 @@ export type SessionUpdateInput = {
|
||||
readonly permissions?:
|
||||
| ReadonlyArray<{ readonly action: string; readonly resource: string; readonly effect: "allow" | "deny" | "ask" }>
|
||||
| undefined
|
||||
readonly archived?: boolean | undefined
|
||||
}["title"]
|
||||
readonly metadata?: {
|
||||
readonly title?: string | undefined
|
||||
@@ -4174,7 +4137,6 @@ export type SessionUpdateInput = {
|
||||
readonly permissions?:
|
||||
| ReadonlyArray<{ readonly action: string; readonly resource: string; readonly effect: "allow" | "deny" | "ask" }>
|
||||
| undefined
|
||||
readonly archived?: boolean | undefined
|
||||
}["metadata"]
|
||||
readonly permissions?: {
|
||||
readonly title?: string | undefined
|
||||
@@ -4182,16 +4144,7 @@ export type SessionUpdateInput = {
|
||||
readonly permissions?:
|
||||
| ReadonlyArray<{ readonly action: string; readonly resource: string; readonly effect: "allow" | "deny" | "ask" }>
|
||||
| undefined
|
||||
readonly archived?: boolean | undefined
|
||||
}["permissions"]
|
||||
readonly archived?: {
|
||||
readonly title?: string | undefined
|
||||
readonly metadata?: { readonly [x: string]: JsonValue } | undefined
|
||||
readonly permissions?:
|
||||
| ReadonlyArray<{ readonly action: string; readonly resource: string; readonly effect: "allow" | "deny" | "ask" }>
|
||||
| undefined
|
||||
readonly archived?: boolean | undefined
|
||||
}["archived"]
|
||||
}
|
||||
|
||||
export type SessionUpdateOutput = void
|
||||
@@ -5742,6 +5695,28 @@ export type IntegrationConnectKeyInput = {
|
||||
|
||||
export type IntegrationConnectKeyOutput = void
|
||||
|
||||
export type IntegrationConnectExternalInput = {
|
||||
readonly integrationID: { readonly integrationID: string }["integrationID"]
|
||||
readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"]
|
||||
readonly methodID: {
|
||||
readonly methodID: string
|
||||
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
|
||||
readonly label?: string | undefined
|
||||
}["methodID"]
|
||||
readonly answer?: {
|
||||
readonly methodID: string
|
||||
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
|
||||
readonly label?: string | undefined
|
||||
}["answer"]
|
||||
readonly label?: {
|
||||
readonly methodID: string
|
||||
readonly answer?: { readonly [x: string]: string | number | boolean | ReadonlyArray<string> } | undefined
|
||||
readonly label?: string | undefined
|
||||
}["label"]
|
||||
}
|
||||
|
||||
export type IntegrationConnectExternalOutput = void
|
||||
|
||||
export type IntegrationOauthConnectInput = {
|
||||
readonly integrationID: { readonly integrationID: string }["integrationID"]
|
||||
readonly location?: { readonly location?: { readonly directory?: string | undefined } | undefined }["location"]
|
||||
|
||||
@@ -701,14 +701,6 @@ export function createData(config: CreateDataInput) {
|
||||
if (store.session.info[event.data.sessionID])
|
||||
setStore("session", "info", event.data.sessionID, "permissions", event.data.permissions)
|
||||
return
|
||||
case "session.archived":
|
||||
if (store.session.info[event.data.sessionID])
|
||||
setStore("session", "info", event.data.sessionID, "time", "archived", event.created)
|
||||
return
|
||||
case "session.unarchived":
|
||||
if (store.session.info[event.data.sessionID])
|
||||
setStore("session", "info", event.data.sessionID, "time", "archived", undefined)
|
||||
return
|
||||
case "session.moved": {
|
||||
const current = store.session.info[event.data.sessionID]
|
||||
if (current) {
|
||||
|
||||
@@ -2,10 +2,14 @@ export * as ConfigMarkdown from "./markdown.js"
|
||||
|
||||
import matter from "gray-matter"
|
||||
export function parse(content: string) {
|
||||
// Passing options bypasses gray-matter's module-global content cache, which
|
||||
// it populates before parsing: a failed YAML parse poisons the entry and
|
||||
// every later parse of the same content replays it without throwing, so the
|
||||
// sanitize fallback below never runs. Upstream: jonschlinkert/gray-matter#166.
|
||||
try {
|
||||
return matter(content)
|
||||
return matter(content, {})
|
||||
} catch {
|
||||
return matter(sanitize(content))
|
||||
return matter(sanitize(content), {})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
export * as ConfigPolicyPlugin from "./policy.js"
|
||||
|
||||
import { define } from "@opencode/plugin/effect/plugin"
|
||||
import { Document } from "@opencode/schema/config"
|
||||
import { Effect } from "effect"
|
||||
import { Effect, Stream } from "effect"
|
||||
import { Config } from "../../config.js"
|
||||
import { ManagedPolicy } from "../../managed-policy.js"
|
||||
import { State } from "../../state.js"
|
||||
import { Wildcard } from "../../util/wildcard.js"
|
||||
import { ConfigEntryObserver } from "./entry-observer.js"
|
||||
|
||||
@@ -13,25 +13,17 @@ export const Plugin = define({
|
||||
effect: Effect.fn(function* (ctx) {
|
||||
const config = yield* Config.Service
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, ctx.provider.reload())
|
||||
const reload = State.batch(
|
||||
Effect.all([ctx.provider.reload(), ctx.mcp.reload(), ctx.skill.reload()], { discard: true }),
|
||||
)
|
||||
const loaded = yield* ConfigEntryObserver.observe(config, ctx.event, reload)
|
||||
yield* managed.changes().pipe(
|
||||
Stream.runForEach(() => reload),
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
// Authored documents reverse so user-global policy outranks repository policy; organization statements
|
||||
// from the connected Console follow every authored one and have the final say.
|
||||
const policies = () => {
|
||||
const organization = managed.current()
|
||||
return [
|
||||
...loaded.entries
|
||||
.filter((entry): entry is Document => entry.type === "document")
|
||||
.toReversed()
|
||||
.flatMap((entry) => entry.info.experimental?.policies ?? [])
|
||||
.map((policy) => ({ ...policy, message: "Blocked by configuration policy" })),
|
||||
...organization.statements.map((policy) => ({
|
||||
...policy,
|
||||
message: organization.organization
|
||||
? `Blocked by ${organization.organization}'s policy`
|
||||
: "Blocked by your organization's policy",
|
||||
})),
|
||||
]
|
||||
}
|
||||
const policies = () => ManagedPolicy.statements(loaded.entries, managed.current())
|
||||
yield* ctx.provider.transform((providers) => {
|
||||
const current = policies()
|
||||
for (const record of providers.list()) {
|
||||
@@ -41,6 +33,18 @@ export const Plugin = define({
|
||||
if (policy?.effect === "deny") providers.remove(record.provider.id)
|
||||
}
|
||||
})
|
||||
yield* ctx.mcp.transform((servers) => {
|
||||
const current = policies()
|
||||
for (const [name] of servers.list()) {
|
||||
if (ManagedPolicy.decision(current, "integration.use", `mcp:${name}`) === "deny") servers.remove(name)
|
||||
}
|
||||
})
|
||||
yield* ctx.skill.transform((skills) => {
|
||||
const current = policies()
|
||||
for (const skill of skills.list()) {
|
||||
if (ManagedPolicy.decision(current, "integration.use", `skill:${skill.id}`) === "deny") skills.remove(skill.id)
|
||||
}
|
||||
})
|
||||
yield* ctx.permission.hook("evaluate", (event) =>
|
||||
Effect.sync(() => {
|
||||
const current = policies()
|
||||
@@ -48,7 +52,7 @@ export const Plugin = define({
|
||||
.map((resource) =>
|
||||
current.findLast(
|
||||
(policy) =>
|
||||
policy.action === "permission" && Wildcard.match(`${event.action}:${resource}`, policy.resource),
|
||||
policy.action === "tool.use" && Wildcard.match(`${event.action}:${resource}`, policy.resource),
|
||||
),
|
||||
)
|
||||
.find((policy) => policy?.effect === "deny")
|
||||
|
||||
+2
@@ -47,6 +47,7 @@ import m44 from "./migration/20260819222447_session_viewed_state.js"
|
||||
import m45 from "./migration/20260823191254_nullable_workspace_binding.js"
|
||||
import m46 from "./migration/20260910120000_clear_v1_session_permission.js"
|
||||
import m47 from "./migration/20260923013825_project_time_active.js"
|
||||
import m48 from "./migration/20261007190000_azure_cli_external_credential.js"
|
||||
|
||||
export const migrations = [
|
||||
m00,
|
||||
@@ -97,4 +98,5 @@ export const migrations = [
|
||||
m45,
|
||||
m46,
|
||||
m47,
|
||||
m48,
|
||||
] satisfies DatabaseMigration.Migration[]
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Effect } from "effect"
|
||||
import type { DatabaseMigration } from "../migration.js"
|
||||
|
||||
// Azure CLI connections were OAuth credentials holding a copy of the CLI's token; they now reference the CLI as an
|
||||
// external credential source. Dropping the token fields keeps the method and the resource in metadata.
|
||||
const migration: DatabaseMigration.Migration = {
|
||||
id: "20261007190000_azure_cli_external_credential",
|
||||
up(tx) {
|
||||
return Effect.gen(function* () {
|
||||
yield* tx.run(`
|
||||
UPDATE \`credential\`
|
||||
SET \`value\` = json_remove(json_set(\`value\`, '$.type', 'external'), '$.access', '$.refresh', '$.expires')
|
||||
WHERE \`integration_id\` = 'azure'
|
||||
AND json_extract(\`value\`, '$.type') = 'oauth'
|
||||
AND json_extract(\`value\`, '$.methodID') = 'azure-cli'
|
||||
`)
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -45,6 +45,9 @@ export type CommandMethod = Integration.CommandMethod
|
||||
export const KeyMethod = Integration.KeyMethod
|
||||
export type KeyMethod = Integration.KeyMethod
|
||||
|
||||
export const ExternalMethod = Integration.ExternalMethod
|
||||
export type ExternalMethod = Integration.ExternalMethod
|
||||
|
||||
export const EnvMethod = Integration.EnvMethod
|
||||
export type EnvMethod = Integration.EnvMethod
|
||||
|
||||
@@ -82,6 +85,11 @@ export interface KeyImplementation {
|
||||
readonly method: KeyMethod
|
||||
}
|
||||
|
||||
export interface ExternalImplementation {
|
||||
readonly integrationID: ID
|
||||
readonly method: ExternalMethod
|
||||
}
|
||||
|
||||
export interface CommandImplementation {
|
||||
readonly integrationID: ID
|
||||
readonly method: CommandMethod
|
||||
@@ -92,7 +100,12 @@ export interface EnvImplementation {
|
||||
readonly method: EnvMethod
|
||||
}
|
||||
|
||||
export type Implementation = OAuthImplementation | CommandImplementation | KeyImplementation | EnvImplementation
|
||||
export type Implementation =
|
||||
| OAuthImplementation
|
||||
| CommandImplementation
|
||||
| KeyImplementation
|
||||
| ExternalImplementation
|
||||
| EnvImplementation
|
||||
|
||||
export const Attempt = Integration.Attempt
|
||||
export type Attempt = Integration.Attempt
|
||||
@@ -180,6 +193,17 @@ export interface Interface extends State.Transformable<Editor> {
|
||||
/** User-facing label for the stored credential. */
|
||||
readonly label?: string
|
||||
}) => Effect.Effect<void, AuthorizationError>
|
||||
/** Runs an external method and stores a reference configured by its form answers. */
|
||||
readonly external: (input: {
|
||||
/** Integration receiving the credential. */
|
||||
readonly integrationID: ID
|
||||
/** External method that defines the form and credential source. */
|
||||
readonly methodID: MethodID
|
||||
/** Values collected from the method's form fields. */
|
||||
readonly answer?: Form.Answer
|
||||
/** User-facing label for the stored credential. */
|
||||
readonly label?: string
|
||||
}) => Effect.Effect<void, AuthorizationError>
|
||||
/** Selects a stored credential as the active integration connection. */
|
||||
readonly activate: (credentialID: Credential.ID) => Effect.Effect<void>
|
||||
/** Updates a stored credential exposed as a connection. */
|
||||
@@ -327,6 +351,8 @@ const layer = Layer.effect(
|
||||
return method.id === implementation.method.id
|
||||
if (method.type === "command" && implementation.method.type === "command")
|
||||
return method.id === implementation.method.id
|
||||
if (method.type === "external" && implementation.method.type === "external")
|
||||
return method.id === implementation.method.id
|
||||
return true
|
||||
})
|
||||
if (index === -1) current.methods.push(implementation.method as Types.DeepMutable<Method>)
|
||||
@@ -345,6 +371,7 @@ const layer = Layer.effect(
|
||||
if (candidate.type !== method.type) return false
|
||||
if (candidate.type === "oauth" && method.type === "oauth") return candidate.id === method.id
|
||||
if (candidate.type === "command" && method.type === "command") return candidate.id === method.id
|
||||
if (candidate.type === "external" && method.type === "external") return candidate.id === method.id
|
||||
return true
|
||||
})
|
||||
if (index !== -1) current.methods.splice(index, 1)
|
||||
@@ -736,6 +763,31 @@ const layer = Layer.effect(
|
||||
}),
|
||||
})
|
||||
}),
|
||||
external: Effect.fn("Integration.connection.external")(function* (input) {
|
||||
const method = state
|
||||
.get()
|
||||
.integrations.get(input.integrationID)
|
||||
?.methods.find((method) => method.type === "external" && method.id === input.methodID)
|
||||
if (method?.type !== "external")
|
||||
return yield* new AuthorizationError({ cause: new Error(`External method not found: ${input.methodID}`) })
|
||||
const answer = input.answer ?? {}
|
||||
if (method.form) {
|
||||
const invalid = Form.validateFields(method.form) ?? Form.validateAnswer(method.form, answer)
|
||||
if (invalid) return yield* new AuthorizationError({ cause: new Error(invalid) })
|
||||
}
|
||||
if (!method.form && Object.keys(answer).length > 0) {
|
||||
return yield* new AuthorizationError({ cause: new Error("External method does not accept a form answer") })
|
||||
}
|
||||
yield* createCredential({
|
||||
integrationID: input.integrationID,
|
||||
label: input.label,
|
||||
value: Credential.External.make({
|
||||
type: "external",
|
||||
methodID: method.id,
|
||||
...(Object.keys(answer).length > 0 ? { metadata: answer } : {}),
|
||||
}),
|
||||
})
|
||||
}),
|
||||
activate: Effect.fn("Integration.connection.activate")((credentialID) => credentials.activate(credentialID)),
|
||||
update: Effect.fn("Integration.connection.update")((credentialID, updates) =>
|
||||
credentials.update(credentialID, updates),
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
export * as ManagedPolicy from "./managed-policy.js"
|
||||
|
||||
import { Document, type Entry } from "@opencode/schema/config"
|
||||
import { isDeepStrictEqual } from "node:util"
|
||||
import { Wildcard } from "./util/wildcard.js"
|
||||
import { ConfigPolicy } from "@opencode/schema/config/policy"
|
||||
import { Context, Effect, Layer } from "effect"
|
||||
import { Context, Effect, Layer, PubSub, Stream } from "effect"
|
||||
import { makeGlobalNode } from "@opencode/util/effect/app-node"
|
||||
|
||||
/** Policy statements the connected OpenCode Console compiled for whoever it authenticated. */
|
||||
@@ -12,6 +15,7 @@ export interface State {
|
||||
}
|
||||
|
||||
export interface Interface {
|
||||
readonly changes: () => Stream.Stream<void>
|
||||
/** Synchronous so catalog transforms can consult the statements while they run. */
|
||||
readonly current: () => State
|
||||
/** Replaces the whole state; statements never merge across connections. */
|
||||
@@ -20,15 +24,52 @@ export interface Interface {
|
||||
|
||||
export class Service extends Context.Service<Service, Interface>()("@opencode/ManagedPolicy") {}
|
||||
|
||||
const layer = Layer.sync(Service, () => {
|
||||
const state: { current: State } = { current: { statements: [] } }
|
||||
return Service.of({
|
||||
current: () => state.current,
|
||||
set: (next) =>
|
||||
Effect.sync(() => {
|
||||
state.current = next
|
||||
}),
|
||||
})
|
||||
})
|
||||
export const layer = Layer.effect(
|
||||
Service,
|
||||
Effect.gen(function* () {
|
||||
const changes = yield* PubSub.unbounded<void>()
|
||||
const state: { current: State } = { current: { statements: [] } }
|
||||
return Service.of({
|
||||
changes: () => Stream.fromPubSub(changes),
|
||||
current: () => state.current,
|
||||
set: (next) =>
|
||||
Effect.gen(function* () {
|
||||
const changed =
|
||||
state.current.organization !== next.organization ||
|
||||
!isDeepStrictEqual(state.current.statements, next.statements)
|
||||
state.current = next
|
||||
if (!changed) return
|
||||
yield* PubSub.publish(changes, undefined)
|
||||
}),
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
export const node = makeGlobalNode({ service: Service, layer, deps: [] })
|
||||
|
||||
export function statements(entries: readonly Entry[], organization: State) {
|
||||
return [
|
||||
...entries
|
||||
.filter((entry): entry is Document => entry.type === "document")
|
||||
.toReversed()
|
||||
.flatMap((entry) => entry.info.experimental?.policies ?? [])
|
||||
.map((policy) => ({ ...policy, message: "Blocked by configuration policy" })),
|
||||
...organization.statements.map((policy) => ({
|
||||
...policy,
|
||||
message: organization.organization
|
||||
? `Blocked by ${organization.organization}'s policy`
|
||||
: "Blocked by your organization's policy",
|
||||
})),
|
||||
]
|
||||
}
|
||||
|
||||
export function decision(
|
||||
policies: readonly ConfigPolicy.Info[],
|
||||
action: ConfigPolicy.Info["action"],
|
||||
resource: string,
|
||||
) {
|
||||
return (
|
||||
policies.findLast((policy) => policy.action === action && Wildcard.match(resource, policy.resource))?.effect ??
|
||||
"allow"
|
||||
)
|
||||
}
|
||||
@@ -207,7 +207,7 @@ const resolveCatalogModel = Effect.fn("ModelResolver.resolveCatalogModel")(funct
|
||||
const settings = yield* prepareProviderSettings(
|
||||
resolved,
|
||||
Provider.mergeOverlay(resolved.settings, {
|
||||
...nativeCredentialSettings(resolved.package ?? "", credential),
|
||||
...nativeCredentialSettings(resolved, resolved.package ?? "", credential),
|
||||
...credential?.metadata,
|
||||
...configuration,
|
||||
}) ?? {},
|
||||
@@ -225,7 +225,7 @@ const resolveCatalogModel = Effect.fn("ModelResolver.resolveCatalogModel")(funct
|
||||
const settings = {
|
||||
...(credential ? Struct.omit(mapped, ["accessToken", "apiKey", "authToken"]) : mapped),
|
||||
...(resolved.canonical === undefined ? {} : { provider: resolved.canonical }),
|
||||
...nativeCredentialSettings(specifier, credential),
|
||||
...nativeCredentialSettings(resolved, specifier, credential),
|
||||
headers: resolved.headers,
|
||||
body: resolved.body,
|
||||
}
|
||||
@@ -282,7 +282,10 @@ function prepareProviderSettings(
|
||||
)
|
||||
}
|
||||
|
||||
function prepareProviderURL(model: RuntimeInfo, baseURL: string): Effect.Effect<string, UnresolvedProviderVariablesError> {
|
||||
function prepareProviderURL(
|
||||
model: RuntimeInfo,
|
||||
baseURL: string,
|
||||
): Effect.Effect<string, UnresolvedProviderVariablesError> {
|
||||
if (!baseURL.includes("${")) return Effect.succeed(baseURL)
|
||||
const prepared = baseURL.replace(/\$\{([^}]+)\}/g, (placeholder, name: string) => process.env[name] ?? placeholder)
|
||||
const failure = unresolvedProviderVariables(model, prepared)
|
||||
@@ -299,17 +302,27 @@ function unresolvedProviderVariables(model: RuntimeInfo, baseURL: string) {
|
||||
})
|
||||
}
|
||||
|
||||
const nativeCredentialSettings = (specifier: string, credential: Credential.Value | undefined) => {
|
||||
if (!credential || credential.type === "external") return {}
|
||||
const nativeCredentialSettings = (model: RuntimeInfo, specifier: string, credential: Credential.Value | undefined) => {
|
||||
if (!credential) return {}
|
||||
if (credential.type === "key") return { apiKey: credential.key }
|
||||
if (credential.type === "oauth") return tokenSettings(specifier, credential.access)
|
||||
// The saved profile reaches the package through metadata; SigV4 keeps an ambient bearer token from taking over.
|
||||
if (specifier.startsWith("@opencode/ai/providers/amazon-bedrock")) return { auth: "sigv4" }
|
||||
// The Azure plugin's request hooks replace this with an Entra ID token from the Azure CLI; it only gets the
|
||||
// request past the package's own credential check.
|
||||
if (model.providerID === Provider.ID.azure) return tokenSettings(specifier, "azure-cli")
|
||||
return {}
|
||||
}
|
||||
|
||||
const tokenSettings = (specifier: string, token: string) => {
|
||||
if (specifier === "@opencode/ai/providers/anthropic" || specifier === "@opencode/ai/providers/anthropic-compatible")
|
||||
return { authToken: credential.access }
|
||||
return { authToken: token }
|
||||
if (
|
||||
specifier === "@opencode/ai/providers/google-vertex" ||
|
||||
specifier.startsWith("@opencode/ai/providers/google-vertex/")
|
||||
)
|
||||
return { accessToken: credential.access }
|
||||
return { apiKey: credential.access }
|
||||
return { accessToken: token }
|
||||
return { apiKey: token }
|
||||
}
|
||||
|
||||
const unsupported = (model: RuntimeInfo) =>
|
||||
|
||||
@@ -286,6 +286,13 @@ export const make = Effect.fn("PluginHost.make")(function* (
|
||||
answer: input.answer,
|
||||
label: input.label,
|
||||
}),
|
||||
external: (input) =>
|
||||
integration.connection.external({
|
||||
integrationID: Integration.ID.make(input.integrationID),
|
||||
methodID: Integration.MethodID.make(input.methodID),
|
||||
answer: input.answer,
|
||||
label: input.label,
|
||||
}),
|
||||
},
|
||||
oauth: {
|
||||
connect: (input) =>
|
||||
@@ -665,6 +672,12 @@ function methodImplementation(input: IntegrationMethodRegistration): Integration
|
||||
method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
|
||||
}
|
||||
}
|
||||
if (input.method.type === "external") {
|
||||
return {
|
||||
integrationID: Integration.ID.make(input.integrationID),
|
||||
method: { ...input.method, id: Integration.MethodID.make(input.method.id) },
|
||||
}
|
||||
}
|
||||
return {
|
||||
integrationID: Integration.ID.make(input.integrationID),
|
||||
method: input.method,
|
||||
|
||||
@@ -11,9 +11,13 @@ import { fileURLToPath, pathToFileURL } from "url"
|
||||
import type { ConfigPluginSource } from "../config/plugin/source.js"
|
||||
import type { Generation } from "../plugin.js"
|
||||
import { PluginPromise } from "./promise.js"
|
||||
import { Config } from "../config.js"
|
||||
import { ManagedPolicy } from "../managed-policy.js"
|
||||
import { Watcher } from "../filesystem/watcher.js"
|
||||
|
||||
export const make = Effect.fn("PluginModule.make")(function* () {
|
||||
const config = yield* Config.Service
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const watcher = yield* Watcher.Service
|
||||
const scope = yield* Effect.scope
|
||||
const runPromise = yield* FiberSet.makeRuntimePromise()
|
||||
@@ -40,7 +44,21 @@ export const make = Effect.fn("PluginModule.make")(function* () {
|
||||
load: (
|
||||
operation: Extract<ConfigPluginSource.Operation, { type: "add" }>,
|
||||
options?: { readonly install?: boolean },
|
||||
) => load(operation, sources, options),
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const version = operation.target.lastIndexOf("@")
|
||||
const target =
|
||||
path.isAbsolute(operation.target) || version <= 0 ? operation.target : operation.target.slice(0, version)
|
||||
if (
|
||||
ManagedPolicy.decision(
|
||||
ManagedPolicy.statements(yield* config.entries(), managed.current()),
|
||||
"integration.use",
|
||||
`plugin:${target}`,
|
||||
) === "deny"
|
||||
)
|
||||
return { blocked: true as const }
|
||||
return yield* load(operation, sources, options)
|
||||
}),
|
||||
changes: () => Stream.fromPubSub(changes),
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { Effect } from "effect"
|
||||
import path from "node:path"
|
||||
import { define } from "@opencode/plugin/effect/plugin"
|
||||
import { FSUtil } from "@opencode/util/fs-util"
|
||||
import { Global } from "@opencode/util/global"
|
||||
import { Provider } from "../../provider.js"
|
||||
|
||||
// Ambient inputs the AWS default credential chain can turn into credentials
|
||||
@@ -19,6 +22,32 @@ const isBedrock = (item: { readonly package: string }) =>
|
||||
export const AmazonBedrockPlugin = define({
|
||||
id: "opencode.provider.amazon.bedrock",
|
||||
effect: Effect.fn(function* (ctx) {
|
||||
const fs = yield* FSUtil.Service
|
||||
const paths = [
|
||||
process.env.AWS_CONFIG_FILE ?? path.join(Global.Path.home, ".aws", "config"),
|
||||
process.env.AWS_SHARED_CREDENTIALS_FILE ?? path.join(Global.Path.home, ".aws", "credentials"),
|
||||
]
|
||||
const files = yield* Effect.all(
|
||||
paths.map((file) => fs.readFileStringSafe(file).pipe(Effect.orElseSucceed(() => undefined))),
|
||||
)
|
||||
// Discover names only. Resolving every profile here could run credential helpers or contact AWS.
|
||||
const profiles = Array.from(
|
||||
new Set(
|
||||
files.flatMap((content, index) =>
|
||||
Array.from((content ?? "").matchAll(/^\s*\[([^\]\r\n]+)\]/gm)).flatMap((match) => {
|
||||
const section = match[1].trim()
|
||||
// The credentials file uses bare names; the config file prefixes all but "default" with "profile ".
|
||||
if (index === 1 || section === "default") return [section]
|
||||
return section.startsWith("profile ") ? [section.slice(8).trim()] : []
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
.filter(Boolean)
|
||||
.toSorted()
|
||||
const sources = paths
|
||||
.map((file) => (file.startsWith(Global.Path.home + path.sep) ? `~${file.slice(Global.Path.home.length)}` : file))
|
||||
.join(" and ")
|
||||
yield* ctx.integration.transform((editor) => {
|
||||
// models.dev advertises AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and
|
||||
// AWS_REGION alongside the bearer token. Only the bearer token is a key;
|
||||
@@ -27,6 +56,34 @@ export const AmazonBedrockPlugin = define({
|
||||
integrationID: Provider.ID.amazonBedrock,
|
||||
method: { type: "env", names: ["AWS_BEARER_TOKEN_BEDROCK"] },
|
||||
})
|
||||
editor.method.update({
|
||||
integrationID: Provider.ID.amazonBedrock,
|
||||
method: { type: "key", label: "Bedrock API key" },
|
||||
})
|
||||
editor.method.update({
|
||||
integrationID: Provider.ID.amazonBedrock,
|
||||
method: {
|
||||
id: "aws-profile",
|
||||
type: "external",
|
||||
label: "AWS profile (SSO or named profile)",
|
||||
form: [
|
||||
{
|
||||
key: "profile",
|
||||
type: "string",
|
||||
title: "AWS profile",
|
||||
description: profiles.length
|
||||
? `Found ${profiles.length} profile${profiles.length === 1 ? "" : "s"} in ${sources} on the server.`
|
||||
: `No AWS profiles found in ${sources} on the server.`,
|
||||
required: true,
|
||||
minLength: 1,
|
||||
pattern: "\\S",
|
||||
placeholder: "Profile name",
|
||||
custom: true,
|
||||
options: profiles.map((profile) => ({ value: profile, label: profile })),
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
})
|
||||
yield* ctx.provider.transform((evt) => {
|
||||
for (const item of evt.list()) {
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { Clock, Effect, FiberHandle, Option, Schema, Semaphore, Stream } from "effect"
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
|
||||
import { ChildProcess } from "effect/unstable/process"
|
||||
import path from "node:path"
|
||||
import { define } from "@opencode/plugin/effect/plugin"
|
||||
import { Form } from "@opencode/schema/form"
|
||||
import { FSUtil } from "@opencode/util/fs-util"
|
||||
import { Global } from "@opencode/util/global"
|
||||
import { AppProcess } from "@opencode/util/process"
|
||||
import { App } from "../../app.js"
|
||||
import { Bus } from "../../bus.js"
|
||||
@@ -49,8 +52,18 @@ const decodeManagementDeployment = Schema.decodeUnknownOption(
|
||||
}),
|
||||
}),
|
||||
)
|
||||
const ResourceQuery = Schema.Struct({ query: Schema.String })
|
||||
const ResourceQuery = Schema.Struct({
|
||||
query: Schema.String,
|
||||
options: Schema.optional(Schema.Struct({ $top: Schema.Number })),
|
||||
})
|
||||
const Resources = Schema.Struct({ data: Schema.Array(Schema.Struct({ id: Schema.NonEmptyString })) })
|
||||
const ResourceListing = Schema.Struct({ data: Schema.Array(Schema.Unknown) })
|
||||
const decodeProfile = Schema.decodeUnknownOption(
|
||||
Schema.fromJsonString(Schema.Struct({ subscriptions: Schema.NonEmptyArray(Schema.Unknown) })),
|
||||
)
|
||||
const decodeResourceListing = Schema.decodeUnknownOption(
|
||||
Schema.Struct({ resourceName: Schema.NonEmptyString, resourceGroup: Schema.String, location: Schema.String }),
|
||||
)
|
||||
|
||||
type Deployment = { readonly name: string; readonly model: string }
|
||||
|
||||
@@ -65,6 +78,7 @@ export function make(
|
||||
effect: Effect.fn(function* (ctx) {
|
||||
const configured = yield* configuredSettings(Provider.ID.azure)
|
||||
const processes = yield* AppProcess.Service
|
||||
const fs = yield* FSUtil.Service
|
||||
const bus = yield* Bus.Service
|
||||
const credentials = yield* Credential.Service
|
||||
const providers = yield* Provider.Service
|
||||
@@ -118,61 +132,59 @@ export function make(
|
||||
)
|
||||
|
||||
const available = Boolean(which("az"))
|
||||
const form = () =>
|
||||
iife(() => {
|
||||
if (resolveResourceName(configured) || typeof configured?.baseURL === "string") return
|
||||
return Form.Fields.make([
|
||||
{
|
||||
type: "string",
|
||||
key: "resourceName",
|
||||
title: "Enter Azure Resource Name",
|
||||
placeholder: "e.g. my-models",
|
||||
required: true,
|
||||
},
|
||||
])
|
||||
})
|
||||
const configuredResource = Boolean(resolveResourceName(configured) || typeof configured?.baseURL === "string")
|
||||
// Undefined until the Azure CLI answers; a failed lookup leaves the form to manual entry.
|
||||
const listing: { resources?: readonly Form.Option[] } = {}
|
||||
|
||||
yield* ctx.integration.transform((editor) => {
|
||||
editor.method.update({
|
||||
integrationID: Provider.ID.azure,
|
||||
method: { type: "key", label: "API key", form: form() },
|
||||
method: {
|
||||
type: "key",
|
||||
label: "API key",
|
||||
form: configuredResource
|
||||
? undefined
|
||||
: Form.Fields.make([
|
||||
{
|
||||
type: "string",
|
||||
key: "resourceName",
|
||||
title: "Enter Azure Resource Name",
|
||||
placeholder: "e.g. my-models",
|
||||
required: true,
|
||||
},
|
||||
]),
|
||||
},
|
||||
})
|
||||
if (!available) return
|
||||
editor.method.update({
|
||||
integrationID: Provider.ID.azure,
|
||||
method: {
|
||||
id: methodID,
|
||||
type: "oauth",
|
||||
type: "external",
|
||||
label: "Microsoft Entra ID (Azure CLI)",
|
||||
form: form(),
|
||||
form: configuredResource
|
||||
? undefined
|
||||
: Form.Fields.make([
|
||||
{
|
||||
type: "string",
|
||||
key: "resourceName",
|
||||
title: "Azure resource",
|
||||
placeholder: "e.g. my-models",
|
||||
required: true,
|
||||
pattern: resourcePattern.source,
|
||||
// Resources are listed once at startup, so one created later is typed in. Without a list the field
|
||||
// is a plain text input.
|
||||
...iife(() => {
|
||||
if (!listing.resources) return { description: "Requests use your `az login` session." }
|
||||
if (listing.resources.length === 0)
|
||||
return {
|
||||
description: "No Azure OpenAI or AI Services resources found for your `az login` account.",
|
||||
}
|
||||
return { custom: true, options: listing.resources }
|
||||
}),
|
||||
},
|
||||
]),
|
||||
},
|
||||
authorize: (answer) =>
|
||||
Effect.succeed({
|
||||
mode: "auto" as const,
|
||||
url: "",
|
||||
instructions: "Sign in with `az login` before continuing.",
|
||||
callback: Effect.gen(function* () {
|
||||
const resourceName =
|
||||
(typeof answer.resourceName === "string" ? answer.resourceName.trim() : "") ||
|
||||
resolveResourceName(configured)
|
||||
if (!resourceName) return yield* Effect.fail(new Error("Azure resource name is required"))
|
||||
const current = yield* token(cognitiveScope)
|
||||
return Credential.OAuth.make({
|
||||
type: "oauth",
|
||||
methodID,
|
||||
access: current.access,
|
||||
refresh: "azure-cli",
|
||||
expires: current.expires,
|
||||
metadata: { resourceName },
|
||||
})
|
||||
}),
|
||||
}),
|
||||
refresh: (credential) =>
|
||||
token(cognitiveScope).pipe(
|
||||
Effect.map((current) =>
|
||||
Credential.OAuth.make({ ...credential, access: current.access, expires: current.expires }),
|
||||
),
|
||||
),
|
||||
})
|
||||
})
|
||||
|
||||
@@ -235,7 +247,7 @@ export function make(
|
||||
|
||||
const resourceDeployments = Effect.fn("AzurePlugin.resourceDeployments")(function* (
|
||||
url: string,
|
||||
credential: Credential.Key | Credential.OAuth,
|
||||
credential: Credential.Key | Credential.External,
|
||||
) {
|
||||
return yield* http
|
||||
.execute(
|
||||
@@ -244,7 +256,7 @@ export function make(
|
||||
HttpClientRequest.setHeader("User-Agent", App.useragent(ctx.app)),
|
||||
credential.type === "key"
|
||||
? HttpClientRequest.setHeader("api-key", credential.key)
|
||||
: HttpClientRequest.bearerToken(credential.access),
|
||||
: HttpClientRequest.bearerToken((yield* token(cognitiveScope)).access),
|
||||
),
|
||||
)
|
||||
.pipe(
|
||||
@@ -266,8 +278,8 @@ export function make(
|
||||
// data-plane version 2022-12-01 has it; later versions dropped `/deployments` and keep `/models`, which lists
|
||||
// models the resource can deploy rather than its deployments.
|
||||
// https://github.com/Azure/azure-rest-api-specs/blob/main/specification/cognitiveservices/data-plane/OpenAIAuthoring/stable/2022-12-01/azureopenai.json
|
||||
const deployments = (url: string, resource: string, credential: Credential.Key | Credential.OAuth) =>
|
||||
credential.type === "oauth"
|
||||
const deployments = (url: string, resource: string, credential: Credential.Key | Credential.External) =>
|
||||
credential.type === "external"
|
||||
? managementDeployments(resource).pipe(Effect.catch(() => resourceDeployments(url, credential)))
|
||||
: resourceDeployments(url, credential)
|
||||
|
||||
@@ -310,8 +322,8 @@ export function make(
|
||||
.pipe(Effect.orElseSucceed(() => undefined))
|
||||
if (
|
||||
!credential ||
|
||||
credential.type === "external" ||
|
||||
(credential.type === "oauth" && credential.methodID !== methodID)
|
||||
credential.type === "oauth" ||
|
||||
(credential.type === "external" && credential.methodID !== methodID)
|
||||
)
|
||||
return
|
||||
const found = yield* deployments(url, name, credential).pipe(
|
||||
@@ -353,6 +365,43 @@ export function make(
|
||||
: resolveResourceName(provider.settings, loaded.resource)
|
||||
|
||||
Object.assign(loaded, yield* load())
|
||||
|
||||
// Lists the resources the Azure CLI account can reach in the background, so the connect form can offer them
|
||||
// without startup waiting on Azure. The CLI's profile shows a signed-in account without running the CLI.
|
||||
// https://learn.microsoft.com/cli/azure/azure-cli-configuration#cli-configuration-file
|
||||
const listResources = Effect.fn("AzurePlugin.listResources")(function* () {
|
||||
const profile = yield* fs.readFileStringSafe(
|
||||
path.join(process.env.AZURE_CONFIG_DIR ?? path.join(Global.Path.home, ".azure"), "azureProfile.json"),
|
||||
)
|
||||
// The Azure CLI writes the profile with a byte order mark.
|
||||
if (Option.isNone(decodeProfile(profile?.replace(/^\uFEFF/, "")))) return
|
||||
const response = yield* HttpClientRequest.post(
|
||||
`${endpoints.management}/providers/Microsoft.ResourceGraph/resources?api-version=2022-10-01`,
|
||||
).pipe(
|
||||
HttpClientRequest.schemaBodyJson(ResourceQuery)({ query: resourceListQuery, options: { $top: 1000 } }),
|
||||
Effect.flatMap(management),
|
||||
Effect.flatMap(HttpClientResponse.schemaBodyJson(ResourceListing)),
|
||||
Effect.timeout("10 seconds"),
|
||||
)
|
||||
listing.resources = response.data.flatMap((raw): Form.Option[] => {
|
||||
const item = Option.getOrUndefined(decodeResourceListing(raw))
|
||||
if (!item || !resourcePattern.test(item.resourceName)) return []
|
||||
return [
|
||||
{
|
||||
value: item.resourceName,
|
||||
label: item.resourceName,
|
||||
description: `${item.resourceGroup} · ${item.location}`,
|
||||
},
|
||||
]
|
||||
})
|
||||
yield* ctx.integration.reload()
|
||||
})
|
||||
if (available && !configuredResource)
|
||||
yield* listResources().pipe(
|
||||
Effect.catch((cause) => Effect.logDebug("failed to list Azure resources", { cause })),
|
||||
Effect.forkScoped,
|
||||
)
|
||||
|
||||
yield* ctx.provider.transform((evt) => {
|
||||
for (const item of evt.list()) {
|
||||
if (
|
||||
@@ -432,7 +481,7 @@ export function make(
|
||||
const credential = connection
|
||||
? yield* ctx.integration.connection.resolve(connection).pipe(Effect.orElseSucceed(() => undefined))
|
||||
: undefined
|
||||
if (credential?.type !== "oauth" || credential.methodID !== methodID) return
|
||||
if (credential?.type !== "external" || credential.methodID !== methodID) return
|
||||
const target = new URL(url)
|
||||
const scope =
|
||||
target.hostname.endsWith(".services.ai.azure.com") && !target.pathname.startsWith("/models")
|
||||
@@ -493,12 +542,23 @@ function credentialResource(credential: Credential.Value | undefined) {
|
||||
const resource =
|
||||
credential?.type === "key"
|
||||
? (credential.configuration?.resourceName ?? credential.metadata?.resourceName)
|
||||
: credential?.methodID === methodID
|
||||
: credential?.type === "external" && credential.methodID === methodID
|
||||
? credential.metadata?.resourceName
|
||||
: undefined
|
||||
return typeof resource === "string" && resource.trim() !== "" ? resource : undefined
|
||||
}
|
||||
|
||||
// Entra ID authentication requires a custom subdomain, which is the resource name every endpoint uses.
|
||||
// https://learn.microsoft.com/azure/ai-services/cognitive-services-custom-subdomains
|
||||
const resourceListQuery = [
|
||||
"resources",
|
||||
"| where type =~ 'microsoft.cognitiveservices/accounts' and kind in~ ('AIServices', 'OpenAI')",
|
||||
"| extend resourceName = tostring(properties.customSubDomainName)",
|
||||
"| where isnotempty(resourceName)",
|
||||
"| project resourceName, resourceGroup, location",
|
||||
"| order by resourceName asc",
|
||||
].join(" ")
|
||||
|
||||
function resourceQuery(resource: string) {
|
||||
return [
|
||||
"resources",
|
||||
|
||||
@@ -13,6 +13,7 @@ import { Integration } from "../../integration.js"
|
||||
import { Model } from "../../model.js"
|
||||
import { OauthCallbackPage } from "../../oauth/page.js"
|
||||
import { Provider } from "../../provider.js"
|
||||
import { SessionAffinity } from "../../session/affinity.js"
|
||||
import type { PluginInternal } from "../internal.js"
|
||||
|
||||
// First-time sign-in registers a user-owned client; OpenAI returns its issued client ID on the callback.
|
||||
@@ -264,6 +265,21 @@ export const ChatGPTPlugin = define({
|
||||
}),
|
||||
{ providerID },
|
||||
)
|
||||
yield* ctx.session.hook(
|
||||
"model.request",
|
||||
(evt) =>
|
||||
Effect.gen(function* () {
|
||||
if (!chatgpt) return
|
||||
const session = yield* ctx.session
|
||||
.get({ sessionID: evt.sessionID })
|
||||
.pipe(Effect.orElseSucceed(() => undefined))
|
||||
// Mirror the Codex client's session headers: ChatGPT derives prompt-cache affinity from session-id.
|
||||
evt.headers["session-id"] = session ? SessionAffinity.get(session) : evt.sessionID
|
||||
evt.headers["thread-id"] = evt.sessionID
|
||||
evt.headers["x-client-request-id"] = evt.sessionID
|
||||
}),
|
||||
{ providerID },
|
||||
)
|
||||
yield* ctx.provider.transform((providers) => {
|
||||
const item = providers.get(providerID)
|
||||
if (!item) return
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Duration, Effect, Equal, Option, Schema, Scope, Semaphore, Stream } from "effect"
|
||||
import { Duration, Effect, Equal, Option, Schema, SchemaGetter, Scope, Semaphore, Stream } from "effect"
|
||||
import type { IntegrationOAuthMethodRegistration } from "@opencode/plugin/effect/integration"
|
||||
import { define } from "@opencode/plugin/effect/plugin"
|
||||
import type { SessionHttpResponse } from "@opencode/plugin/effect/session"
|
||||
@@ -36,7 +36,20 @@ const RemoteResponse = Schema.Struct({
|
||||
}).pipe(Schema.optional),
|
||||
// Organization policy compiled for the authenticated caller; omitted when there is none.
|
||||
experimental: Schema.Struct({
|
||||
policies: Schema.Array(ConfigPolicy.Info).pipe(Schema.optional),
|
||||
policies: Schema.Array(Schema.Unknown).pipe(
|
||||
Schema.decodeTo(Schema.Unknown, {
|
||||
// Filter only unsupported actions. Malformed supported statements still fail validation.
|
||||
decode: SchemaGetter.transform((policies) =>
|
||||
policies.filter((policy) => {
|
||||
const action = Schema.decodeUnknownOption(Schema.Struct({ action: Schema.String }))(policy)
|
||||
return Option.isNone(action) || Schema.is(ConfigPolicy.Info.fields.action)(action.value.action)
|
||||
}),
|
||||
),
|
||||
encode: SchemaGetter.passthrough({ strict: false }),
|
||||
}),
|
||||
Schema.decodeTo(Schema.Array(ConfigPolicy.Info)),
|
||||
Schema.optional,
|
||||
),
|
||||
}).pipe(Schema.optional),
|
||||
})
|
||||
const Device = Schema.Struct({
|
||||
@@ -462,11 +475,7 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Manag
|
||||
|
||||
// Console config can change independently of local credential activity, so re-fetch
|
||||
// periodically and only rebuild the catalog and search providers when the snapshot differs.
|
||||
yield* Effect.sleep(Duration.minutes(1)).pipe(
|
||||
Effect.andThen(check()),
|
||||
Effect.forever,
|
||||
Effect.forkScoped,
|
||||
)
|
||||
yield* Effect.sleep(Duration.minutes(1)).pipe(Effect.andThen(check()), Effect.forever, Effect.forkScoped)
|
||||
}),
|
||||
})
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Cause, Effect, Layer, Queue, Stream } from "effect"
|
||||
import path from "path"
|
||||
import { ConfigPluginSource } from "../config/plugin/source.js"
|
||||
import { makeLocationNode } from "@opencode/util/effect/app-node"
|
||||
import { ManagedPolicy } from "../managed-policy.js"
|
||||
import { Bus } from "../bus.js"
|
||||
import { Npm } from "@opencode/util/npm"
|
||||
import { Plugin } from "../plugin.js"
|
||||
@@ -64,6 +65,13 @@ const resolve = Effect.fn("PluginSupervisor.resolve")(function* (
|
||||
)
|
||||
}),
|
||||
)
|
||||
if ("blocked" in plugin) {
|
||||
const previous = packages.get(operation.target)
|
||||
if (previous) enabled.delete(previous.id)
|
||||
packages.delete(operation.target)
|
||||
failures.delete(operation.target)
|
||||
continue
|
||||
}
|
||||
if ("pending" in plugin) {
|
||||
pending.add(operation.target)
|
||||
continue
|
||||
@@ -115,6 +123,7 @@ const resolve = Effect.fn("PluginSupervisor.resolve")(function* (
|
||||
|
||||
export const layer = Layer.effectDiscard(
|
||||
Effect.gen(function* () {
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const registry = yield* Plugin.Service
|
||||
const sdk = yield* SdkPlugins.Service
|
||||
const instance = yield* InstancePlugins.Service
|
||||
@@ -209,6 +218,7 @@ export const layer = Layer.effectDiscard(
|
||||
)
|
||||
yield* watch(sources.changes())
|
||||
yield* watch(modules.changes())
|
||||
yield* watch(managed.changes())
|
||||
yield* watch(Stream.fromEffectRepeat(Effect.sleep("24 hours")))
|
||||
yield* watch(bus.subscribe([Event.Updated, SdkPlugins.Updated]))
|
||||
yield* watch(
|
||||
|
||||
@@ -174,8 +174,6 @@ export interface Interface {
|
||||
readonly switchAgent: (input: { sessionID: SessionSchema.ID; agent: Agent.ID }) => Effect.Effect<void, NotFoundError>
|
||||
readonly switchModel: (input: { sessionID: SessionSchema.ID; model: Model.Ref }) => Effect.Effect<void, NotFoundError>
|
||||
readonly rename: (input: { sessionID: SessionSchema.ID; title: string }) => Effect.Effect<void, NotFoundError>
|
||||
readonly archive: (sessionID: SessionSchema.ID) => Effect.Effect<void, NotFoundError>
|
||||
readonly unarchive: (sessionID: SessionSchema.ID) => Effect.Effect<void, NotFoundError>
|
||||
readonly setMetadata: (input: {
|
||||
sessionID: SessionSchema.ID
|
||||
metadata: SessionSchema.Metadata
|
||||
@@ -435,8 +433,6 @@ const layer = Layer.effect(
|
||||
switchAgent: (input) => sessions.forSession(input.sessionID).switchAgent(input),
|
||||
switchModel: (input) => sessions.forSession(input.sessionID).switchModel(input),
|
||||
rename: (input) => sessions.forSession(input.sessionID).rename(input),
|
||||
archive: (sessionID) => sessions.forSession(sessionID).archive(),
|
||||
unarchive: (sessionID) => sessions.forSession(sessionID).unarchive(),
|
||||
setMetadata: (input) => sessions.forSession(input.sessionID).setMetadata(input),
|
||||
setPermissions: (input) => sessions.forSession(input.sessionID).setPermissions(input),
|
||||
move: moves.move,
|
||||
|
||||
@@ -58,7 +58,7 @@ export function fromRow(row: typeof SessionTable.$inferSelect): SessionSchema.In
|
||||
updated: DateTime.makeUnsafe(row.time_updated),
|
||||
idle: row.time_idle === null ? undefined : DateTime.makeUnsafe(row.time_idle),
|
||||
viewed: row.time_viewed === null ? undefined : DateTime.makeUnsafe(row.time_viewed),
|
||||
archived: row.time_archived === null ? undefined : DateTime.makeUnsafe(row.time_archived),
|
||||
archived: row.time_archived ? DateTime.makeUnsafe(row.time_archived) : undefined,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -80,8 +80,6 @@ export function update(adapter: Adapter, event: SessionEvent.DurableEvent) {
|
||||
Match.discriminatorsExhaustive("type")({
|
||||
"session.created": () => Effect.void,
|
||||
"session.viewed": () => Effect.void,
|
||||
"session.archived": () => Effect.void,
|
||||
"session.unarchived": () => Effect.void,
|
||||
"session.message.content.updated": (event) =>
|
||||
updateOwnedAssistant(event.data.messageID, (draft) => {
|
||||
draft.content = castDraft(
|
||||
|
||||
@@ -126,10 +126,24 @@ const mimeToModality = (mime: string) => {
|
||||
if (mime === "application/pdf") return "pdf"
|
||||
}
|
||||
|
||||
const unsupportedMedia = (mime: string, name: string | undefined, capabilities: Model.Capabilities) => {
|
||||
// xAI rejects any other image type (e.g. GIF) with invalid_image, and the stored image would fail every later turn.
|
||||
const XAI_IMAGE_MIMES = new Set(["image/png", "image/jpeg", "image/webp"])
|
||||
|
||||
const unsupportedMedia = (
|
||||
mime: string,
|
||||
name: string | undefined,
|
||||
capabilities: Model.Capabilities,
|
||||
provider: string | undefined,
|
||||
) => {
|
||||
const modality = mimeToModality(mime)
|
||||
if (!modality || capabilities.input.some((item) => item.startsWith(modality))) return
|
||||
return `ERROR: Cannot read ${name ? `"${name}"` : modality} (this model does not support ${modality} input). Inform the user.`
|
||||
if (!modality) return
|
||||
const unsupported = !capabilities.input.some((item) => item.startsWith(modality))
|
||||
? modality
|
||||
: provider === "xai" && modality === "image" && !XAI_IMAGE_MIMES.has(mime.toLowerCase())
|
||||
? mime
|
||||
: undefined
|
||||
if (!unsupported) return
|
||||
return `ERROR: Cannot read ${name ? `"${name}"` : modality} (this model does not support ${unsupported} input). Inform the user.`
|
||||
}
|
||||
|
||||
// Remote and provider-referenced media carry no local payload and never count toward the inline budget.
|
||||
@@ -166,8 +180,11 @@ const replaceMedia = (
|
||||
: new Message({ ...message, content })
|
||||
})
|
||||
|
||||
export const unsupportedParts = (messages: LLMRequest["messages"], capabilities: Model.Capabilities) =>
|
||||
replaceMedia(messages, (media) => unsupportedMedia(media.mime, media.name, capabilities))
|
||||
export const unsupportedParts = (
|
||||
messages: LLMRequest["messages"],
|
||||
capabilities: Model.Capabilities,
|
||||
provider?: string,
|
||||
) => replaceMedia(messages, (media) => unsupportedMedia(media.mime, media.name, capabilities, provider))
|
||||
|
||||
export const boundImages = (messages: LLMRequest["messages"]) => {
|
||||
const isImage = (mime: string) => mime.toLowerCase().startsWith("image/")
|
||||
@@ -277,7 +294,7 @@ export const layer = Layer.effect(
|
||||
// TODO: Persist cache lineage so nested forks reuse the root session's cache key.
|
||||
promptCacheKey: /^ses_[0-9a-f]{64}$/.test(affinity) ? affinity.slice(4) : affinity,
|
||||
system: shaped.system,
|
||||
messages: boundImages(unsupportedParts(shaped.messages, model.capabilities)),
|
||||
messages: boundImages(unsupportedParts(shaped.messages, model.capabilities, model.model.provider)),
|
||||
tools: Array.from(hooked, ([name, t]) => ({ ...t, name })),
|
||||
toolChoice: input.toolChoice,
|
||||
generation: Object.keys(generation).length === 0 ? undefined : generation,
|
||||
|
||||
@@ -55,7 +55,7 @@ const forkTitle = (value?: string) => {
|
||||
return `${value} (fork #1)`
|
||||
}
|
||||
|
||||
function applyUsage(db: DatabaseService, sessionID: SessionSchema.ID, value: Usage) {
|
||||
function applyUsage(db: DatabaseService, sessionID: SessionSchema.ID, value: Usage, timeUpdated?: number) {
|
||||
return db
|
||||
.update(SessionTable)
|
||||
.set({
|
||||
@@ -65,13 +65,22 @@ function applyUsage(db: DatabaseService, sessionID: SessionSchema.ID, value: Usa
|
||||
tokens_reasoning: sql`${SessionTable.tokens_reasoning} + ${value.tokens.reasoning}`,
|
||||
tokens_cache_read: sql`${SessionTable.tokens_cache_read} + ${value.tokens.cache.read}`,
|
||||
tokens_cache_write: sql`${SessionTable.tokens_cache_write} + ${value.tokens.cache.write}`,
|
||||
time_updated: sql`${SessionTable.time_updated}`,
|
||||
time_updated: timeUpdated ?? sql`${SessionTable.time_updated}`,
|
||||
})
|
||||
.where(eq(SessionTable.id, sessionID))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
}
|
||||
|
||||
function touch(db: DatabaseService, event: MessageEvent) {
|
||||
return db
|
||||
.update(SessionTable)
|
||||
.set({ time_updated: event.created })
|
||||
.where(eq(SessionTable.id, event.data.sessionID))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
}
|
||||
|
||||
const publishSessionUsage = Effect.fn("SessionProjector.publishUsage")(function* (
|
||||
db: DatabaseService,
|
||||
bus: Bus.Interface,
|
||||
@@ -603,22 +612,6 @@ const layer = Layer.effectDiscard(
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
})
|
||||
yield* bus.project(SessionEvent.Archived, (event) =>
|
||||
db
|
||||
.update(SessionTable)
|
||||
.set({ time_archived: event.created, time_updated: event.created })
|
||||
.where(eq(SessionTable.id, event.data.sessionID))
|
||||
.run()
|
||||
.pipe(Effect.orDie),
|
||||
)
|
||||
yield* bus.project(SessionEvent.Unarchived, (event) =>
|
||||
db
|
||||
.update(SessionTable)
|
||||
.set({ time_archived: null, time_updated: event.created })
|
||||
.where(eq(SessionTable.id, event.data.sessionID))
|
||||
.run()
|
||||
.pipe(Effect.orDie),
|
||||
)
|
||||
yield* bus.project(SessionEvent.MessageContentUpdated, (event) => run(db, event))
|
||||
yield* bus.project(SessionEvent.UsageRecorded, (event) => applyUsage(db, event.data.sessionID, event.data))
|
||||
yield* bus.project(SessionEvent.Forked, (event) => projectFork(db, event))
|
||||
@@ -697,19 +690,30 @@ const layer = Layer.effectDiscard(
|
||||
yield* bus.project(SessionEvent.Skill.Activated, (event) => run(db, event))
|
||||
yield* bus.project(SessionEvent.Shell.Started, (event) => run(db, event))
|
||||
yield* bus.project(SessionEvent.Shell.Ended, (event) => run(db, event))
|
||||
yield* bus.project(SessionEvent.Step.Started, (event) => run(db, event))
|
||||
yield* bus.project(SessionEvent.Step.Started, (event) =>
|
||||
Effect.gen(function* () {
|
||||
yield* run(db, event)
|
||||
yield* touch(db, event)
|
||||
}),
|
||||
)
|
||||
yield* bus.project(SessionEvent.Step.Streamed, (event) => run(db, event))
|
||||
yield* bus.project(SessionEvent.Step.Ended, (event) =>
|
||||
Effect.gen(function* () {
|
||||
yield* run(db, event)
|
||||
yield* applyUsage(db, event.data.sessionID, event.data)
|
||||
yield* applyUsage(db, event.data.sessionID, event.data, event.created)
|
||||
}),
|
||||
)
|
||||
yield* bus.project(SessionEvent.Step.Failed, (event) =>
|
||||
Effect.gen(function* () {
|
||||
yield* run(db, event)
|
||||
if (event.data.cost !== undefined && event.data.tokens !== undefined)
|
||||
yield* applyUsage(db, event.data.sessionID, { cost: event.data.cost, tokens: event.data.tokens })
|
||||
yield* applyUsage(
|
||||
db,
|
||||
event.data.sessionID,
|
||||
{ cost: event.data.cost, tokens: event.data.tokens },
|
||||
event.created,
|
||||
)
|
||||
else yield* touch(db, event)
|
||||
}),
|
||||
)
|
||||
yield* bus.project(SessionEvent.Text.Started, (event) => run(db, event))
|
||||
|
||||
@@ -72,16 +72,6 @@ export const make = Effect.fn("Session.make")(function* () {
|
||||
yield* get(sessionID)
|
||||
yield* bus.publish(SessionEvent.Renamed, { sessionID, title: input.title })
|
||||
})
|
||||
const archive = Effect.fn("Session.archive")(function* (sessionID: SessionSchema.ID) {
|
||||
const session = yield* get(sessionID)
|
||||
if (session.time.archived) return
|
||||
yield* bus.publish(SessionEvent.Archived, { sessionID })
|
||||
})
|
||||
const unarchive = Effect.fn("Session.unarchive")(function* (sessionID: SessionSchema.ID) {
|
||||
const session = yield* get(sessionID)
|
||||
if (!session.time.archived) return
|
||||
yield* bus.publish(SessionEvent.Unarchived, { sessionID })
|
||||
})
|
||||
const setMetadata = Effect.fn("Session.setMetadata")(function* (
|
||||
sessionID: SessionSchema.ID,
|
||||
input: { metadata: SessionSchema.Metadata },
|
||||
@@ -358,8 +348,6 @@ export const make = Effect.fn("Session.make")(function* () {
|
||||
message,
|
||||
view,
|
||||
rename,
|
||||
archive,
|
||||
unarchive,
|
||||
setMetadata,
|
||||
setPermissions,
|
||||
switchAgent,
|
||||
@@ -384,8 +372,6 @@ export const make = Effect.fn("Session.make")(function* () {
|
||||
const message = operations.message.bind(undefined, sessionID)
|
||||
const view = operations.view.bind(undefined, sessionID)
|
||||
const rename = operations.rename.bind(undefined, sessionID)
|
||||
const archive = operations.archive.bind(undefined, sessionID)
|
||||
const unarchive = operations.unarchive.bind(undefined, sessionID)
|
||||
const setMetadata = operations.setMetadata.bind(undefined, sessionID)
|
||||
const setPermissions = operations.setPermissions.bind(undefined, sessionID)
|
||||
const switchAgent = operations.switchAgent.bind(undefined, sessionID)
|
||||
@@ -413,8 +399,6 @@ export const make = Effect.fn("Session.make")(function* () {
|
||||
message,
|
||||
view,
|
||||
rename,
|
||||
archive,
|
||||
unarchive,
|
||||
setMetadata,
|
||||
setPermissions,
|
||||
switchAgent,
|
||||
|
||||
@@ -20,7 +20,6 @@ const ListInputBase = {
|
||||
limit: PositiveInt.pipe(Schema.optional),
|
||||
order: Schema.Literals(["asc", "desc"]).pipe(Schema.optional),
|
||||
parentID: Schema.NullOr(Session.ID).pipe(Schema.optional),
|
||||
archived: Schema.Boolean.pipe(Schema.optional),
|
||||
anchor: Session.ListAnchor.pipe(Schema.optional),
|
||||
}
|
||||
|
||||
@@ -112,8 +111,6 @@ const layer = Layer.effect(
|
||||
conditions.push(
|
||||
input.parentID === null ? isNull(SessionTable.parent_id) : eq(SessionTable.parent_id, input.parentID),
|
||||
)
|
||||
if (input.archived !== undefined)
|
||||
conditions.push(input.archived ? isNotNull(SessionTable.time_archived) : isNull(SessionTable.time_archived))
|
||||
if (input.anchor) {
|
||||
conditions.push(
|
||||
order === "asc"
|
||||
|
||||
@@ -8,6 +8,7 @@ export * as WriteTool from "./write.js"
|
||||
|
||||
import type { Context } from "@opencode/plugin/effect/plugin"
|
||||
import { ToolFailure } from "@opencode/ai"
|
||||
import { FileDiff } from "@opencode/schema/file-diff"
|
||||
import { Effect, Schema } from "effect"
|
||||
import { Bom } from "@opencode/util/bom"
|
||||
import { Environment } from "../../environment/index.js"
|
||||
@@ -32,6 +33,7 @@ export const Output = Schema.Struct({
|
||||
target: Schema.String,
|
||||
resource: Schema.String,
|
||||
existed: Schema.Boolean,
|
||||
files: Schema.Array(FileDiff.Info),
|
||||
})
|
||||
export type Output = typeof Output.Type
|
||||
|
||||
@@ -85,13 +87,18 @@ export const Plugin = {
|
||||
source,
|
||||
})
|
||||
const result = yield* fileMutation.writeTextPreservingBom({ target, content: input.content })
|
||||
const bom = (yield* FileMutation.readText(environment.files, target.absolute)).bom
|
||||
if (yield* formatter.file(target.absolute)) {
|
||||
yield* FileMutation.syncTextBom(environment.files, target.absolute, bom)
|
||||
}
|
||||
return result
|
||||
const written = yield* FileMutation.readText(environment.files, target.absolute)
|
||||
const formatted = (yield* formatter.file(target.absolute))
|
||||
? yield* FileMutation.syncTextBom(environment.files, target.absolute, written.bom)
|
||||
: written.text
|
||||
return {
|
||||
...result,
|
||||
files: [
|
||||
fileDiff(result.resource, current?.text ?? "", formatted, result.existed ? "modified" : "added"),
|
||||
],
|
||||
} satisfies Output
|
||||
}).pipe(
|
||||
Effect.map((output) => ({ output, content: toModelContent(output) })),
|
||||
Effect.map((output) => ({ output, content: toModelContent(output), metadata: { files: output.files } })),
|
||||
Effect.mapError((error) => new ToolFailure({ message: `Unable to write ${input.path}`, error })),
|
||||
),
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { ConfigMarkdown } from "@opencode/core/config/markdown"
|
||||
|
||||
const invalidYaml = `---
|
||||
description: Use when the user needs to crawl pages. Keywords: crawl, scrape
|
||||
---
|
||||
body`
|
||||
|
||||
describe("ConfigMarkdown.parse", () => {
|
||||
test("recovers unquoted-colon frontmatter via the sanitize fallback", () => {
|
||||
const parsed = ConfigMarkdown.parse(invalidYaml)
|
||||
expect(parsed.data.description).toBe("Use when the user needs to crawl pages. Keywords: crawl, scrape")
|
||||
expect(parsed.content.trim()).toBe("body")
|
||||
})
|
||||
|
||||
test("recovers the same content again after a previous failed parse", () => {
|
||||
// gray-matter caches by content before parsing; a poisoned entry used to
|
||||
// make every later parse of the same text return silently without data.
|
||||
expect(() => ConfigMarkdown.parse("---\ndescription: [unclosed\n---\nbody")).toThrow()
|
||||
const parsed = ConfigMarkdown.parse(invalidYaml)
|
||||
expect(parsed.data.description).toBe("Use when the user needs to crawl pages. Keywords: crawl, scrape")
|
||||
})
|
||||
|
||||
test("keeps throwing for the same unparseable content on every call", () => {
|
||||
const input = "---\ndescription: [unclosed\n---\nbody"
|
||||
expect(() => ConfigMarkdown.parse(input)).toThrow()
|
||||
expect(() => ConfigMarkdown.parse(input)).toThrow()
|
||||
})
|
||||
|
||||
test("parses plain content without frontmatter", () => {
|
||||
const parsed = ConfigMarkdown.parse("just body")
|
||||
expect(parsed.content).toBe("just body")
|
||||
expect(parsed.data).toEqual({})
|
||||
})
|
||||
})
|
||||
@@ -49,6 +49,35 @@ function withoutEmptyCompatibilityContainers(input: Record<string, unknown>) {
|
||||
}
|
||||
|
||||
describe("ConfigNormalize", () => {
|
||||
test("accepts tool.use without losing statement order", () => {
|
||||
const policies = [
|
||||
{ action: "tool.use", effect: "deny", resource: "shell:*" },
|
||||
{ action: "tool.use", effect: "allow", resource: "shell:git *" },
|
||||
{ action: "tool.use", effect: "deny", resource: "shell:git push *" },
|
||||
] as const
|
||||
const result = normalized({ experimental: { policies } })
|
||||
expect(result.diagnostics).toEqual([])
|
||||
expect(Schema.decodeUnknownSync(Info)(result.encoded).experimental?.policies).toEqual(policies)
|
||||
})
|
||||
|
||||
test("drops unsupported policy actions without losing supported policies", () => {
|
||||
const supported = { action: "tool.use", effect: "deny", resource: "shell:*" } as const
|
||||
const result = normalized({
|
||||
experimental: {
|
||||
policies: [
|
||||
{ action: "permission", effect: "allow", resource: "*" },
|
||||
supported,
|
||||
{ action: "future.use", effect: "deny", resource: "*" },
|
||||
],
|
||||
},
|
||||
})
|
||||
expect(Schema.decodeUnknownSync(Info)(result.encoded).experimental?.policies).toEqual([supported])
|
||||
expect(result.diagnostics.map((diagnostic) => diagnostic.path)).toEqual([
|
||||
["experimental", "policies", "0"],
|
||||
["experimental", "policies", "2"],
|
||||
])
|
||||
})
|
||||
|
||||
test("rejects every non-object root with one root diagnostic", () => {
|
||||
for (const input of [null, [], "config", true, 1]) {
|
||||
expect(ConfigNormalize.normalize(input)).toEqual({
|
||||
@@ -543,7 +572,14 @@ describe("ConfigNormalize", () => {
|
||||
},
|
||||
})
|
||||
expect(result.encoded.providers).not.toHaveProperty(["gateway", "models", "bedrock", "settings", "reasoningConfig"])
|
||||
expect(result.encoded.providers).not.toHaveProperty(["gateway", "models", "both", "settings", "thinking", "blockBinding"])
|
||||
expect(result.encoded.providers).not.toHaveProperty([
|
||||
"gateway",
|
||||
"models",
|
||||
"both",
|
||||
"settings",
|
||||
"thinking",
|
||||
"blockBinding",
|
||||
])
|
||||
expect(result.encoded.providers).not.toHaveProperty([
|
||||
"gateway",
|
||||
"models",
|
||||
|
||||
@@ -25,8 +25,8 @@ const provider = (effect: ConfigPolicy.Effect, resource: string): ConfigPolicy.I
|
||||
resource,
|
||||
effect,
|
||||
})
|
||||
const permission = (effect: ConfigPolicy.Effect, resource: string): ConfigPolicy.Info => ({
|
||||
action: "permission",
|
||||
const tool = (effect: ConfigPolicy.Effect, resource: string): ConfigPolicy.Info => ({
|
||||
action: "tool.use",
|
||||
resource,
|
||||
effect,
|
||||
})
|
||||
@@ -49,6 +49,29 @@ const evaluate = Effect.fn(function* (action: string, resources: string[], effec
|
||||
})
|
||||
|
||||
describe("ConfigPolicyPlugin.Plugin", () => {
|
||||
it.effect("preserves last-match precedence for tool.use without granting approvals", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* addPlugin([
|
||||
document(tool("deny", "shell:*"), tool("allow", "shell:git *"), tool("deny", "shell:git push *")),
|
||||
])
|
||||
expect((yield* evaluate("shell", ["git status"], "ask")).effect).toBe("ask")
|
||||
expect((yield* evaluate("shell", ["git push origin main"])).effect).toBe("deny")
|
||||
expect((yield* evaluate("shell", ["ls"])).effect).toBe("deny")
|
||||
expect((yield* evaluate("edit", ["notes.md"])).effect).toBe("allow")
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("organization tool.use policy overrides authored policy", () =>
|
||||
Effect.gen(function* () {
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
yield* managed.set({ statements: [tool("deny", "shell:*")], organization: "Acme" })
|
||||
yield* addPlugin([document(tool("allow", "shell:*"))])
|
||||
expect(yield* evaluate("shell", ["ls"])).toEqual({ effect: "deny", message: "Blocked by Acme's policy" })
|
||||
yield* managed.set({ statements: [tool("allow", "shell:*")] })
|
||||
expect((yield* evaluate("shell", ["ls"], "ask")).effect).toBe("ask")
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("filters plugin-provided providers with ordered wildcard policies", () =>
|
||||
Effect.gen(function* () {
|
||||
const catalog = yield* Provider.Service
|
||||
@@ -96,7 +119,7 @@ describe("ConfigPolicyPlugin.Plugin", () => {
|
||||
|
||||
it.effect("denies permissions matched as action:resource", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* addPlugin([document(permission("deny", "shell:git push *"))])
|
||||
yield* addPlugin([document(tool("deny", "shell:git push *"))])
|
||||
|
||||
expect(yield* evaluate("shell", ["git push"])).toEqual({
|
||||
effect: "deny",
|
||||
@@ -115,7 +138,7 @@ describe("ConfigPolicyPlugin.Plugin", () => {
|
||||
|
||||
it.effect("turns an ask into a deny but never grants", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* addPlugin([document(permission("deny", "webfetch:*"), permission("allow", "shell:*"))])
|
||||
yield* addPlugin([document(tool("deny", "webfetch:*"), tool("allow", "shell:*"))])
|
||||
|
||||
expect((yield* evaluate("webfetch", ["https://example.com"], "ask")).effect).toBe("deny")
|
||||
expect((yield* evaluate("shell", ["ls"], "ask")).effect).toBe("ask")
|
||||
@@ -124,7 +147,7 @@ describe("ConfigPolicyPlugin.Plugin", () => {
|
||||
|
||||
it.effect("lets a later allow lift an earlier broad deny", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* addPlugin([document(permission("deny", "shell:*"), permission("allow", "shell:git status *"))])
|
||||
yield* addPlugin([document(tool("deny", "shell:*"), tool("allow", "shell:git status *"))])
|
||||
|
||||
expect((yield* evaluate("shell", ["git status --short"])).effect).toBe("allow")
|
||||
expect((yield* evaluate("shell", ["rm -rf /"])).effect).toBe("deny")
|
||||
@@ -133,7 +156,7 @@ describe("ConfigPolicyPlugin.Plugin", () => {
|
||||
|
||||
it.effect("denies every permission with a bare wildcard", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* addPlugin([document(permission("deny", "*"))])
|
||||
yield* addPlugin([document(tool("deny", "*"))])
|
||||
|
||||
expect((yield* evaluate("question", ["*"])).effect).toBe("deny")
|
||||
expect((yield* evaluate("read", ["/tmp/notes.txt"])).effect).toBe("deny")
|
||||
@@ -174,13 +197,13 @@ describe("ConfigPolicyPlugin.Plugin", () => {
|
||||
it.effect("names the organization when its permission statement decides", () =>
|
||||
Effect.gen(function* () {
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
yield* managed.set({ statements: [permission("deny", "shell:sudo *")], organization: "Acme" })
|
||||
yield* addPlugin([document(permission("allow", "shell:*"))])
|
||||
yield* managed.set({ statements: [tool("deny", "shell:sudo *")], organization: "Acme" })
|
||||
yield* addPlugin([document(tool("allow", "shell:*"))])
|
||||
|
||||
expect(yield* evaluate("shell", ["sudo ls"])).toEqual({ effect: "deny", message: "Blocked by Acme's policy" })
|
||||
expect((yield* evaluate("shell", ["ls"])).effect).toBe("allow")
|
||||
|
||||
yield* managed.set({ statements: [permission("deny", "shell:sudo *")] })
|
||||
yield* managed.set({ statements: [tool("deny", "shell:sudo *")] })
|
||||
expect(yield* evaluate("shell", ["sudo ls"])).toEqual({
|
||||
effect: "deny",
|
||||
message: "Blocked by your organization's policy",
|
||||
|
||||
@@ -37,6 +37,7 @@ describe("ConfigSnapshotPlugin.Plugin", () => {
|
||||
const bus = yield* Bus.Service
|
||||
const config = yield* Config.Test
|
||||
const plugins = yield* Plugin.Service
|
||||
yield* config.setEntries([new Document({ type: "document", info: new Info({ snapshots: false }) })])
|
||||
yield* ConfigSnapshotPlugin.Plugin.effect(yield* PluginHost.make(plugins))
|
||||
|
||||
expect(yield* snapshot.capture()).toBeUndefined()
|
||||
@@ -58,9 +59,6 @@ describe("ConfigSnapshotPlugin.Plugin", () => {
|
||||
)
|
||||
}),
|
||||
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
|
||||
).pipe(
|
||||
Effect.provide(PluginTestLayer),
|
||||
Effect.provide(Config.testLayer([new Document({ type: "document", info: new Info({ snapshots: false }) })])),
|
||||
),
|
||||
).pipe(Effect.provide(PluginTestLayer)),
|
||||
)
|
||||
})
|
||||
@@ -24,6 +24,12 @@ describe("ConfigToolOutputPlugin.Plugin", () => {
|
||||
const bus = yield* Bus.Service
|
||||
const config = yield* Config.Test
|
||||
const plugins = yield* Plugin.Service
|
||||
yield* config.setEntries([
|
||||
new Document({
|
||||
type: "document",
|
||||
info: new Info({ tool_output: new ConfigToolOutput.Info({ max_lines: 1 }) }),
|
||||
}),
|
||||
])
|
||||
yield* ConfigToolOutputPlugin.Plugin.effect(yield* PluginHost.make(plugins))
|
||||
|
||||
expect((yield* output.truncate({ content: [{ type: "text", text: "one\ntwo" }] })).metadata?.truncated).toBe(
|
||||
@@ -51,16 +57,6 @@ describe("ConfigToolOutputPlugin.Plugin", () => {
|
||||
),
|
||||
),
|
||||
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
|
||||
).pipe(
|
||||
Effect.provide(PluginTestLayer),
|
||||
Effect.provide(
|
||||
Config.testLayer([
|
||||
new Document({
|
||||
type: "document",
|
||||
info: new Info({ tool_output: new ConfigToolOutput.Info({ max_lines: 1 }) }),
|
||||
}),
|
||||
]),
|
||||
),
|
||||
),
|
||||
).pipe(Effect.provide(PluginTestLayer)),
|
||||
)
|
||||
})
|
||||
@@ -20,6 +20,7 @@ import workspaceMigration from "@opencode/core/database/migration/20260808023530
|
||||
import executionClaimsMigration from "@opencode/core/database/migration/20260811161259_execution_claim_attempts"
|
||||
import sessionInboxMigration from "@opencode/core/database/migration/20260812181746_session_inbox"
|
||||
import sessionViewedStateMigration from "@opencode/core/database/migration/20260819222447_session_viewed_state"
|
||||
import azureCliCredentialMigration from "@opencode/core/database/migration/20261007190000_azure_cli_external_credential"
|
||||
import { Global } from "@opencode/util/global"
|
||||
|
||||
const run = <A, E>(
|
||||
@@ -531,6 +532,37 @@ describe("DatabaseMigration", () => {
|
||||
)
|
||||
})
|
||||
|
||||
test("moves Azure CLI connections saved as OAuth credentials to external credentials", async () => {
|
||||
await run(
|
||||
Effect.gen(function* () {
|
||||
const db = yield* makeDb
|
||||
yield* DatabaseMigration.apply(db)
|
||||
const now = Date.now()
|
||||
const oauth = { type: "oauth", methodID: "azure-cli", access: "token", refresh: "azure-cli", expires: 123 }
|
||||
yield* db.run(sql`
|
||||
INSERT INTO credential (id, integration_id, label, value, time_created, time_updated) VALUES
|
||||
('cli', 'azure', 'Azure CLI', ${JSON.stringify({ ...oauth, metadata: { resourceName: "my-models" } })}, ${now}, ${now}),
|
||||
('cli-configured', 'azure', 'Azure CLI', ${JSON.stringify(oauth)}, ${now}, ${now}),
|
||||
('key', 'azure', 'API key', ${JSON.stringify({ type: "key", key: "secret" })}, ${now}, ${now}),
|
||||
('other', 'openai', 'OAuth', ${JSON.stringify(oauth)}, ${now}, ${now})
|
||||
`)
|
||||
|
||||
yield* db.run(sql`DELETE FROM migration WHERE id = ${azureCliCredentialMigration.id}`)
|
||||
yield* DatabaseMigration.applyOnly(db, [azureCliCredentialMigration])
|
||||
|
||||
expect(yield* db.all(sql`SELECT id, value FROM credential ORDER BY id`)).toEqual([
|
||||
{
|
||||
id: "cli",
|
||||
value: JSON.stringify({ type: "external", methodID: "azure-cli", metadata: { resourceName: "my-models" } }),
|
||||
},
|
||||
{ id: "cli-configured", value: JSON.stringify({ type: "external", methodID: "azure-cli" }) },
|
||||
{ id: "key", value: JSON.stringify({ type: "key", key: "secret" }) },
|
||||
{ id: "other", value: JSON.stringify(oauth) },
|
||||
])
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
test("rolls back a failed migration without recording it", async () => {
|
||||
await run(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { ConfigPolicyPlugin } from "@opencode/core/config/plugin/policy"
|
||||
import { Mcp } from "@opencode/core/mcp/index"
|
||||
import { Skill } from "@opencode/core/skill"
|
||||
import { ID } from "@opencode/schema/event"
|
||||
import { Effect, Stream } from "effect"
|
||||
import { host } from "../plugin/host"
|
||||
|
||||
// Exercise the real policy plugin against supplied catalogs without unrelated provider/permission setup.
|
||||
export const registerIntegrationPolicy = Effect.fn(function* (input: {
|
||||
mcp?: Mcp.Interface
|
||||
skill?: Skill.Interface
|
||||
events?: Stream.Stream<{ readonly type: string }, unknown>
|
||||
}) {
|
||||
yield* ConfigPolicyPlugin.Plugin.effect(
|
||||
host({
|
||||
event: {
|
||||
subscribe: () =>
|
||||
(input.events ?? Stream.never).pipe(
|
||||
Stream.filter((event) => event.type === "config.updated"),
|
||||
Stream.map(() => ({ id: ID.create(), created: Date.now(), type: "config.updated" as const, data: {} })),
|
||||
),
|
||||
},
|
||||
provider: {
|
||||
list: () => Effect.die("unused provider.list"),
|
||||
get: () => Effect.die("unused provider.get"),
|
||||
transform: () => Effect.succeed({ dispose: Effect.void }),
|
||||
reload: () => Effect.void,
|
||||
},
|
||||
mcp: {
|
||||
list: () => Effect.die("unused mcp.list"),
|
||||
transform: (callback) => input.mcp?.transform(callback) ?? Effect.succeed({ dispose: Effect.void }),
|
||||
reload: () => input.mcp?.reload() ?? Effect.void,
|
||||
},
|
||||
skill: {
|
||||
list: () => Effect.die("unused skill.list"),
|
||||
transform: (callback) => input.skill?.transform(callback) ?? Effect.succeed({ dispose: Effect.void }),
|
||||
reload: () => input.skill?.reload() ?? Effect.void,
|
||||
},
|
||||
permission: {
|
||||
hook: () => Effect.succeed({ dispose: Effect.void }),
|
||||
list: () => Effect.die("unused permission.list"),
|
||||
get: () => Effect.die("unused permission.get"),
|
||||
reply: () => Effect.die("unused permission.reply"),
|
||||
},
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -32,6 +32,7 @@ const integrations = Layer.mock(Integration.Service, {
|
||||
active: () => Effect.undefined,
|
||||
resolve: () => Effect.die("unused"),
|
||||
key: () => Effect.die("unused"),
|
||||
external: () => Effect.die("unused"),
|
||||
activate: () => Effect.die("unused"),
|
||||
update: () => Effect.die("unused"),
|
||||
remove: () => Effect.die("unused"),
|
||||
|
||||
@@ -12,6 +12,8 @@ import {
|
||||
import { Document, Event, Info } from "@opencode/schema/config"
|
||||
import { ConfigMCP } from "@opencode/schema/config/mcp"
|
||||
import { McpEvent } from "@opencode/schema/mcp-event"
|
||||
import { ConfigPolicy } from "@opencode/schema/config/policy"
|
||||
import { ManagedPolicy } from "@opencode/core/managed-policy"
|
||||
import { Config } from "@opencode/core/config"
|
||||
import { ConfigMcpPlugin } from "@opencode/core/config/plugin/mcp"
|
||||
import { Credential } from "@opencode/core/credential"
|
||||
@@ -56,6 +58,7 @@ import { ExitCode, makeHandle, ProcessId } from "effect/unstable/process/ChildPr
|
||||
import { Image } from "@opencode/core/image"
|
||||
import { advance, drain } from "./lib/clock"
|
||||
import { testEffect } from "./lib/effect"
|
||||
import { registerIntegrationPolicy } from "./fixture/policy"
|
||||
import { imagePassthrough } from "./lib/image"
|
||||
import { location } from "./fixture/location"
|
||||
import { tmpdirScoped } from "./fixture/tmpdir"
|
||||
@@ -269,6 +272,8 @@ function resourceMcpLayer(
|
||||
onFormCreated?: (form: Form.Info) => Effect.Effect<void>,
|
||||
options?: Mcp.Options,
|
||||
overrides?: {
|
||||
managed?: ManagedPolicy.Interface
|
||||
policies?: readonly ConfigPolicy.Info[]
|
||||
entries?: Config.Interface["entries"]
|
||||
subscribe?: Bus.Interface["subscribe"]
|
||||
environment?: Layer.Layer<Environment.Service>
|
||||
@@ -280,13 +285,20 @@ function resourceMcpLayer(
|
||||
return Layer.effectDiscard(
|
||||
Effect.gen(function* () {
|
||||
const bus = yield* Bus.Service
|
||||
yield* ConfigMcpPlugin.register(bus.subscribe())
|
||||
const mcp = yield* Mcp.Service
|
||||
yield* State.batch(
|
||||
Effect.gen(function* () {
|
||||
yield* ConfigMcpPlugin.register(bus.subscribe())
|
||||
yield* registerIntegrationPolicy({ mcp, events: bus.subscribe() })
|
||||
}),
|
||||
)
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(Mcp.layer(options)),
|
||||
Layer.provideMerge(Form.layer),
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
overrides?.managed ? Layer.succeed(ManagedPolicy.Service, overrides.managed) : ManagedPolicy.layer,
|
||||
overrides?.entries
|
||||
? Layer.succeed(
|
||||
Config.Service,
|
||||
@@ -299,6 +311,7 @@ function resourceMcpLayer(
|
||||
new Document({
|
||||
type: "document",
|
||||
info: new Info({
|
||||
experimental: { policies: overrides?.policies ?? [] },
|
||||
mcp: new ConfigMCP.Info({
|
||||
servers: {
|
||||
resources:
|
||||
@@ -330,6 +343,7 @@ function resourceMcpLayer(
|
||||
active: unusedIntegration,
|
||||
resolve: unusedIntegration,
|
||||
key: unusedIntegration,
|
||||
external: unusedIntegration,
|
||||
activate: unusedIntegration,
|
||||
update: unusedIntegration,
|
||||
remove: unusedIntegration,
|
||||
@@ -1989,7 +2003,16 @@ testEffect(Layer.empty).live("keeps MCP config snapshots stable during an in-fli
|
||||
|
||||
const shutdownIt = testEffect(
|
||||
AppNodeBuilder.build(
|
||||
LayerNode.group([Bus.node, Integration.node, Credential.node, Form.node, Environment.node, Location.node]),
|
||||
LayerNode.group([
|
||||
Config.node,
|
||||
ManagedPolicy.node,
|
||||
Bus.node,
|
||||
Integration.node,
|
||||
Credential.node,
|
||||
Form.node,
|
||||
Environment.node,
|
||||
Location.node,
|
||||
]),
|
||||
[
|
||||
Location.node.replace(
|
||||
Layer.succeed(
|
||||
@@ -2558,3 +2581,123 @@ it.effect("does not call MCP when permission is blocked", () =>
|
||||
expect(calls).toBe(0)
|
||||
}),
|
||||
)
|
||||
|
||||
for (const modern of [false, true]) {
|
||||
testEffect(Layer.empty).live(`integration policy denies MCP startup (${modern ? "modern" : "legacy"})`, () =>
|
||||
Effect.gen(function* () {
|
||||
const server = yield* resourceServer({ modern })
|
||||
yield* Effect.gen(function* () {
|
||||
const service = yield* Mcp.Service
|
||||
expect(yield* service.servers()).toEqual([])
|
||||
expect(Exit.isFailure(yield* service.connect("resources").pipe(Effect.exit))).toBe(true)
|
||||
yield* service.add("resources", { type: "remote", url: server.url, oauth: false })
|
||||
expect(yield* service.servers()).toEqual([])
|
||||
expect(yield* service.tools()).toEqual([])
|
||||
expect(yield* service.instructions()).toEqual([])
|
||||
expect(yield* service.prompts()).toEqual([])
|
||||
expect(yield* service.resourceCatalog()).toEqual({ resources: [], templates: [] })
|
||||
expect(Exit.isFailure(yield* service.resources({ server: "resources" }).pipe(Effect.exit))).toBe(true)
|
||||
expect(Exit.isFailure(yield* service.prompt({ server: "resources", name: "greet" }).pipe(Effect.exit))).toBe(
|
||||
true,
|
||||
)
|
||||
expect(
|
||||
Exit.isFailure(yield* service.readResource({ server: "resources", uri: "docs://readme" }).pipe(Effect.exit)),
|
||||
).toBe(true)
|
||||
expect(Exit.isFailure(yield* service.callTool({ server: "resources", name: "echo" }).pipe(Effect.exit))).toBe(
|
||||
true,
|
||||
)
|
||||
expect(server.state.initializations).toBe(0)
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
resourceMcpLayer(server.url, undefined, undefined, {
|
||||
policies: [{ action: "integration.use", resource: "mcp:*", effect: "deny" }],
|
||||
}),
|
||||
),
|
||||
)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
for (const source of ["config", "organization"] as const) {
|
||||
testEffect(Layer.mergeAll(Config.testLayer(), ManagedPolicy.layer)).live(
|
||||
`revokes and restores a connected MCP through ${source} policy`,
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const server = yield* resourceServer()
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const config = yield* Config.Service
|
||||
const test = yield* Config.Test
|
||||
const updates = yield* PubSub.unbounded<{ readonly type: string }>()
|
||||
const document = (effect: ConfigPolicy.Effect) =>
|
||||
new Document({
|
||||
type: "document",
|
||||
info: new Info({
|
||||
mcp: new ConfigMCP.Info({
|
||||
servers: { resources: new ConfigMCP.Remote({ type: "remote", url: server.url, oauth: false }) },
|
||||
}),
|
||||
experimental: { policies: [{ action: "integration.use", resource: "mcp:*", effect }] },
|
||||
}),
|
||||
})
|
||||
yield* test.setEntries([document("allow")])
|
||||
yield* Effect.gen(function* () {
|
||||
const service = yield* Mcp.Service
|
||||
expect(yield* settled(service)).toEqual({ status: "connected" })
|
||||
expect((yield* service.tools()).length).toBeGreaterThan(0)
|
||||
if (source === "config") yield* test.setEntries([document("deny")])
|
||||
if (source === "organization")
|
||||
yield* managed.set({ statements: [{ action: "integration.use", resource: "mcp:*", effect: "deny" }] })
|
||||
if (source === "config") yield* PubSub.publish(updates, { type: Event.Updated.type })
|
||||
yield* service.servers().pipe(
|
||||
Effect.filterOrFail(
|
||||
(servers) => servers.length === 0,
|
||||
() => new Error("MCP policy was not applied"),
|
||||
),
|
||||
Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }),
|
||||
)
|
||||
expect(yield* service.servers()).toEqual([])
|
||||
expect(yield* service.tools()).toEqual([])
|
||||
expect(yield* service.instructions()).toEqual([])
|
||||
expect(yield* service.prompts()).toEqual([])
|
||||
expect(yield* service.resourceCatalog()).toEqual({ resources: [], templates: [] })
|
||||
expect(Exit.isFailure(yield* service.resources({ server: "resources" }).pipe(Effect.exit))).toBe(true)
|
||||
expect(Exit.isFailure(yield* service.prompt({ server: "resources", name: "greet" }).pipe(Effect.exit))).toBe(
|
||||
true,
|
||||
)
|
||||
expect(
|
||||
Exit.isFailure(
|
||||
yield* service.readResource({ server: "resources", uri: "docs://readme" }).pipe(Effect.exit),
|
||||
),
|
||||
).toBe(true)
|
||||
expect(Exit.isFailure(yield* service.connect("resources").pipe(Effect.exit))).toBe(true)
|
||||
expect(Exit.isFailure(yield* service.callTool({ server: "resources", name: "echo" }).pipe(Effect.exit))).toBe(
|
||||
true,
|
||||
)
|
||||
expect(server.state.toolCalls).toEqual([])
|
||||
expect(server.state.resourceReads).toEqual([])
|
||||
yield* Effect.promise(server.restart)
|
||||
if (source === "config") {
|
||||
yield* test.setEntries([document("allow")])
|
||||
yield* PubSub.publish(updates, { type: Event.Updated.type })
|
||||
}
|
||||
if (source === "organization") yield* managed.set({ statements: [] })
|
||||
yield* service.servers().pipe(
|
||||
Effect.filterOrFail(
|
||||
(servers) => servers.some((server) => server.status.status === "connected"),
|
||||
() => new Error("MCP policy was not restored"),
|
||||
),
|
||||
Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }),
|
||||
)
|
||||
expect(yield* settled(service)).toEqual({ status: "connected" })
|
||||
expect((yield* service.tools()).length).toBeGreaterThan(0)
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
resourceMcpLayer(server.url, undefined, undefined, {
|
||||
entries: config.entries,
|
||||
managed,
|
||||
subscribe: (() => Stream.fromPubSub(updates)) as Bus.Interface["subscribe"],
|
||||
}),
|
||||
),
|
||||
)
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -372,6 +372,7 @@ describe("ModelResolver", () => {
|
||||
},
|
||||
resolve: () => Effect.die("unused"),
|
||||
key: () => Effect.die("unused"),
|
||||
external: () => Effect.die("unused"),
|
||||
activate: () => Effect.die("unused"),
|
||||
update: () => Effect.die("unused"),
|
||||
remove: () => Effect.die("unused"),
|
||||
@@ -731,6 +732,43 @@ describe("ModelResolver", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("lets Azure CLI requests past package auth for the Azure plugin to authorize", () =>
|
||||
withConfigEnv({}, () =>
|
||||
Effect.gen(function* () {
|
||||
const credential = Credential.External.make({
|
||||
type: "external",
|
||||
methodID: Integration.MethodID.make("azure-cli"),
|
||||
metadata: { resourceName: "cli-resource" },
|
||||
})
|
||||
const azure = yield* ModelResolver.fromCatalogModel(
|
||||
model(Provider.aisdk("@ai-sdk/azure"), { providerID: Provider.ID.azure, headers: {}, body: {} }),
|
||||
credential,
|
||||
)
|
||||
const foundry = yield* ModelResolver.fromCatalogModel(
|
||||
model(Provider.aisdk("@ai-sdk/anthropic"), {
|
||||
providerID: Provider.ID.azure,
|
||||
settings: { baseURL: "https://cli-resource.services.ai.azure.com/anthropic/v1" },
|
||||
headers: {},
|
||||
body: {},
|
||||
}),
|
||||
credential,
|
||||
)
|
||||
const authorize = (resolved: LanguageModel) =>
|
||||
resolved.route.auth.apply({
|
||||
request: LLM.request({ model: resolved, prompt: "Hello" }),
|
||||
method: "POST",
|
||||
url: "https://cli-resource.openai.azure.com/openai/v1/responses",
|
||||
body: "{}",
|
||||
headers: Headers.empty,
|
||||
})
|
||||
|
||||
expect(azure.route.endpoint.baseURL).toBe("https://cli-resource.openai.azure.com/openai/v1")
|
||||
expect((yield* authorize(azure))["api-key"]).toBe("azure-cli")
|
||||
expect((yield* authorize(foundry)).authorization).toBe("Bearer azure-cli")
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("does not project API key metadata into the request body", () =>
|
||||
Effect.gen(function* () {
|
||||
// V1 auth.json stored connect-form answers as API key metadata, and the legacy import preserves them there.
|
||||
|
||||
@@ -98,7 +98,7 @@ it.live("loads a local plugin with its configured options", () =>
|
||||
target: path.join(import.meta.dir, "plugin/fixtures/greeting.ts"),
|
||||
options: { description: "Configured greeting" },
|
||||
})
|
||||
if ("pending" in definition) return yield* Effect.die("Local plugin was not loaded")
|
||||
if ("pending" in definition || "blocked" in definition) return yield* Effect.die("Local plugin was not loaded")
|
||||
yield* plugins.activate([definition])
|
||||
|
||||
expect(yield* commands.get("greet")).toMatchObject({ description: "Configured greeting" })
|
||||
|
||||
@@ -53,6 +53,8 @@ const npmLayer = Layer.succeed(
|
||||
|
||||
const generateLayer = Layer.succeed(Generate.Service, Generate.Service.of({ text: () => Effect.succeed("") }))
|
||||
|
||||
const configLayer = Config.testLayer()
|
||||
|
||||
const permissionLayer = Layer.succeed(
|
||||
Permission.Service,
|
||||
Permission.Service.of({
|
||||
@@ -74,6 +76,7 @@ export const PluginTestLayer = AppNodeBuilder.build(
|
||||
Location.node,
|
||||
Npm.node,
|
||||
Credential.node,
|
||||
Config.node,
|
||||
Bus.node,
|
||||
Form.node,
|
||||
Generate.node,
|
||||
@@ -107,9 +110,9 @@ export const PluginTestLayer = AppNodeBuilder.build(
|
||||
[
|
||||
Location.node.replace(tempLocationLayer),
|
||||
Npm.node.replace(npmLayer),
|
||||
Config.node.replace(Config.testLayer()),
|
||||
Config.node.replace(configLayer),
|
||||
Mcp.node.replace(emptyMcpLayer),
|
||||
Generate.node.replace(generateLayer),
|
||||
Permission.node.replace(permissionLayer),
|
||||
],
|
||||
)
|
||||
).pipe(Layer.provideMerge(configLayer))
|
||||
@@ -78,6 +78,7 @@ export function host(overrides: Overrides = {}): Plugin.Context {
|
||||
get: () => Effect.die("unused integration.get"),
|
||||
connect: {
|
||||
key: () => Effect.die("unused integration.connect.key"),
|
||||
external: () => Effect.die("unused integration.connect.external"),
|
||||
},
|
||||
oauth: {
|
||||
connect: () => Effect.die("unused integration.oauth.connect"),
|
||||
@@ -297,6 +298,7 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
|
||||
get: () => Effect.die("unused integration.get"),
|
||||
connect: {
|
||||
key: () => Effect.die("unused integration.connect.key"),
|
||||
external: () => Effect.die("unused integration.connect.external"),
|
||||
},
|
||||
oauth: {
|
||||
connect: () => Effect.die("unused integration.oauth.connect"),
|
||||
@@ -409,6 +411,16 @@ export function integrationHost(integration: Integration.Interface): Plugin.Cont
|
||||
})
|
||||
return
|
||||
}
|
||||
if (input.method.type === "external") {
|
||||
editor.method.update({
|
||||
integrationID: Integration.ID.make(input.integrationID),
|
||||
method: {
|
||||
...input.method,
|
||||
id: Integration.MethodID.make(input.method.id),
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
editor.method.update({
|
||||
integrationID: Integration.ID.make(input.integrationID),
|
||||
method: input.method,
|
||||
@@ -459,7 +471,7 @@ export function webSearchHost(websearch: WebSearch.Interface): Plugin.Context["w
|
||||
}
|
||||
|
||||
function internalMethod(value: IntegrationMethod): Integration.Method {
|
||||
if (value.type === "oauth" || value.type === "command") {
|
||||
if (value.type === "oauth" || value.type === "command" || value.type === "external") {
|
||||
return { ...value, id: Integration.MethodID.make(value.id) }
|
||||
}
|
||||
return value
|
||||
|
||||
@@ -1,17 +1,32 @@
|
||||
import { expect } from "bun:test"
|
||||
import { cp } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { Deferred, Effect, Exit, Fiber, Layer, Schedule, Scope, Stream } from "effect"
|
||||
import { Brand, Cause, Deferred, Effect, Exit, Fiber, Layer, Option, Schedule, Schema, Scope, Stream } from "effect"
|
||||
import { Agent } from "@opencode/schema/agent"
|
||||
import { Session } from "@opencode/schema/session"
|
||||
import { SessionMessage } from "@opencode/schema/session-message"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
import { Watcher } from "@opencode/core/filesystem/watcher"
|
||||
import { Plugin } from "@opencode/core/plugin"
|
||||
import { ManagedPolicy } from "@opencode/core/managed-policy"
|
||||
import { PluginModule } from "@opencode/core/plugin/module"
|
||||
import { Rpc } from "@opencode/core/rpc"
|
||||
import { Tool } from "@opencode/core/tool"
|
||||
import { execute } from "@opencode/core/tool/runtime"
|
||||
import { Global } from "@opencode/util/global"
|
||||
import { Npm } from "@opencode/util/npm"
|
||||
import { createForeignPackageFilter, ensurePluginRuntime } from "@opencode/plugin/runtime"
|
||||
import { createLoader, discoverPluginRuntimeSpecifiers, pluginRuntimeLoaderCode } from "@opencode/plugin/runtime-modules"
|
||||
import { tempGlobalLayer } from "../fixture/global"
|
||||
import { tmpdirScoped } from "../fixture/tmpdir"
|
||||
import { testEffect } from "../lib/effect"
|
||||
import { PluginTestLayer } from "./fixture"
|
||||
|
||||
ensurePluginRuntime()
|
||||
|
||||
const it = testEffect(
|
||||
Layer.merge(
|
||||
Layer.mergeAll(
|
||||
PluginTestLayer,
|
||||
AppNodeBuilder.build(Npm.node, [Global.node.replace(tempGlobalLayer)]),
|
||||
Watcher.layer().pipe(Layer.provide(Watcher.nativeLayer)),
|
||||
),
|
||||
@@ -90,3 +105,338 @@ it.live("interrupts pending watcher setup when the loader scope closes during mo
|
||||
yield* Effect.promise(() => Bun.sleep(50))
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("loads plugins and their transitive dependencies against the host's Effect and @opencode/plugin instances", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* tmpdirScoped()
|
||||
const pluginDir = path.join(directory.path, "plugin")
|
||||
const pluginEffectDir = path.join(pluginDir, "node_modules/effect")
|
||||
const hostEffectDir = path.dirname(Bun.resolveSync("effect/package.json", import.meta.dir))
|
||||
|
||||
yield* Effect.promise(async () => {
|
||||
await cp(path.join(hostEffectDir, "dist"), path.join(pluginEffectDir, "dist"), {
|
||||
recursive: true,
|
||||
filter: (src) => !src.endsWith(".d.ts") && !src.endsWith(".map") && !/httpApi(?:Scalar|Swagger)\.js$/.test(src),
|
||||
})
|
||||
const pkg = { ...(await Bun.file(path.join(hostEffectDir, "package.json")).json()), version: "4.0.0-rc.111" }
|
||||
|
||||
// Sabotage the plugin's own Effect copy with the version-skew failure modes so loading it would crash:
|
||||
// 1. Effect.log reading an incompatible fiber log-level property (crashing host logger with logLevel.toUpperCase)
|
||||
// 2. Effect.runPromise calling fiber.succeedWith on a host fiber
|
||||
// 3. Schema.withDecodingDefault / Schema.Int / Schema.isPattern / Schema.Trim using foreign parser sentinels
|
||||
const internalEffectPath = path.join(pluginEffectDir, "dist/internal/effect.js")
|
||||
const originalInternalEffect = await Bun.file(internalEffectPath).text()
|
||||
const logPattern =
|
||||
/const logLevel = level \?\? fiber\.(?:currentLogLevel|cache\.logLevel);\r?\n\s*if \(isLogLevelGreaterThan\(fiber\.(?:minimumLogLevel|cache\.minimumLogLevel), logLevel\)\) \{/
|
||||
const runPromisePattern = /const runPromiseExit = runPromiseExitWith\(context\);/
|
||||
expect(logPattern.test(originalInternalEffect)).toBe(true)
|
||||
expect(runPromisePattern.test(originalInternalEffect)).toBe(true)
|
||||
|
||||
await writeFiles(pluginDir, {
|
||||
"node_modules/effect/package.json": JSON.stringify(pkg),
|
||||
"node_modules/effect/dist/internal/effect.js": originalInternalEffect
|
||||
.replace(
|
||||
logPattern,
|
||||
"const logLevel = level ?? fiber.foreignSkew?.logLevel;\n if (isLogLevelGreaterThan(fiber.foreignSkew?.minimumLogLevel, logLevel)) {",
|
||||
)
|
||||
.replace(
|
||||
runPromisePattern,
|
||||
"if (true) return (effect) => Promise.resolve().then(() => { const fiber = {}; return fiber.succeedWith(effect); });\n const runPromiseExit = runPromiseExitWith(context);",
|
||||
),
|
||||
"node_modules/transitive-dep/package.json":
|
||||
'{"name":"transitive-dep","type":"module","exports":{".":"./index.js"}}',
|
||||
"node_modules/transitive-dep/index.js": `import { Effect, Schema } from "effect"
|
||||
import { some } from "effect/Option"
|
||||
export const depToolInput = Schema.Struct({
|
||||
mode: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed("from-dep"))),
|
||||
count: Schema.Int,
|
||||
code: Schema.Trim.check(Schema.isPattern(/^v[0-9]+$/)),
|
||||
})
|
||||
export const depCaptured = { Effect, Schema, some }`,
|
||||
"node_modules/@opencode/plugin/package.json":
|
||||
'{"name":"@opencode/plugin","type":"module","exports":{"./effect":"./effect.js","./rpc":"./rpc.js"}}',
|
||||
"node_modules/@opencode/plugin/effect.js": "export const Plugin = { define: (p) => p }",
|
||||
"node_modules/@opencode/plugin/rpc.js": "export const Rpc = { define: (d) => d }",
|
||||
"index.ts": `import { Plugin } from "@opencode/plugin/effect"
|
||||
import { Rpc } from "@opencode/plugin/rpc"
|
||||
import { Effect, Schema } from "effect"
|
||||
import { some } from "effect/Option"
|
||||
import { nominal } from "effect/Brand"
|
||||
import { depCaptured, depToolInput } from "transitive-dep"
|
||||
|
||||
export const captured = {
|
||||
plugin: { Effect, Schema, some, nominal },
|
||||
dep: depCaptured,
|
||||
pluginCount: -1,
|
||||
}
|
||||
|
||||
const Contract = Rpc.define({
|
||||
id: "host-effect-rpc",
|
||||
methods: {
|
||||
check: {
|
||||
input: Schema.Struct({
|
||||
count: Schema.Int.pipe(Schema.withDecodingDefault(Effect.succeed(5))),
|
||||
tag: Schema.Trim.check(Schema.isPattern(/^v[0-9]+$/)),
|
||||
}),
|
||||
output: Schema.Struct({ value: Schema.String }),
|
||||
},
|
||||
},
|
||||
events: {},
|
||||
})
|
||||
|
||||
export default Plugin.define({
|
||||
id: "host-effect-fixture",
|
||||
effect: (ctx) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.log("setup log from plugin")
|
||||
const listed = yield* Effect.promise(() =>
|
||||
Effect.runPromise(ctx.plugin.list().pipe(Effect.orDie)),
|
||||
)
|
||||
captured.pluginCount = listed.data.length
|
||||
|
||||
yield* ctx.tool.transform((editor) => {
|
||||
editor.add({
|
||||
name: "check_tool",
|
||||
description: "Tool with decoding default from transitive dependency and Int/Trim/isPattern checks",
|
||||
input: depToolInput,
|
||||
output: Schema.Struct({ formatted: Schema.String }),
|
||||
execute: ({ mode, count, code }) =>
|
||||
Effect.log("executing check_tool").pipe(
|
||||
Effect.as({
|
||||
output: { formatted: \`\${mode}:\${code}:\${count}\` },
|
||||
content: \`\${mode}:\${code}:\${count}\`,
|
||||
}),
|
||||
),
|
||||
})
|
||||
})
|
||||
|
||||
yield* ctx.rpc.register(Contract, {
|
||||
check: ({ count, tag }) =>
|
||||
Effect.log("executing rpc check").pipe(
|
||||
Effect.as({ value: \`\${tag}#\${count}\` }),
|
||||
),
|
||||
}).pipe(Effect.orDie)
|
||||
}),
|
||||
})`,
|
||||
})
|
||||
})
|
||||
|
||||
const modules = yield* PluginModule.make()
|
||||
const plugins = yield* Plugin.Service
|
||||
const tools = yield* Tool.Service
|
||||
const rpc = yield* Rpc.Service
|
||||
|
||||
const definition = yield* modules.load({ type: "add", target: pluginDir, options: {} })
|
||||
if ("pending" in definition || "blocked" in definition) return yield* Effect.die(new Error("Local plugin was not loaded"))
|
||||
yield* plugins.activate([definition])
|
||||
yield* plugins.awaitActivation
|
||||
|
||||
expect(yield* plugins.list()).toMatchObject([{ id: "host-effect-fixture", state: { status: "active" } }])
|
||||
|
||||
const imported = yield* Effect.promise(() => import(path.join(pluginDir, "index.ts")))
|
||||
expect(imported.captured.plugin.Effect).toBe(Effect)
|
||||
expect(imported.captured.plugin.Schema).toBe(Schema)
|
||||
expect(imported.captured.plugin.some).toBe(Option.some)
|
||||
expect(imported.captured.plugin.nominal).toBe(Brand.nominal)
|
||||
expect(imported.captured.dep.Effect).toBe(Effect)
|
||||
expect(imported.captured.dep.Schema).toBe(Schema)
|
||||
expect(imported.captured.dep.some).toBe(Option.some)
|
||||
expect(imported.captured.pluginCount).toBe(0)
|
||||
|
||||
const checkTool = (yield* tools.list()).find((tool) => tool.id === "check_tool")
|
||||
expect(checkTool).toBeDefined()
|
||||
if (!checkTool) return
|
||||
|
||||
const context = {
|
||||
sessionID: Session.ID.make("ses_host_effect"),
|
||||
agent: Agent.ID.make("build"),
|
||||
messageID: SessionMessage.ID.make("msg_host_effect"),
|
||||
id: Tool.CallID.make("call_host_effect"),
|
||||
progress: () => Effect.void,
|
||||
}
|
||||
|
||||
expect(yield* execute(checkTool, { count: 3, code: " v42 " }, context)).toEqual({
|
||||
output: { formatted: "from-dep:v42:3" },
|
||||
content: [{ type: "text", text: "from-dep:v42:3" }],
|
||||
})
|
||||
expect(yield* rpc.call("host-effect-rpc", "check", { tag: " v9 " })).toEqual({ value: "v9#5" })
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("redirects plugin dependencies with a nested Effect 3 installation to the host, allows effect/package.json, and fails loudly on unprovided subpaths", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* tmpdirScoped()
|
||||
const pluginDir = path.join(directory.path, "v3-dep-plugin")
|
||||
const badDir = path.join(directory.path, "removed-subpath-plugin")
|
||||
const v3DepDir = path.join(pluginDir, "node_modules/v3-dep")
|
||||
|
||||
yield* Effect.promise(() =>
|
||||
writeFiles(directory.path, {
|
||||
"v3-dep-plugin/node_modules/effect/package.json":
|
||||
'{"name":"effect","version":"4.0.0-rc.111","type":"module","exports":{"./package.json":"./package.json"}}',
|
||||
"v3-dep-plugin/node_modules/v3-dep/node_modules/effect/package.json":
|
||||
'{"name":"effect","version":"3.19.19","type":"module","exports":{".":"./index.js","./Option":"./Option.js","./ReadonlyArray":"./ReadonlyArray.js"}}',
|
||||
"v3-dep-plugin/node_modules/v3-dep/node_modules/effect/index.js":
|
||||
"export const Effect = { major: 3 }; export const Schema = { major: 3 }",
|
||||
"v3-dep-plugin/node_modules/v3-dep/node_modules/effect/Option.js": "export const some = () => ({ major: 3 })",
|
||||
"v3-dep-plugin/node_modules/v3-dep/node_modules/effect/ReadonlyArray.js": "export const fromIterable = () => []",
|
||||
"v3-dep-plugin/node_modules/v3-dep/package.json":
|
||||
'{"name":"v3-dep","type":"module","exports":{".":"./index.js","./v3-only":"./v3-only.js"}}',
|
||||
"v3-dep-plugin/node_modules/v3-dep/index.js":
|
||||
'import { Effect, Schema } from "effect"; import { some } from "effect/Option"; export const v3DepCaptured = { Effect, Schema, some }',
|
||||
"v3-dep-plugin/node_modules/v3-dep/v3-only.js":
|
||||
'import { fromIterable } from "effect/ReadonlyArray"; export { fromIterable }',
|
||||
"v3-dep-plugin/index.ts":
|
||||
'import pkg from "effect/package.json" with { type: "json" }; import { v3DepCaptured } from "v3-dep"; export const effectPkgName = pkg.name; export { v3DepCaptured }; export default { id: "v3-dep-plugin", async setup() {} }',
|
||||
"removed-subpath-plugin/node_modules/effect/package.json":
|
||||
'{"name":"effect","type":"module","exports":{"./RemovedLegacySubpath":"./RemovedLegacySubpath.js"}}',
|
||||
"removed-subpath-plugin/node_modules/effect/RemovedLegacySubpath.js": "export const legacy = true",
|
||||
"removed-subpath-plugin/index.ts":
|
||||
'import { legacy } from "effect/RemovedLegacySubpath"; export default { id: "removed-subpath", async setup() { void legacy } }',
|
||||
}),
|
||||
)
|
||||
|
||||
const modules = yield* PluginModule.make()
|
||||
expect(yield* modules.load({ type: "add", target: pluginDir, options: {} })).toMatchObject({ id: "v3-dep-plugin" })
|
||||
|
||||
const imported = yield* Effect.promise(() => import(path.join(pluginDir, "index.ts")))
|
||||
expect(imported.effectPkgName).toBe("effect")
|
||||
expect(imported.v3DepCaptured.Effect).toBe(Effect)
|
||||
expect(imported.v3DepCaptured.Schema).toBe(Schema)
|
||||
expect(imported.v3DepCaptured.some).toBe(Option.some)
|
||||
yield* Effect.promise(async () => {
|
||||
await expect(import(path.join(v3DepDir, "v3-only.js"))).rejects.toThrow("effect/ReadonlyArray.js")
|
||||
})
|
||||
|
||||
const exit = yield* modules.load({ type: "add", target: badDir, options: {} }).pipe(Effect.exit)
|
||||
expect(Exit.isFailure(exit)).toBe(true)
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(String(Cause.squash(exit.cause))).toContain("effect/RemovedLegacySubpath.js")
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("discovers exported specifiers from the resolved tree even when dist/ exists, and validates barrel loader routing, async loader dedup, and Windows foreign filters", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* tmpdirScoped()
|
||||
const consumerDir = path.join(directory.path, "consumer")
|
||||
const jitFixtureDir = path.join(directory.path, "jit-fixture")
|
||||
const asyncModPath = path.join(directory.path, "async-mod.ts")
|
||||
|
||||
yield* Effect.promise(() =>
|
||||
writeFiles(directory.path, {
|
||||
"consumer/node_modules/@opencode/plugin/package.json": JSON.stringify({
|
||||
name: "@opencode/plugin",
|
||||
type: "module",
|
||||
exports: {
|
||||
".": "./src/promise/index.ts",
|
||||
"./effect": "./src/effect/index.ts",
|
||||
"./effect/*": "./src/effect/*.ts",
|
||||
},
|
||||
}),
|
||||
"consumer/node_modules/@opencode/plugin/src/promise/index.ts": "export const root = 'src'",
|
||||
"consumer/node_modules/@opencode/plugin/src/effect/index.ts": "export * as plugin from './plugin.ts'",
|
||||
"consumer/node_modules/@opencode/plugin/src/effect/plugin.ts": "export const leaf = 'src'",
|
||||
"consumer/node_modules/@opencode/plugin/src/unexported.ts": "export const secret = true",
|
||||
"consumer/node_modules/@opencode/plugin/dist/promise/index.js": "export const root = 'dist'",
|
||||
"consumer/node_modules/@opencode/plugin/dist/effect/index.js": "export const index = 'dist'",
|
||||
"consumer/node_modules/@opencode/plugin/dist/effect/plugin.js": "export const leaf = 'dist'",
|
||||
"jit-fixture/SchemaJITCompiler.js": "export const enable = () => 'fn'",
|
||||
"jit-fixture/enable.js": "export {}",
|
||||
"async-mod.ts": "await new Promise((r) => setTimeout(r, 20)); export const nonce = Math.random()",
|
||||
}),
|
||||
)
|
||||
|
||||
const discovered = discoverPluginRuntimeSpecifiers(consumerDir, ["@opencode/plugin"])
|
||||
expect(discovered.get("@opencode/plugin")?.replaceAll("\\", "/")).toEndWith("src/promise/index.ts")
|
||||
expect(discovered.get("@opencode/plugin/effect")?.replaceAll("\\", "/")).toEndWith("src/effect/index.ts")
|
||||
expect(discovered.get("@opencode/plugin/effect/plugin")?.replaceAll("\\", "/")).toEndWith("src/effect/plugin.ts")
|
||||
expect(discovered.has("@opencode/plugin/unexported")).toBe(false)
|
||||
|
||||
const hostDiscovered = new Map(discoverPluginRuntimeSpecifiers())
|
||||
hostDiscovered.set("effect/schema/SchemaJITCompiler", path.join(jitFixtureDir, "SchemaJITCompiler.js"))
|
||||
hostDiscovered.set("effect/schema/SchemaJITCompiler/enable", path.join(jitFixtureDir, "enable.js"))
|
||||
expect(pluginRuntimeLoaderCode("effect/Option", hostDiscovered)).toBe('() => require("effect")["Option"]')
|
||||
expect(pluginRuntimeLoaderCode("effect/testing", hostDiscovered)).toBe('() => require("effect/testing")')
|
||||
expect(pluginRuntimeLoaderCode("effect/unstable/http/MultipartParser/HeadersParser", hostDiscovered)).toBe(
|
||||
'() => require("effect/unstable/http/MultipartParser/HeadersParser")',
|
||||
)
|
||||
expect(pluginRuntimeLoaderCode("effect/schema/SchemaJITCompiler/enable", hostDiscovered)).toBe(
|
||||
'() => require("effect/schema/SchemaJITCompiler/enable")',
|
||||
)
|
||||
|
||||
const loadAsync = createLoader(asyncModPath)
|
||||
const first = loadAsync()
|
||||
const second = loadAsync()
|
||||
expect(first).toBeInstanceOf(Promise)
|
||||
expect(first).toBe(second)
|
||||
const [res1, res2] = yield* Effect.promise(() => Promise.all([first, second]))
|
||||
expect(res1).toBe(res2)
|
||||
|
||||
const winFilter = createForeignPackageFilter([
|
||||
"C:\\runner\\_work\\opencode\\node_modules\\.bun\\effect@4.0.0-rc.112\\node_modules\\effect",
|
||||
])
|
||||
expect(
|
||||
winFilter.test(
|
||||
"C:\\runner\\_work\\opencode\\node_modules\\.bun\\effect@4.0.0-rc.112\\node_modules\\effect\\dist\\index.js",
|
||||
),
|
||||
).toBe(false)
|
||||
expect(
|
||||
winFilter.test(
|
||||
"C:/runner/_work/opencode/node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/index.js",
|
||||
),
|
||||
).toBe(false)
|
||||
expect(winFilter.test("C:\\Users\\plugin\\node_modules\\effect\\dist\\index.js")).toBe(true)
|
||||
expect(winFilter.test("C:/Users/plugin/node_modules/effect/dist/index.js")).toBe(true)
|
||||
expect(winFilter.test("C:\\Users\\user\\.bun\\install\\cache\\effect@4.0.1@@@1\\dist\\index.js")).toBe(true)
|
||||
expect(winFilter.test("C:/Users/user/.bun/install/cache/effect@4.0.1@@@1/dist/index.js")).toBe(true)
|
||||
}),
|
||||
)
|
||||
|
||||
async function writeFiles(root: string, files: Record<string, string>) {
|
||||
await Promise.all(Object.entries(files).map(([file, text]) => Bun.write(path.join(root, file), text)))
|
||||
}
|
||||
|
||||
it.live("blocks a local plugin before module initialization and honors replacement policies", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* tmpdirScoped()
|
||||
const entered = path.join(directory.path, "entered")
|
||||
yield* Effect.promise(() =>
|
||||
Bun.write(
|
||||
path.join(directory.path, "index.ts"),
|
||||
`
|
||||
await Bun.write(${JSON.stringify(entered)}, "loaded")
|
||||
export default { id: "policy-fixture", async setup() {} }
|
||||
`,
|
||||
),
|
||||
)
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const modules = yield* PluginModule.make()
|
||||
const operation = { type: "add" as const, target: directory.path, options: {} }
|
||||
yield* managed.set({
|
||||
statements: [{ action: "integration.use", resource: `plugin:${directory.path}`, effect: "deny" }],
|
||||
})
|
||||
expect(yield* modules.load(operation)).toEqual({ blocked: true })
|
||||
expect(yield* Effect.promise(() => Bun.file(entered).exists())).toBe(false)
|
||||
yield* managed.set({ statements: [] })
|
||||
expect(yield* modules.load(operation)).toMatchObject({ id: "policy-fixture" })
|
||||
expect(yield* Effect.promise(() => Bun.file(entered).exists())).toBe(true)
|
||||
}),
|
||||
)
|
||||
|
||||
for (const target of ["policy-fixture@1.2.3", "@scope/policy-fixture@1.2.3"]) {
|
||||
it.live(`blocks versioned package ${target} before npm resolution or installation`, () =>
|
||||
Effect.gen(function* () {
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const modules = yield* PluginModule.make()
|
||||
yield* managed.set({
|
||||
statements: [
|
||||
{ action: "integration.use", resource: `plugin:${target.slice(0, target.lastIndexOf("@"))}`, effect: "deny" },
|
||||
],
|
||||
})
|
||||
const operation = { type: "add" as const, target, options: {} }
|
||||
expect(yield* modules.load(operation, { install: false })).toEqual({ blocked: true })
|
||||
expect(yield* modules.load(operation, { install: true })).toEqual({ blocked: true })
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -104,8 +104,7 @@ describe("AmazonBedrockPlugin", () => {
|
||||
})
|
||||
})
|
||||
yield* addPlugin()
|
||||
expect((yield* integrations.get(integrationID))?.methods).toEqual([
|
||||
{ type: "key" },
|
||||
expect((yield* integrations.get(integrationID))?.methods.filter((method) => method.type === "env")).toEqual([
|
||||
{ type: "env", names: ["AWS_BEARER_TOKEN_BEDROCK"] },
|
||||
])
|
||||
}),
|
||||
|
||||
@@ -64,13 +64,13 @@ type AzureRequest = {
|
||||
type Route = (request: AzureRequest) => Response | Promise<Response>
|
||||
|
||||
// Answers like Azure: the resource's own deployment list, Resource Graph, and the management API.
|
||||
const fakeAzure = (routes: { resource?: Route; management?: Route }) =>
|
||||
const fakeAzure = (routes: { resource?: Route; management?: Route; resources?: () => unknown[] }) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
const requests: AzureRequest[] = []
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch: (raw) => {
|
||||
fetch: async (raw) => {
|
||||
const url = new URL(raw.url)
|
||||
const request = {
|
||||
method: raw.method,
|
||||
@@ -81,8 +81,12 @@ const fakeAzure = (routes: { resource?: Route; management?: Route }) =>
|
||||
}
|
||||
requests.push(request)
|
||||
if (request.path.startsWith("/openai/deployments")) return routes.resource?.(request) ?? notFound()
|
||||
if (request.path.startsWith("/providers/Microsoft.ResourceGraph/"))
|
||||
if (request.path.startsWith("/providers/Microsoft.ResourceGraph/")) {
|
||||
// The connect form lists every resource; discovery looks up one resource's ID.
|
||||
if ((await raw.text()).includes("project resourceName"))
|
||||
return routes.resources ? Response.json({ data: routes.resources() }) : unauthorized()
|
||||
return Response.json({ data: [{ id: resourceID }] })
|
||||
}
|
||||
return routes.management?.(request) ?? notFound()
|
||||
},
|
||||
})
|
||||
@@ -121,7 +125,14 @@ const fakeAzureCli = Effect.fn(function* (respond: (args: readonly string[]) =>
|
||||
const executable = `${directory}/${windows ? "az.cmd" : "az"}`
|
||||
yield* Effect.promise(() => Bun.write(executable, windows ? "@exit /b 0\r\n" : "#!/bin/sh\nexit 0\n"))
|
||||
yield* Effect.promise(() => chmod(executable, 0o755))
|
||||
yield* setEnv({ PATH: `${directory}${windows ? ";" : ":"}${process.env.PATH}` })
|
||||
// The CLI writes its profile with a byte order mark.
|
||||
yield* Effect.promise(() =>
|
||||
Bun.write(`${directory}/azure/azureProfile.json`, `\uFEFF${JSON.stringify({ subscriptions: [{ id: "sub" }] })}`),
|
||||
)
|
||||
yield* setEnv({
|
||||
PATH: `${directory}${windows ? ";" : ":"}${process.env.PATH}`,
|
||||
AZURE_CONFIG_DIR: `${directory}/azure`,
|
||||
})
|
||||
const commands: string[][] = []
|
||||
const fake = AppProcess.Service.of({
|
||||
...processes,
|
||||
@@ -146,13 +157,10 @@ const fakeAzureCli = Effect.fn(function* (respond: (args: readonly string[]) =>
|
||||
}
|
||||
})
|
||||
|
||||
const cliCredential = (options: { access?: string; expires?: number } = {}) =>
|
||||
Credential.OAuth.make({
|
||||
type: "oauth",
|
||||
const cliCredential = () =>
|
||||
Credential.External.make({
|
||||
type: "external",
|
||||
methodID: Integration.MethodID.make("azure-cli"),
|
||||
access: options.access ?? "stored-token",
|
||||
refresh: "azure-cli",
|
||||
expires: options.expires ?? Date.now() + hour,
|
||||
metadata: { resourceName: "test-resource" },
|
||||
})
|
||||
|
||||
@@ -231,18 +239,84 @@ describe("AzurePlugin connecting", () => {
|
||||
yield* setEnv({ PATH: "/nonexistent" })
|
||||
yield* addPlugin()
|
||||
const integrations = yield* Integration.Service
|
||||
expect(required(yield* integrations.get(azureID)).methods.some((method) => method.type === "oauth")).toBe(false)
|
||||
expect(required(yield* integrations.get(azureID)).methods.some((method) => method.type === "external")).toBe(
|
||||
false,
|
||||
)
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("offers the resources the Azure CLI can reach and accepts a typed resource name", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* setEnv(noResourceEnv)
|
||||
const cli = yield* fakeAzureCli()
|
||||
const azure = yield* fakeAzure({
|
||||
resources: () => [
|
||||
{ resourceName: "alpha", resourceGroup: "models", location: "eastus" },
|
||||
{ resourceName: "not a hostname", resourceGroup: "models", location: "eastus" },
|
||||
{ id: 42 },
|
||||
],
|
||||
})
|
||||
yield* addPlugin(azure.endpoints).pipe(cli.provide)
|
||||
const integrations = yield* Integration.Service
|
||||
const field = Effect.gen(function* () {
|
||||
const method = required(yield* integrations.get(azureID)).methods.find((method) => method.type === "external")
|
||||
const field = method?.type === "external" ? method.form?.[0] : undefined
|
||||
return field?.type === "string" ? field : undefined
|
||||
})
|
||||
|
||||
const listed = required(yield* eventually(field, (field) => (field?.options?.length ?? 0) > 0))
|
||||
expect(listed).toMatchObject({
|
||||
key: "resourceName",
|
||||
custom: true,
|
||||
options: [{ value: "alpha", label: "alpha", description: "models · eastus" }],
|
||||
})
|
||||
|
||||
const external = (resourceName: string) =>
|
||||
integrations.connection.external({
|
||||
integrationID: azureID,
|
||||
methodID: Integration.MethodID.make("azure-cli"),
|
||||
answer: { resourceName },
|
||||
})
|
||||
expect(yield* external("not a hostname").pipe(Effect.flip)).toBeInstanceOf(Integration.AuthorizationError)
|
||||
yield* external("typed-resource")
|
||||
const credentials = yield* Credential.Service
|
||||
expect((yield* credentials.list(azureID)).map((item) => item.value)).toEqual([
|
||||
Credential.External.make({
|
||||
type: "external",
|
||||
methodID: Integration.MethodID.make("azure-cli"),
|
||||
metadata: { resourceName: "typed-resource" },
|
||||
}),
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("asks for the resource name as text when the Azure CLI lists no resources", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* setEnv(noResourceEnv)
|
||||
const cli = yield* fakeAzureCli()
|
||||
const azure = yield* fakeAzure({ resources: () => [] })
|
||||
yield* addPlugin(azure.endpoints).pipe(cli.provide)
|
||||
const integrations = yield* Integration.Service
|
||||
const field = Effect.gen(function* () {
|
||||
const method = required(yield* integrations.get(azureID)).methods.find((method) => method.type === "external")
|
||||
const field = method?.type === "external" ? method.form?.[0] : undefined
|
||||
return field?.type === "string" ? field : undefined
|
||||
})
|
||||
|
||||
const listed = required(yield* eventually(field, (field) => field?.description?.startsWith("No ") === true))
|
||||
expect(listed.options).toBeUndefined()
|
||||
expect(listed.custom).toBeUndefined()
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
describe("AzurePlugin startup", () => {
|
||||
it.live("starts without calling Azure, even with an expired token, then lists deployments", () =>
|
||||
it.live("starts without calling Azure, then lists deployments", () =>
|
||||
Effect.gen(function* () {
|
||||
const cli = yield* fakeAzureCli()
|
||||
const azure = yield* fakeAzure({ management: () => managementPage([managed("gpt-5-mini", "gpt-5-mini")]) })
|
||||
yield* seedCatalog
|
||||
yield* connect(cliCredential({ access: "expired-token", expires: Date.now() - hour }))
|
||||
yield* connect(cliCredential())
|
||||
yield* addPlugin(azure.endpoints).pipe(cli.provide)
|
||||
|
||||
expect(cli.commands).toEqual([])
|
||||
@@ -329,7 +403,7 @@ describe("AzurePlugin discovery", () => {
|
||||
const cli = yield* fakeAzureCli()
|
||||
const azure = yield* fakeAzure({
|
||||
resource: (request) =>
|
||||
request.authorization === "Bearer stored-token"
|
||||
request.authorization === "Bearer https://cognitiveservices.azure.com/.default-token"
|
||||
? resourceList(listed("gpt-5-mini", "gpt-5-mini"))
|
||||
: unauthorized(),
|
||||
})
|
||||
|
||||
@@ -73,10 +73,14 @@ const authorize = Effect.fn(function* () {
|
||||
return new URL(attempt.url)
|
||||
})
|
||||
|
||||
const request = Effect.fn(function* (providerID: Provider.ID, baseURL: string) {
|
||||
const request = Effect.fn(function* (
|
||||
providerID: Provider.ID,
|
||||
baseURL: string,
|
||||
sessionID = Session.ID.make("ses_test"),
|
||||
) {
|
||||
const hooks = yield* PluginHooks.Service
|
||||
const event = yield* hooks.trigger("session", "model.request", {
|
||||
sessionID: Session.ID.make("ses_test"),
|
||||
sessionID,
|
||||
agent: Agent.ID.make("build"),
|
||||
model: Model.Ref.make({ providerID, id: Model.ID.make("gpt-5.5") }),
|
||||
kind: "primary",
|
||||
@@ -767,8 +771,21 @@ describe("ChatGPTPlugin", () => {
|
||||
expect(provider.settings?.baseURL).toBe("https://api.openai.com/v1")
|
||||
expect(provider.headers).not.toHaveProperty("x-openai-chatpass-test")
|
||||
expect(direct.baseURL).toBe("https://api.openai.com/v1")
|
||||
expect(direct.headers).toEqual({})
|
||||
expect(direct.headers).toEqual({
|
||||
"session-id": "ses_test",
|
||||
"thread-id": "ses_test",
|
||||
"x-client-request-id": "ses_test",
|
||||
})
|
||||
expect(direct.hasHttpHooks).toBe(false)
|
||||
const sessions = yield* Session.Service
|
||||
const location = yield* Location.Service
|
||||
const parent = yield* sessions.create({ location: { directory: location.directory } })
|
||||
const child = yield* sessions.create({ parentID: parent.id })
|
||||
expect((yield* request(Provider.ID.openai, "https://api.openai.com/v1", child.id)).headers).toEqual({
|
||||
"session-id": parent.id,
|
||||
"thread-id": child.id,
|
||||
"x-client-request-id": child.id,
|
||||
})
|
||||
const eligible = required(yield* models.get(Provider.ID.openai, Model.ID.make("gpt-5.5")))
|
||||
expect(eligible.package).toBe("@opencode/ai/providers/openai")
|
||||
expect(eligible.headers).not.toHaveProperty("x-openai-chatpass-test")
|
||||
@@ -845,6 +862,7 @@ describe("ChatGPTPlugin", () => {
|
||||
expect(provider.settings?.transport).toBe("websocket")
|
||||
expect(model.settings?.transport).toBeUndefined()
|
||||
expect(direct.baseURL).toBe("https://api.openai.com/v1")
|
||||
expect(direct.headers).toEqual({})
|
||||
expect(direct.hasHttpHooks).toBe(false)
|
||||
expect(provider.headers).not.toHaveProperty("x-openai-chatpass-test")
|
||||
expect(required(yield* models.get(Provider.ID.openai, Model.ID.make("gpt-4.1"))).enabled).toBe(true)
|
||||
|
||||
@@ -41,6 +41,20 @@ const noRemoteConfig = HttpClient.make((request) =>
|
||||
Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status: 404 }))),
|
||||
)
|
||||
|
||||
// Periodic Console checks run on TestClock, but a loopback request takes real time that `drain` does not wait for.
|
||||
// Calling the server's handler in-process keeps each check within `drain`.
|
||||
const inProcess = (server: { fetch: (request: Request) => Response | Promise<Response> }) =>
|
||||
Effect.provideService(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) =>
|
||||
HttpClientRequest.toWeb(request).pipe(
|
||||
Effect.orDie,
|
||||
Effect.flatMap((web) => Effect.promise(async () => server.fetch(web))),
|
||||
Effect.map((response) => HttpClientResponse.fromWeb(request, response)),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
function consoleServer(orgID: string | null | undefined, unavailable = false) {
|
||||
const config: { authorization: string | null; orgID: string | null }[] = []
|
||||
const requests: string[] = []
|
||||
@@ -602,7 +616,7 @@ describe("OpencodePlugin", () => {
|
||||
yield* websearch.transform(() => {
|
||||
rebuilds.websearch++
|
||||
})
|
||||
yield* addPlugin()
|
||||
yield* addPlugin().pipe(inProcess(server))
|
||||
yield* drain
|
||||
const initial = { ...rebuilds }
|
||||
expect(state.requests).toBe(1)
|
||||
@@ -723,6 +737,7 @@ describe("OpencodePlugin", () => {
|
||||
}),
|
||||
}),
|
||||
),
|
||||
inProcess(server),
|
||||
)
|
||||
yield* drain
|
||||
|
||||
@@ -751,7 +766,7 @@ describe("OpencodePlugin", () => {
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("enforces organization policy statements from the Console", () =>
|
||||
it.effect("ignores unsupported managed actions and keys while enforcing supported policies", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() =>
|
||||
Bun.serve({
|
||||
@@ -761,12 +776,18 @@ describe("OpencodePlugin", () => {
|
||||
providers: { opencode: {} },
|
||||
experimental: {
|
||||
policies: [
|
||||
{ action: "future.use", resource: { names: ["anything"] }, effect: "future-effect", future: true },
|
||||
{ action: "provider.use", resource: "*", effect: "deny" },
|
||||
{ action: "provider.use", resource: "opencode", effect: "allow" },
|
||||
{ action: "permission", resource: "shell:sudo *", effect: "deny", audience: "ignored" },
|
||||
{ action: "tool.use", resource: "shell:*", effect: "deny" },
|
||||
{ action: "tool.use", resource: "shell:git *", effect: "allow" },
|
||||
{ action: "permission", resource: "*", effect: "deny" },
|
||||
{ action: "tool.use", resource: "shell:sudo *", effect: "deny", audience: "ignored" },
|
||||
{ action: "integration.use", resource: "mcp:restricted", effect: "deny" },
|
||||
],
|
||||
unknown: true,
|
||||
unknown: { future: true },
|
||||
},
|
||||
future: { unknown: true },
|
||||
}),
|
||||
}),
|
||||
),
|
||||
@@ -793,10 +814,30 @@ describe("OpencodePlugin", () => {
|
||||
statements: [
|
||||
{ action: "provider.use", resource: "*", effect: "deny" },
|
||||
{ action: "provider.use", resource: "opencode", effect: "allow" },
|
||||
{ action: "permission", resource: "shell:sudo *", effect: "deny" },
|
||||
{ action: "tool.use", resource: "shell:*", effect: "deny" },
|
||||
{ action: "tool.use", resource: "shell:git *", effect: "allow" },
|
||||
{ action: "tool.use", resource: "shell:sudo *", effect: "deny" },
|
||||
{ action: "integration.use", resource: "mcp:restricted", effect: "deny" },
|
||||
],
|
||||
organization: "Acme",
|
||||
})
|
||||
const hooks = yield* PluginHooks.Service
|
||||
const decision = yield* hooks.trigger("permission", "evaluate", {
|
||||
sessionID: Session.ID.make("ses_tool_policy"),
|
||||
action: "shell",
|
||||
resources: ["sudo ls"],
|
||||
effect: "allow",
|
||||
})
|
||||
expect(decision.effect).toBe("deny")
|
||||
expect(decision.message).toBe("Blocked by Acme's policy")
|
||||
expect(
|
||||
(yield* hooks.trigger("permission", "evaluate", {
|
||||
sessionID: Session.ID.make("ses_tool_policy"),
|
||||
action: "shell",
|
||||
resources: ["git status"],
|
||||
effect: "ask",
|
||||
})).effect,
|
||||
).toBe("ask")
|
||||
expect(yield* catalog.get(Provider.ID.anthropic)).toBeUndefined()
|
||||
expect(yield* catalog.get(Provider.ID.opencode)).toBeDefined()
|
||||
}),
|
||||
@@ -804,6 +845,66 @@ describe("OpencodePlugin", () => {
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("refreshes past future-only policies while retaining config on malformed supported statements", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const state: { policies: unknown[] } = {
|
||||
policies: [{ action: "tool.use", resource: "shell:sudo *", effect: "deny" }],
|
||||
}
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch: () => Response.json({ providers: { opencode: {} }, experimental: { policies: state.policies } }),
|
||||
})
|
||||
return { server, state }
|
||||
}),
|
||||
({ server, state }) =>
|
||||
Effect.gen(function* () {
|
||||
const credentials = yield* Credential.Service
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const providers = yield* Provider.Service
|
||||
const sudo: ConfigPolicy.Info = { action: "tool.use", resource: "shell:sudo *", effect: "deny" }
|
||||
const env: ConfigPolicy.Info = { action: "tool.use", resource: "edit:*.env", effect: "deny" }
|
||||
yield* credentials.create({
|
||||
integrationID: Integration.ID.make("opencode"),
|
||||
value: Credential.Key.make({
|
||||
type: "key",
|
||||
key: "secret",
|
||||
metadata: { server: server.url.origin, orgID: "org_acme", orgName: "Acme" },
|
||||
}),
|
||||
})
|
||||
yield* addPlugin().pipe(inProcess(server))
|
||||
yield* drain
|
||||
expect(managed.current()).toEqual({ statements: [sudo], organization: "Acme" })
|
||||
|
||||
for (const malformed of [
|
||||
{ action: "tool.use", resource: "shell:*", effect: "future-effect" },
|
||||
{ action: "tool.use", resource: 42, effect: "deny" },
|
||||
{ action: "tool.use", effect: "deny" },
|
||||
null,
|
||||
{},
|
||||
]) {
|
||||
state.policies = [env, malformed]
|
||||
yield* TestClock.adjust("1 minute")
|
||||
yield* drain
|
||||
expect(managed.current()).toEqual({ statements: [sudo], organization: "Acme" })
|
||||
expect(yield* providers.get(Provider.ID.opencode)).toBeDefined()
|
||||
}
|
||||
|
||||
state.policies = [{ action: "future.use", future: { values: [true] } }]
|
||||
yield* TestClock.adjust("1 minute")
|
||||
yield* drain
|
||||
expect(managed.current()).toEqual({ statements: [], organization: "Acme" })
|
||||
expect(yield* providers.get(Provider.ID.opencode)).toBeDefined()
|
||||
|
||||
state.policies = [{ action: "future.use", effect: { next: true } }, env]
|
||||
yield* TestClock.adjust("1 minute")
|
||||
yield* drain
|
||||
expect(managed.current()).toEqual({ statements: [env], organization: "Acme" })
|
||||
}),
|
||||
({ server }) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("keeps policy statements bound to the connected Console account", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
@@ -838,13 +939,13 @@ describe("OpencodePlugin", () => {
|
||||
metadata: { server: server.url.origin, orgID, orgName },
|
||||
}),
|
||||
})
|
||||
const sudo: ConfigPolicy.Info = { action: "permission", resource: "shell:sudo *", effect: "deny" }
|
||||
const env: ConfigPolicy.Info = { action: "permission", resource: "edit:*.env", effect: "deny" }
|
||||
const sudo: ConfigPolicy.Info = { action: "tool.use", resource: "shell:sudo *", effect: "deny" }
|
||||
const env: ConfigPolicy.Info = { action: "tool.use", resource: "edit:*.env", effect: "deny" }
|
||||
yield* providers.transform(() => {
|
||||
rebuilds.count++
|
||||
})
|
||||
const alpha = yield* account("org_alpha", "Alpha")
|
||||
yield* addPlugin()
|
||||
yield* addPlugin().pipe(inProcess(server))
|
||||
yield* drain
|
||||
const initial = rebuilds.count
|
||||
expect(state.requests).toBe(1)
|
||||
@@ -917,7 +1018,7 @@ describe("OpencodePlugin", () => {
|
||||
)
|
||||
return Response.json({
|
||||
providers: {},
|
||||
experimental: { policies: [{ action: "permission", resource: "shell:sudo *", effect: "deny" }] },
|
||||
experimental: { policies: [{ action: "tool.use", resource: "shell:sudo *", effect: "deny" }] },
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -932,7 +1033,7 @@ describe("OpencodePlugin", () => {
|
||||
integrations
|
||||
.get(Integration.ID.make("opencode"))
|
||||
.pipe(Effect.map((integration) => integration?.connections[0]?.status))
|
||||
const sudo: ConfigPolicy.Info = { action: "permission", resource: "shell:sudo *", effect: "deny" }
|
||||
const sudo: ConfigPolicy.Info = { action: "tool.use", resource: "shell:sudo *", effect: "deny" }
|
||||
yield* credentials.create({
|
||||
integrationID: Integration.ID.make("opencode"),
|
||||
value: Credential.Key.make({
|
||||
@@ -941,7 +1042,7 @@ describe("OpencodePlugin", () => {
|
||||
metadata: { server: `${server.url.origin}/console`, orgID: "org_acme", orgName: "Acme" },
|
||||
}),
|
||||
})
|
||||
yield* addPlugin()
|
||||
yield* addPlugin().pipe(inProcess(server))
|
||||
yield* drain
|
||||
expect(yield* status()).toBeUndefined()
|
||||
|
||||
@@ -1039,7 +1140,7 @@ describe("OpencodePlugin", () => {
|
||||
state.body ??
|
||||
Response.json({
|
||||
providers: {},
|
||||
experimental: { policies: [{ action: "permission", resource: "shell:sudo *", effect: "deny" }] },
|
||||
experimental: { policies: [{ action: "tool.use", resource: "shell:sudo *", effect: "deny" }] },
|
||||
}),
|
||||
})
|
||||
return { server, state }
|
||||
@@ -1049,12 +1150,12 @@ describe("OpencodePlugin", () => {
|
||||
const credentials = yield* Credential.Service
|
||||
const integrations = yield* Integration.Service
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const sudo: ConfigPolicy.Info = { action: "permission", resource: "shell:sudo *", effect: "deny" }
|
||||
const sudo: ConfigPolicy.Info = { action: "tool.use", resource: "shell:sudo *", effect: "deny" }
|
||||
yield* credentials.create({
|
||||
integrationID: Integration.ID.make("opencode"),
|
||||
value: Credential.Key.make({ type: "key", key: "secret", metadata: { server: server.url.origin } }),
|
||||
})
|
||||
yield* addPlugin()
|
||||
yield* addPlugin().pipe(inProcess(server))
|
||||
yield* drain
|
||||
|
||||
for (const body of [
|
||||
@@ -1171,7 +1272,7 @@ describe("OpencodePlugin", () => {
|
||||
})
|
||||
const status = () =>
|
||||
integrations.get(Integration.ID.make("opencode")).pipe(Effect.map((item) => item?.connections[0]?.status))
|
||||
yield* addPlugin()
|
||||
yield* addPlugin().pipe(inProcess(server))
|
||||
yield* drain
|
||||
|
||||
expect(yield* status()).toEqual({ status: "needs_auth", message: "Reconnect OpenCode Console to continue" })
|
||||
|
||||
@@ -13,6 +13,7 @@ import { Bus } from "@opencode/core/bus"
|
||||
import { Command } from "@opencode/core/command"
|
||||
import { Database } from "@opencode/core/database/database"
|
||||
import { Watcher } from "@opencode/core/filesystem/watcher"
|
||||
import { ManagedPolicy } from "@opencode/core/managed-policy"
|
||||
import { Instance } from "@opencode/core/instance"
|
||||
import { LocationServiceMap } from "@opencode/core/location-services"
|
||||
import { Location } from "@opencode/core/location"
|
||||
@@ -59,11 +60,13 @@ const instances = Layer.effect(
|
||||
LocationServiceMap.Service,
|
||||
Effect.gen(function* () {
|
||||
const watcher = yield* Watcher.Test
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const map = yield* LayerMap.make((ref: Location.Ref) => Instance.layer(ref, { replacements: bindings }), {
|
||||
idleTimeToLive: Duration.infinity,
|
||||
})
|
||||
const bindings: LayerNode.Replacements = [
|
||||
Global.node.replace(tempGlobalLayer),
|
||||
ManagedPolicy.node.replace(Layer.succeed(ManagedPolicy.Service, managed)),
|
||||
offlineModels,
|
||||
Npm.node.replace(npmLayer),
|
||||
Watcher.node.replace(Layer.succeed(Watcher.Service, watcher)),
|
||||
@@ -76,14 +79,13 @@ const instances = Layer.effect(
|
||||
]
|
||||
return map
|
||||
}),
|
||||
).pipe(Layer.provide(Watcher.testLayer))
|
||||
).pipe(Layer.provide(Watcher.testLayer), Layer.provide(ManagedPolicy.layer))
|
||||
|
||||
const it = testEffect(
|
||||
AppNodeBuilder.build(LayerNode.group([Database.node, Bus.node, SdkPlugins.node, LocationServiceMap.node]), [
|
||||
Global.node.replace(tempGlobalLayer),
|
||||
offlineModels,
|
||||
LocationServiceMap.node.replace(instances),
|
||||
]).pipe(Layer.provideMerge(Watcher.testLayer)),
|
||||
AppNodeBuilder.build(
|
||||
LayerNode.group([ManagedPolicy.node, Database.node, Bus.node, SdkPlugins.node, LocationServiceMap.node]),
|
||||
[Global.node.replace(tempGlobalLayer), offlineModels, LocationServiceMap.node.replace(instances)],
|
||||
).pipe(Layer.provideMerge(Watcher.testLayer)),
|
||||
)
|
||||
|
||||
const greeter = (command: string) => `export default {
|
||||
@@ -337,3 +339,57 @@ describe("PluginSupervisor reload", () => {
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it.live("applies organization integration changes to running external plugins", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* tmpdirScoped()
|
||||
const root = path.join(directory.path, "external/policy-fixture")
|
||||
const entered = path.join(directory.path, "entered")
|
||||
const configuration = path.join(directory.path, ".opencode/opencode.json")
|
||||
yield* Effect.promise(async () => {
|
||||
await Bun.write(
|
||||
path.join(root, "index.ts"),
|
||||
`await Bun.write(${JSON.stringify(entered)}, "loaded"); ${greeter("policy-greet")}`,
|
||||
)
|
||||
await Bun.write(
|
||||
configuration,
|
||||
JSON.stringify({
|
||||
plugins: [root],
|
||||
experimental: { policies: [{ action: "integration.use", resource: "plugin:*", effect: "deny" }] },
|
||||
}),
|
||||
)
|
||||
})
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
yield* Effect.gen(function* () {
|
||||
const plugins = yield* Plugin.Service
|
||||
const commands = yield* Command.Service
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const bus = yield* Bus.Service
|
||||
yield* plugins.awaitActivation
|
||||
expect(yield* commands.get("policy-greet")).toBeUndefined()
|
||||
expect(yield* Effect.promise(() => Bun.file(entered).exists())).toBe(false)
|
||||
yield* Effect.promise(() => Bun.write(configuration, JSON.stringify({ plugins: [root] })))
|
||||
yield* bus.publish(Event.Updated, {})
|
||||
yield* commands.get("policy-greet").pipe(
|
||||
Effect.flatMap((command) => (command ? Effect.void : Effect.fail("pending"))),
|
||||
Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }),
|
||||
)
|
||||
expect(yield* Effect.promise(() => Bun.file(entered).exists())).toBe(true)
|
||||
yield* managed.set({ statements: [{ action: "integration.use", resource: `plugin:${root}`, effect: "deny" }] })
|
||||
yield* commands.get("policy-greet").pipe(
|
||||
Effect.flatMap((command) => (command ? Effect.fail("pending") : Effect.void)),
|
||||
Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }),
|
||||
)
|
||||
yield* plugins.awaitActivation
|
||||
expect((yield* plugins.list()).some((plugin) => plugin.id === "greeter")).toBe(false)
|
||||
yield* managed.set({ statements: [] })
|
||||
yield* commands.get("policy-greet").pipe(
|
||||
Effect.flatMap((command) => (command ? Effect.void : Effect.fail("pending"))),
|
||||
Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }),
|
||||
)
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(locations.get(Location.Ref.make({ directory: AbsolutePath.make(directory.path) }))),
|
||||
)
|
||||
}),
|
||||
)
|
||||
@@ -1,81 +0,0 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Bus } from "@opencode/core/bus"
|
||||
import { Database } from "@opencode/core/database/database"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
import { EventTable } from "@opencode/core/event/sql"
|
||||
import { Location } from "@opencode/core/location"
|
||||
import { Project } from "@opencode/core/project"
|
||||
import { AbsolutePath } from "@opencode/core/schema"
|
||||
import { Session } from "@opencode/core/session"
|
||||
import { SessionEvent } from "@opencode/core/session/event"
|
||||
import { SessionExecution } from "@opencode/core/session/execution"
|
||||
import { SessionProjector } from "@opencode/core/session/projector"
|
||||
import { SessionStore } from "@opencode/core/session/store"
|
||||
import { LayerNode } from "@opencode/util/effect/layer-node"
|
||||
import { Effect } from "effect"
|
||||
import { eq } from "drizzle-orm"
|
||||
import { testEffect } from "./lib/effect"
|
||||
import { globalProjectNode } from "./lib/project"
|
||||
|
||||
const it = testEffect(
|
||||
AppNodeBuilder.build(
|
||||
LayerNode.group([Database.node, Bus.node, SessionProjector.node, SessionStore.node, Session.node]),
|
||||
[
|
||||
Bus.node.replace(Bus.configured({ persist: true })),
|
||||
Project.node.replace(globalProjectNode),
|
||||
SessionExecution.node.replace(SessionExecution.noopLayer),
|
||||
],
|
||||
),
|
||||
)
|
||||
const location = Location.Ref.make({ directory: AbsolutePath.make("/project") })
|
||||
|
||||
describe("Session.archive", () => {
|
||||
it.effect("archives and unarchives through one durable event each", () =>
|
||||
Effect.gen(function* () {
|
||||
const session = yield* Session.Service
|
||||
const { db } = yield* Database.Service
|
||||
const created = yield* session.create({ location })
|
||||
expect(created.time.archived).toBeUndefined()
|
||||
|
||||
yield* session.archive(created.id)
|
||||
yield* session.archive(created.id)
|
||||
expect((yield* session.get(created.id)).time.archived).toBeDefined()
|
||||
|
||||
yield* session.unarchive(created.id)
|
||||
yield* session.unarchive(created.id)
|
||||
expect((yield* session.get(created.id)).time.archived).toBeUndefined()
|
||||
|
||||
const types = (yield* db
|
||||
.select({ type: EventTable.type })
|
||||
.from(EventTable)
|
||||
.where(eq(EventTable.aggregate_id, created.id))
|
||||
.all()).map((event) => event.type)
|
||||
expect(types.filter((type) => type === Bus.versionedType(SessionEvent.Archived.type, 1))).toHaveLength(1)
|
||||
expect(types.filter((type) => type === Bus.versionedType(SessionEvent.Unarchived.type, 1))).toHaveLength(1)
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("filters listed sessions by archive state", () =>
|
||||
Effect.gen(function* () {
|
||||
const session = yield* Session.Service
|
||||
const active = yield* session.create({ location })
|
||||
const archived = yield* session.create({ location })
|
||||
yield* session.archive(archived.id)
|
||||
|
||||
const ids = (input?: Session.ListInput) =>
|
||||
session.list(input).pipe(Effect.map((page) => page.data.map((item) => item.id).toSorted()))
|
||||
expect(yield* ids()).toEqual([active.id, archived.id].toSorted())
|
||||
expect(yield* ids({ archived: false })).toEqual([active.id])
|
||||
expect(yield* ids({ archived: true })).toEqual([archived.id])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("rejects an unknown session", () =>
|
||||
Effect.gen(function* () {
|
||||
const session = yield* Session.Service
|
||||
const sessionID = Session.ID.make("ses_missing_archive")
|
||||
expect(yield* Effect.flip(session.archive(sessionID))).toEqual(new Session.NotFoundError({ sessionID }))
|
||||
expect(yield* Effect.flip(session.unarchive(sessionID))).toEqual(new Session.NotFoundError({ sessionID }))
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -59,6 +59,51 @@ describe("SessionModelRequest.unsupportedParts", () => {
|
||||
})
|
||||
})
|
||||
|
||||
test("replaces images xAI cannot decode and keeps png, jpeg and webp", () => {
|
||||
const image = (mime: string, name: string) => ({
|
||||
type: "media" as const,
|
||||
media: Media.base64("aGVsbG8=", mime),
|
||||
filename: name,
|
||||
})
|
||||
const user = [image("image/png", "a.png"), image("image/jpeg", "b.jpg"), image("image/webp", "c.webp")]
|
||||
const messages = [
|
||||
Message.user([...user, image("image/gif", "d.gif")]),
|
||||
Message.tool(
|
||||
ToolResultPart.make({
|
||||
id: "call_1",
|
||||
name: "read",
|
||||
result: {
|
||||
type: "content",
|
||||
value: [
|
||||
{ type: "text", text: "Image read successfully" },
|
||||
{ type: "file", uri: "data:image/gif;base64,R0lGODlh", mime: "image/gif", name: "e.gif" },
|
||||
],
|
||||
},
|
||||
}),
|
||||
),
|
||||
]
|
||||
const result = unsupportedParts(messages, capabilities(["text", "image"]), "xai")
|
||||
|
||||
expect(result[0]?.content).toEqual([
|
||||
...user,
|
||||
Message.text('ERROR: Cannot read "d.gif" (this model does not support image/gif input). Inform the user.'),
|
||||
])
|
||||
expect(result[1]?.content[0]).toMatchObject({
|
||||
type: "tool-result",
|
||||
result: {
|
||||
type: "content",
|
||||
value: [
|
||||
{ type: "text", text: "Image read successfully" },
|
||||
{
|
||||
type: "text",
|
||||
text: 'ERROR: Cannot read "e.gif" (this model does not support image/gif input). Inform the user.',
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
expect(unsupportedParts(messages, capabilities(["text", "image"]), "openai")).toEqual(messages)
|
||||
})
|
||||
|
||||
test("preserves supported media", () => {
|
||||
const message = Message.user({ type: "media", media: Media.base64("aGVsbG8=", "image/png") })
|
||||
expect(unsupportedParts([message], capabilities(["text", "image"]))[0]?.content).toEqual(message.content)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import { DateTime, Effect, Fiber, Option, Schema, Stream } from "effect"
|
||||
import { TestClock } from "effect/testing"
|
||||
import { asc, eq, sql } from "drizzle-orm"
|
||||
import { Database } from "@opencode/core/database/database"
|
||||
import { Agent } from "@opencode/core/agent"
|
||||
@@ -760,4 +761,51 @@ describe("SessionProjector", () => {
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("bumps session time_updated on step lifecycle events", () =>
|
||||
Effect.gen(function* () {
|
||||
const db = yield* seedSession({ time_created: 0, time_updated: 0 })
|
||||
const bus = yield* Bus.Service
|
||||
const updated = () =>
|
||||
db.select({ time_updated: SessionTable.time_updated }).from(SessionTable).get().pipe(Effect.orDie)
|
||||
const first = SessionMessage.ID.make("msg_touch_first")
|
||||
const second = SessionMessage.ID.make("msg_touch_second")
|
||||
|
||||
yield* TestClock.setTime(5)
|
||||
yield* bus.publish(SessionEvent.Step.Started, {
|
||||
sessionID,
|
||||
assistantMessageID: first,
|
||||
agent: build,
|
||||
model,
|
||||
started: 5,
|
||||
})
|
||||
expect(yield* updated()).toEqual({ time_updated: 5 })
|
||||
|
||||
yield* TestClock.setTime(9)
|
||||
yield* bus.publish(SessionEvent.Step.Ended, {
|
||||
sessionID,
|
||||
assistantMessageID: first,
|
||||
finish: "stop",
|
||||
cost: Money.USD.make(0),
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
})
|
||||
expect(yield* updated()).toEqual({ time_updated: 9 })
|
||||
|
||||
yield* TestClock.setTime(12)
|
||||
yield* bus.publish(SessionEvent.Step.Started, {
|
||||
sessionID,
|
||||
assistantMessageID: second,
|
||||
agent: build,
|
||||
model,
|
||||
started: 12,
|
||||
})
|
||||
yield* TestClock.setTime(15)
|
||||
yield* bus.publish(SessionEvent.Step.Failed, {
|
||||
sessionID,
|
||||
assistantMessageID: second,
|
||||
error: { type: "provider.invalid-request", message: "Failed" },
|
||||
})
|
||||
expect(yield* updated()).toEqual({ time_updated: 15 })
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -1,12 +1,14 @@
|
||||
import type { FileSystem } from "@opencode/core/filesystem"
|
||||
import path from "path"
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect, Layer, LayerMap } from "effect"
|
||||
import { Duration, Effect, Layer, LayerMap } from "effect"
|
||||
import { Database } from "@opencode/core/database/database"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
import { LayerNode } from "@opencode/util/effect/layer-node"
|
||||
import { makeGlobalNode } from "@opencode/util/effect/app-node"
|
||||
import { Bus } from "@opencode/core/bus"
|
||||
import { Config } from "@opencode/core/config"
|
||||
import { ManagedPolicy } from "@opencode/core/managed-policy"
|
||||
import { Image } from "@opencode/core/image"
|
||||
import { Location } from "@opencode/core/location"
|
||||
import { LocationServiceMap } from "@opencode/core/location-service-map"
|
||||
@@ -26,6 +28,7 @@ import { Skill } from "@opencode/core/skill"
|
||||
import { Event } from "@opencode/schema/event"
|
||||
import { testEffect } from "./lib/effect"
|
||||
import { globalProjectNode } from "./lib/project"
|
||||
import { registerIntegrationPolicy } from "./fixture/policy"
|
||||
|
||||
const location = Location.Ref.make({ directory: AbsolutePath.make("/project") })
|
||||
const info = Skill.Info.make({
|
||||
@@ -39,25 +42,51 @@ const locations = makeGlobalNode({
|
||||
service: LocationServiceMap.Service,
|
||||
layer: Layer.effect(
|
||||
LocationServiceMap.Service,
|
||||
LayerMap.make(
|
||||
(_ref: Location.Ref) =>
|
||||
// These tests need skill activation and prompt preparation from the same location services.
|
||||
// oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
|
||||
Layer.mergeAll(
|
||||
LayerNode.compile(LayerNode.group([PluginHooks.node, Image.node])),
|
||||
Layer.mock(Skill.Service, {
|
||||
get: (id) => Effect.succeed(id === info.id ? info : undefined),
|
||||
list: () => Effect.succeed([info]),
|
||||
}),
|
||||
Layer.mock(Plugin.Service, { awaitActivation: Effect.void }),
|
||||
) as unknown as Layer.Layer<LocationServices, FileSystem.DirectoryNotFoundError>,
|
||||
),
|
||||
Effect.gen(function* () {
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
return yield* LayerMap.make(
|
||||
(_ref: Location.Ref) =>
|
||||
// These tests need skill activation and prompt preparation from the same location services.
|
||||
// oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
|
||||
Layer.mergeAll(
|
||||
Layer.effectDiscard(
|
||||
Effect.gen(function* () {
|
||||
const skills = yield* Skill.Service
|
||||
yield* skills.transform((editor) => editor.add(info))
|
||||
yield* registerIntegrationPolicy({ skill: skills })
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(
|
||||
LayerNode.compile(
|
||||
LayerNode.group([PluginHooks.node, Image.node, Skill.node, Config.node, ManagedPolicy.node]),
|
||||
{
|
||||
replacements: [
|
||||
Config.node.replace(Config.testLayer()),
|
||||
ManagedPolicy.node.replace(Layer.succeed(ManagedPolicy.Service, managed)),
|
||||
],
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
Layer.mock(Plugin.Service, { awaitActivation: Effect.void }),
|
||||
) as unknown as Layer.Layer<LocationServices, FileSystem.DirectoryNotFoundError>,
|
||||
{ idleTimeToLive: Duration.infinity },
|
||||
)
|
||||
}),
|
||||
),
|
||||
deps: [],
|
||||
deps: [ManagedPolicy.node],
|
||||
})
|
||||
const it = testEffect(
|
||||
AppNodeBuilder.build(
|
||||
LayerNode.group([Database.node, Bus.node, SessionProjector.node, SessionStore.node, Session.node]),
|
||||
LayerNode.group([
|
||||
Database.node,
|
||||
Bus.node,
|
||||
SessionProjector.node,
|
||||
SessionStore.node,
|
||||
Session.node,
|
||||
ManagedPolicy.node,
|
||||
LocationServiceMap.node,
|
||||
]),
|
||||
[
|
||||
LocationServiceMap.node.replace(locations),
|
||||
Project.node.replace(globalProjectNode),
|
||||
@@ -67,6 +96,30 @@ const it = testEffect(
|
||||
)
|
||||
|
||||
describe("Session.skill", () => {
|
||||
it.effect("refuses blocked skill mentions and standalone activation without writing their content", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* Session.Service
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const session = yield* sessions.create({ location })
|
||||
yield* managed.set({ statements: [{ action: "integration.use", resource: "skill:effect", effect: "deny" }] })
|
||||
expect(
|
||||
yield* sessions.skill({ sessionID: session.id, skill: info.id, resume: false }).pipe(Effect.flip),
|
||||
).toMatchObject({ _tag: "Session.SkillNotFoundError", skill: info.id })
|
||||
expect(
|
||||
yield* sessions
|
||||
.prompt({
|
||||
sessionID: session.id,
|
||||
text: "@effect",
|
||||
skills: [{ id: info.id, mention: { start: 0, end: 7, text: "@effect" } }],
|
||||
resume: false,
|
||||
})
|
||||
.pipe(Effect.flip),
|
||||
).toMatchObject({ _tag: "Session.SkillNotFoundError", skill: info.id })
|
||||
expect(yield* sessions.messages({ sessionID: session.id })).toEqual([])
|
||||
expect(yield* sessions.inbox(session.id)).toEqual([])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("materializes mentioned skills on their owning prompt", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* Session.Service
|
||||
@@ -144,6 +197,8 @@ describe("Session.skill", () => {
|
||||
const bus = yield* Bus.Service
|
||||
const session = yield* sessions.create({ location })
|
||||
const id = SessionMessage.ID.make("msg_caller_skill")
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
yield* Skill.Service.use((skills) => skills.list()).pipe(Effect.provide(locations.get(session.location)))
|
||||
const events: Event.Payload[] = []
|
||||
yield* bus.listen((event) =>
|
||||
Effect.sync(() => {
|
||||
|
||||
@@ -1,14 +1,26 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Deferred, Effect, Fiber, Stream } from "effect"
|
||||
import { Deferred, Effect, Fiber, Layer, Schedule, Stream } from "effect"
|
||||
import { Agent } from "@opencode/core/agent"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
import { LayerNode } from "@opencode/util/effect/layer-node"
|
||||
import { Bus } from "@opencode/core/bus"
|
||||
import { Config } from "@opencode/core/config"
|
||||
import { ManagedPolicy } from "@opencode/core/managed-policy"
|
||||
import { Document, Event } from "@opencode/schema/config"
|
||||
import { AbsolutePath } from "@opencode/core/schema"
|
||||
import { Skill } from "@opencode/core/skill"
|
||||
import { SkillInstructions } from "@opencode/core/skill/instructions"
|
||||
import { testEffect } from "./lib/effect"
|
||||
import { readInitial } from "./lib/instructions"
|
||||
import { registerIntegrationPolicy } from "./fixture/policy"
|
||||
|
||||
const it = testEffect(AppNodeBuilder.build(LayerNode.group([Skill.node, Agent.node, Bus.node])))
|
||||
const configLayer = Config.testLayer()
|
||||
const it = testEffect(
|
||||
AppNodeBuilder.build(
|
||||
LayerNode.group([Skill.node, SkillInstructions.node, Agent.node, Bus.node, ManagedPolicy.node]),
|
||||
[Config.node.replace(configLayer)],
|
||||
).pipe(Layer.provideMerge(configLayer)),
|
||||
)
|
||||
|
||||
const info = (id: string, description: string) =>
|
||||
Skill.Info.make({
|
||||
@@ -20,6 +32,93 @@ const info = (id: string, description: string) =>
|
||||
})
|
||||
|
||||
describe("Skill", () => {
|
||||
it.live("hides and refuses denied skills while organization policy overrides local allows", () =>
|
||||
Effect.gen(function* () {
|
||||
const skills = yield* Skill.Service
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const config = yield* Config.Test
|
||||
yield* skills.transform((editor) => {
|
||||
editor.add(info("team:review", "Review"))
|
||||
editor.add(info("deploy", "Deploy"))
|
||||
})
|
||||
yield* config.setEntries([
|
||||
new Document({
|
||||
type: "document",
|
||||
info: {
|
||||
experimental: { policies: [{ action: "integration.use", resource: "skill:*", effect: "allow" }] },
|
||||
},
|
||||
}),
|
||||
])
|
||||
yield* managed.set({
|
||||
statements: [
|
||||
{ action: "integration.use", resource: "*", effect: "deny" },
|
||||
{ action: "integration.use", resource: "skill:team:review", effect: "allow" },
|
||||
],
|
||||
})
|
||||
yield* registerIntegrationPolicy({ skill: skills })
|
||||
expect(yield* skills.list()).toEqual([info("team:review", "Review")])
|
||||
expect(yield* skills.get(Skill.ID.make("deploy"))).toBeUndefined()
|
||||
expect(yield* skills.get(Skill.ID.make("team:review"))).toEqual(info("team:review", "Review"))
|
||||
const instructions = yield* SkillInstructions.Service
|
||||
const guidance = yield* instructions.load([]).pipe(Effect.flatMap(readInitial))
|
||||
expect(guidance.text).toContain("<id>team:review</id>")
|
||||
expect(guidance.text).not.toContain("deploy")
|
||||
|
||||
yield* managed.set({ statements: [{ action: "integration.use", resource: "skill:team:review", effect: "deny" }] })
|
||||
yield* waitUntil(skills.get(Skill.ID.make("team:review")).pipe(Effect.map((skill) => skill === undefined)))
|
||||
expect(yield* skills.get(Skill.ID.make("team:review"))).toBeUndefined()
|
||||
expect(yield* skills.list()).toEqual([info("deploy", "Deploy")])
|
||||
yield* managed.set({ statements: [] })
|
||||
yield* waitUntil(skills.list().pipe(Effect.map((skills) => skills.length === 2)))
|
||||
expect(yield* skills.list()).toHaveLength(2)
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("applies configuration precedence to skills without changing their registered values", () =>
|
||||
Effect.gen(function* () {
|
||||
const skills = yield* Skill.Service
|
||||
const config = yield* Config.Test
|
||||
yield* skills.transform((editor) => editor.add(info("review", "Review")))
|
||||
yield* config.setEntries([
|
||||
new Document({
|
||||
type: "document",
|
||||
info: { experimental: { policies: [{ action: "integration.use", resource: "skill:*", effect: "deny" }] } },
|
||||
}),
|
||||
new Document({
|
||||
type: "document",
|
||||
info: {
|
||||
experimental: { policies: [{ action: "integration.use", resource: "skill:review", effect: "allow" }] },
|
||||
},
|
||||
}),
|
||||
])
|
||||
const bus = yield* Bus.Service
|
||||
yield* registerIntegrationPolicy({ skill: skills, events: bus.subscribe() })
|
||||
expect(yield* skills.list()).toEqual([])
|
||||
expect(yield* skills.get(Skill.ID.make("review"))).toBeUndefined()
|
||||
yield* config.setEntries([])
|
||||
yield* bus.publish(Event.Updated, {})
|
||||
yield* waitUntil(skills.get(Skill.ID.make("review")).pipe(Effect.map((skill) => skill !== undefined)))
|
||||
expect(yield* skills.get(Skill.ID.make("review"))).toEqual(info("review", "Review"))
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("publishes catalog updates when managed policy changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const skills = yield* Skill.Service
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const bus = yield* Bus.Service
|
||||
yield* skills.transform((editor) => editor.add(info("review", "Review")))
|
||||
yield* registerIntegrationPolicy({ skill: skills })
|
||||
const updated = yield* Deferred.make<Skill.Info[]>()
|
||||
yield* bus.subscribe(Skill.Event.Updated).pipe(
|
||||
Stream.runForEach(() => skills.list().pipe(Effect.flatMap((values) => Deferred.succeed(updated, values)))),
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
yield* managed.set({ statements: [{ action: "integration.use", resource: "skill:review", effect: "deny" }] })
|
||||
expect(yield* Deferred.await(updated).pipe(Effect.timeout("1 second"))).toEqual([])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("reads the current editor entry by ID", () =>
|
||||
Effect.gen(function* () {
|
||||
const skill = yield* Skill.Service
|
||||
@@ -123,3 +222,12 @@ describe("Skill", () => {
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
const waitUntil = (condition: Effect.Effect<boolean>) =>
|
||||
condition.pipe(
|
||||
Effect.filterOrFail(
|
||||
(ready) => ready,
|
||||
() => new Error("Skill policy was not applied"),
|
||||
),
|
||||
Effect.retry({ times: 200, schedule: Schedule.spaced("10 millis") }),
|
||||
)
|
||||
@@ -8,6 +8,8 @@ import { Permission } from "@opencode/core/permission"
|
||||
import { AbsolutePath } from "@opencode/core/schema"
|
||||
import { Session } from "@opencode/core/session"
|
||||
import { Skill } from "@opencode/core/skill"
|
||||
import { Config } from "@opencode/core/config"
|
||||
import { ManagedPolicy } from "@opencode/core/managed-policy"
|
||||
import { SkillTool } from "@opencode/core/tool/plugin/skill"
|
||||
import { Tool } from "@opencode/core/tool"
|
||||
import { tmpdir } from "./fixture/tmpdir"
|
||||
@@ -18,6 +20,7 @@ import { permissionLayer } from "./lib/permission"
|
||||
import { makeLocationNode } from "@opencode/util/effect/app-node"
|
||||
import { FSUtil } from "@opencode/util/fs-util"
|
||||
import { toolIdentity, executeTool, registerToolPlugin, toolDefinitions } from "./lib/tool"
|
||||
import { registerIntegrationPolicy } from "./fixture/policy"
|
||||
|
||||
const skillToolNode = makeLocationNode({
|
||||
name: "test/skill-tool-plugin",
|
||||
@@ -28,6 +31,42 @@ const skillToolNode = makeLocationNode({
|
||||
const sessionID = Session.ID.make("ses_skill_tool_test")
|
||||
|
||||
describe("SkillTool", () => {
|
||||
it.effect("refuses a policy-blocked skill before authorization or content preparation", () =>
|
||||
Effect.gen(function* () {
|
||||
const skills = yield* Skill.Service
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const tools = yield* Tool.Service
|
||||
// This path does not exist; an attempted content scan would fail the test.
|
||||
yield* skills.transform((editor) =>
|
||||
editor.add(
|
||||
Skill.Info.make({
|
||||
id: Skill.ID.make("private"),
|
||||
name: Skill.Name.make("Private"),
|
||||
path: AbsolutePath.make("/unavailable/private/SKILL.md"),
|
||||
content: "Private instructions",
|
||||
}),
|
||||
),
|
||||
)
|
||||
yield* managed.set({ statements: [{ action: "integration.use", resource: "skill:private", effect: "deny" }] })
|
||||
yield* registerIntegrationPolicy({ skill: skills })
|
||||
expect(
|
||||
yield* executeTool(tools, {
|
||||
sessionID,
|
||||
...toolIdentity,
|
||||
call: { type: "tool-call", id: "call-policy-denied-skill", name: "skill", input: { id: "private" } },
|
||||
}),
|
||||
).toEqual({ status: "error", error: { type: "tool.execution", message: "Unable to load skill private" } })
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AppNodeBuilder.build(LayerNode.group([Tool.node, skillToolNode, Skill.node, Config.node, ManagedPolicy.node]), [
|
||||
Config.node.replace(Config.testLayer()),
|
||||
Permission.node.replace(permissionLayer({ assert: () => Effect.die("Blocked skill reached authorization") })),
|
||||
Image.node.replace(imagePassthrough),
|
||||
]),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("lists available skills, authorizes the selected ID, and loads model-facing content", () =>
|
||||
Effect.acquireRelease(
|
||||
Effect.promise(() => tmpdir()),
|
||||
|
||||
@@ -110,6 +110,15 @@ describe("WriteTool", () => {
|
||||
Effect.gen(function* () {
|
||||
expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["write", "execute"])
|
||||
const settled = yield* executeTool(registry, call({ path: "src/new.txt", content: "created" }))
|
||||
const files = [
|
||||
{
|
||||
file: "src/new.txt",
|
||||
status: "added",
|
||||
additions: 1,
|
||||
deletions: 0,
|
||||
patch: expect.stringContaining("+created"),
|
||||
},
|
||||
]
|
||||
expect(settled).toEqual({
|
||||
status: "completed",
|
||||
output: {
|
||||
@@ -117,8 +126,10 @@ describe("WriteTool", () => {
|
||||
target: path.join(yield* Effect.promise(() => fs.realpath(tmp.path)), "src", "new.txt"),
|
||||
resource: "src/new.txt",
|
||||
existed: false,
|
||||
files,
|
||||
},
|
||||
content: [{ type: "text", text: "Created file successfully: src/new.txt" }],
|
||||
metadata: { files },
|
||||
})
|
||||
expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "src", "new.txt"), "utf8"))).toBe(
|
||||
"created",
|
||||
@@ -145,7 +156,7 @@ describe("WriteTool", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("formats the committed file", () =>
|
||||
it.live("formats the committed file and returns the diff for final formatted content", () =>
|
||||
withTempDir((tmp) => {
|
||||
const fixture = makeWriteFixture()
|
||||
const target = path.join(tmp.path, "formatted.txt")
|
||||
@@ -154,13 +165,33 @@ describe("WriteTool", () => {
|
||||
await fs.writeFile(file, (await fs.readFile(file, "utf8")).toUpperCase())
|
||||
return true
|
||||
})
|
||||
return withTool(tmp.path, fixture, (registry) =>
|
||||
Effect.gen(function* () {
|
||||
expect(yield* executeTool(registry, call({ path: "formatted.txt", content: "format me" }))).toMatchObject({
|
||||
status: "completed",
|
||||
})
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("FORMAT ME")
|
||||
}),
|
||||
return Effect.promise(() => fs.writeFile(target, "before\n")).pipe(
|
||||
Effect.andThen(
|
||||
withTool(tmp.path, fixture, (registry) =>
|
||||
executeTool(registry, call({ path: "formatted.txt", content: "format me\n" })),
|
||||
),
|
||||
),
|
||||
Effect.andThen((settled) =>
|
||||
Effect.gen(function* () {
|
||||
expect(settled.status).toBe("completed")
|
||||
if (settled.status !== "completed") return
|
||||
const files = [
|
||||
{
|
||||
file: "formatted.txt",
|
||||
status: "modified",
|
||||
additions: 1,
|
||||
deletions: 1,
|
||||
patch: expect.stringMatching(/-before\n\+FORMAT ME\n/),
|
||||
},
|
||||
]
|
||||
expect(settled.output).toMatchObject({ files })
|
||||
expect(settled.metadata).toMatchObject({ files })
|
||||
expect(fixture.assertions[0]?.metadata).toMatchObject({
|
||||
files: [{ patch: expect.stringContaining("+format me") }],
|
||||
})
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("FORMAT ME\n")
|
||||
}),
|
||||
),
|
||||
)
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# `@opencode/plugin`
|
||||
|
||||
Authoring interfaces and runtime loader support for OpenCode V2 plugins:
|
||||
|
||||
- `@opencode/plugin` — [Promise plugin API](./src/README.md)
|
||||
- `@opencode/plugin/effect` — [Effect plugin API](./src/effect/README.md)
|
||||
- `@opencode/plugin/rpc` — portable RPC contract definitions
|
||||
- `@opencode/plugin/tui` — terminal UI plugin API
|
||||
|
||||
## Packaging And Runtime `effect`
|
||||
|
||||
When the OpenCode CLI loads server or TUI plugins, it resolves imports of `effect`, exported `effect/*` subpaths, and `@opencode/plugin` entrypoints (including imports from dependencies inside a plugin's `node_modules`) to the host's runtime module instances so fibers, loggers, and `Schema` parsers share one copy.
|
||||
|
||||
- Declare `effect` as a `peerDependency` (and `devDependency` for local type-checking and testing) rather than a bundled runtime dependency.
|
||||
- Do not bundle `effect` into published plugin files; if you build with a bundler, keep `effect` and `effect/*` external. Two copies of `effect` do not share fiber, logger, or `Schema` internals.
|
||||
- Plugins and their `node_modules` dependencies always receive OpenCode's host `effect` instance. Use `effect` APIs and module paths compatible with the OpenCode release you target; dependencies built on another `effect` major (such as Effect 3) are not supported.
|
||||
- Only public `effect` subpaths are provided. A plugin that imports one of Effect's private `internal` modules fails to load with an error naming the path.
|
||||
- The compiled OpenCode binary does not include the Scalar and Swagger UI assets used by Effect's HTTP API docs pages; serving those pages from a plugin shows a notice instead.
|
||||
@@ -13,6 +13,7 @@
|
||||
".": "./src/promise/index.ts",
|
||||
"./effect": "./src/effect/index.ts",
|
||||
"./host": "./src/host.ts",
|
||||
"./runtime": "./src/runtime.ts",
|
||||
"./tui": "./src/tui/index.ts",
|
||||
"./*": "./src/*.ts"
|
||||
},
|
||||
@@ -37,8 +38,8 @@
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opencode/theme": "workspace:*",
|
||||
"@opentui/core": ">=0.5.14",
|
||||
"@opentui/solid": ">=0.5.14",
|
||||
"@opentui/core": ">=0.5.16",
|
||||
"@opentui/solid": ">=0.5.16",
|
||||
"solid-js": ">=1.9.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
|
||||
@@ -28,6 +28,13 @@ export interface IntegrationKeyMethod {
|
||||
readonly form?: Form.Fields
|
||||
}
|
||||
|
||||
export interface IntegrationExternalMethod {
|
||||
readonly id: string
|
||||
readonly type: "external"
|
||||
readonly label: string
|
||||
readonly form?: Form.Fields
|
||||
}
|
||||
|
||||
export interface IntegrationEnvMethod {
|
||||
readonly type: "env"
|
||||
readonly names: ReadonlyArray<string>
|
||||
@@ -37,6 +44,7 @@ export type IntegrationMethod =
|
||||
| IntegrationOAuthMethod
|
||||
| IntegrationCommandMethod
|
||||
| IntegrationKeyMethod
|
||||
| IntegrationExternalMethod
|
||||
| IntegrationEnvMethod
|
||||
|
||||
export type IntegrationOAuthAuthorization = {
|
||||
@@ -70,6 +78,10 @@ export type IntegrationMethodRegistration =
|
||||
readonly integrationID: string
|
||||
readonly method: IntegrationKeyMethod
|
||||
}
|
||||
| {
|
||||
readonly integrationID: string
|
||||
readonly method: IntegrationExternalMethod
|
||||
}
|
||||
| {
|
||||
readonly integrationID: string
|
||||
readonly method: IntegrationEnvMethod
|
||||
|
||||
@@ -356,6 +356,10 @@ export function fromPromise(plugin: Plugin) {
|
||||
get: adaptApiMethod(IntegrationEndpoints["integration.get"], host.integration.get),
|
||||
connect: {
|
||||
key: adaptApiMethod(IntegrationEndpoints["integration.connect.key"], host.integration.connect.key),
|
||||
external: adaptApiMethod(
|
||||
IntegrationEndpoints["integration.connect.external"],
|
||||
host.integration.connect.external,
|
||||
),
|
||||
},
|
||||
oauth: {
|
||||
connect: adaptApiMethod(
|
||||
|
||||
@@ -27,6 +27,13 @@ export interface IntegrationKeyMethod {
|
||||
readonly form?: Form.Fields
|
||||
}
|
||||
|
||||
export interface IntegrationExternalMethod {
|
||||
readonly id: string
|
||||
readonly type: "external"
|
||||
readonly label: string
|
||||
readonly form?: Form.Fields
|
||||
}
|
||||
|
||||
export interface IntegrationEnvMethod {
|
||||
readonly type: "env"
|
||||
readonly names: ReadonlyArray<string>
|
||||
@@ -36,6 +43,7 @@ export type IntegrationMethod =
|
||||
| IntegrationOAuthMethod
|
||||
| IntegrationCommandMethod
|
||||
| IntegrationKeyMethod
|
||||
| IntegrationExternalMethod
|
||||
| IntegrationEnvMethod
|
||||
|
||||
export type IntegrationOAuthAuthorization = {
|
||||
@@ -68,6 +76,7 @@ export type IntegrationMethodRegistration =
|
||||
readonly integrationID: string
|
||||
readonly method: IntegrationKeyMethod
|
||||
}
|
||||
| { readonly integrationID: string; readonly method: IntegrationExternalMethod }
|
||||
| { readonly integrationID: string; readonly method: IntegrationEnvMethod }
|
||||
|
||||
export interface IntegrationEditor {
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { existsSync, realpathSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
|
||||
export type RuntimeModuleLoader = () => Record<string, unknown> | Promise<Record<string, unknown>>
|
||||
|
||||
const runtimePackages = ["effect", "@opencode/plugin"] as const
|
||||
|
||||
export function resolveHostPackageRoots(from = import.meta.dir, packages: readonly string[] = runtimePackages) {
|
||||
return packages.flatMap((pkgName) => {
|
||||
const dir = path.dirname(Bun.resolveSync(`${pkgName}/package.json`, from))
|
||||
return [dir, findNodeModulesDir(pkgName, from, dir)]
|
||||
})
|
||||
}
|
||||
|
||||
export function loadRuntimeModules(): Readonly<Record<string, RuntimeModuleLoader>> {
|
||||
const entries = discoverPluginRuntimeSpecifiers()
|
||||
const effectEntry = entries.get("effect")
|
||||
if (effectEntry) require(effectEntry)
|
||||
return Object.fromEntries(
|
||||
[...entries.entries()].map(([specifier, resolved]) => [specifier, createLoader(resolved)]),
|
||||
)
|
||||
}
|
||||
|
||||
export function discoverPluginRuntimeSpecifiers(
|
||||
from = import.meta.dir,
|
||||
packages: readonly string[] = runtimePackages,
|
||||
): ReadonlyMap<string, string> {
|
||||
const entries = new Map<string, string>()
|
||||
for (const pkgName of packages) {
|
||||
const realDir = path.dirname(Bun.resolveSync(`${pkgName}/package.json`, from))
|
||||
// Resolve workspace @opencode/plugin paths via node_modules so OpenTUI does not wrap host files in async rewrite loaders.
|
||||
const loadDir = findNodeModulesDir(pkgName, from, realDir)
|
||||
const toLoadPath = (resolved: string) =>
|
||||
loadDir === realDir ? resolved : path.join(loadDir, path.relative(realDir, resolved))
|
||||
const rootEntry = Bun.resolveSync(pkgName, from)
|
||||
const relParts = path.relative(realDir, rootEntry).replaceAll("\\", "/").split("/")
|
||||
const scanDir = relParts.length > 1 ? path.join(realDir, relParts[0]) : realDir
|
||||
const ext = path.extname(rootEntry) || ".js"
|
||||
entries.set(pkgName, toLoadPath(rootEntry))
|
||||
for (const file of new Bun.Glob(`**/*${ext}`).scanSync({ cwd: scanDir })) {
|
||||
const normalized = file.replaceAll("\\", "/")
|
||||
if (
|
||||
normalized.startsWith("internal/") ||
|
||||
normalized.includes("/internal/") ||
|
||||
normalized.startsWith("source.") ||
|
||||
normalized.startsWith("runtime")
|
||||
) {
|
||||
continue
|
||||
}
|
||||
const base = normalized.slice(0, -ext.length)
|
||||
if (base === "index") continue
|
||||
const candidates = base.endsWith("/index")
|
||||
? [`${pkgName}/${base.slice(0, -"/index".length)}`, `${pkgName}/${base}`]
|
||||
: [`${pkgName}/${base}`]
|
||||
for (const specifier of candidates) {
|
||||
if (entries.has(specifier)) continue
|
||||
try {
|
||||
entries.set(specifier, toLoadPath(Bun.resolveSync(specifier, from)))
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
export function pluginRuntimeLoaderCode(specifier: string, entries: ReadonlyMap<string, string>) {
|
||||
if (specifier.startsWith("effect/")) {
|
||||
const slash = specifier.lastIndexOf("/")
|
||||
const parent = specifier.slice(0, slash)
|
||||
const member = specifier.slice(slash + 1)
|
||||
const parentResolved = entries.get(parent)
|
||||
const resolved = entries.get(specifier)
|
||||
if (
|
||||
member !== "index" &&
|
||||
parentResolved &&
|
||||
resolved &&
|
||||
(require(parentResolved) as Record<string, unknown>)[member] === require(resolved)
|
||||
) {
|
||||
return `() => require(${JSON.stringify(parent)})[${JSON.stringify(member)}]`
|
||||
}
|
||||
}
|
||||
return `() => require(${JSON.stringify(specifier)})`
|
||||
}
|
||||
|
||||
export function createLoader(resolved: string): RuntimeModuleLoader {
|
||||
let cached: Record<string, unknown> | undefined
|
||||
let pending: Promise<Record<string, unknown>> | undefined
|
||||
return () => {
|
||||
if (cached) return cached
|
||||
if (pending) return pending
|
||||
try {
|
||||
return (cached = require(resolved) as Record<string, unknown>)
|
||||
} catch {
|
||||
return (pending = import(pathToFileURL(resolved).href).then(
|
||||
(mod: Record<string, unknown>) => (cached = mod),
|
||||
(error) => {
|
||||
pending = undefined
|
||||
throw error
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function findNodeModulesDir(pkgName: string, from: string, realDir: string) {
|
||||
if (/[/\\]node_modules[/\\]/.test(realDir)) return realDir
|
||||
for (let dir = path.resolve(from); ; dir = path.dirname(dir)) {
|
||||
const candidate = path.join(dir, "node_modules", pkgName)
|
||||
if (existsSync(candidate) && realpathSync(candidate) === realDir) return candidate
|
||||
if (path.dirname(dir) === dir) return realDir
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { loadRuntimeModules, resolveHostPackageRoots, type RuntimeModuleLoader } from "./runtime-modules.js"
|
||||
|
||||
const foreignPkgSuffix = String.raw`(?:node_modules[/\\](@opencode[/\\]plugin|effect)|(@opencode[/\\]plugin|effect)@[^/\\]+@@@\d+)`
|
||||
const foreignPkgPattern = new RegExp(String.raw`^(.*[/\\]${foreignPkgSuffix})[/\\](.+)$`)
|
||||
|
||||
let installed: Readonly<Record<string, RuntimeModuleLoader>> | undefined
|
||||
|
||||
export function provides(specifier: string) {
|
||||
return installed !== undefined && Object.hasOwn(installed, specifier)
|
||||
}
|
||||
|
||||
export function ensurePluginRuntime() {
|
||||
if (typeof Bun === "undefined") return {}
|
||||
if (installed) return installed
|
||||
const modules = loadRuntimeModules()
|
||||
installed = modules
|
||||
Bun.plugin({
|
||||
name: "opencode-plugin-runtime",
|
||||
setup(build) {
|
||||
for (const [specifier, load] of Object.entries(modules)) {
|
||||
build.module(specifier, () => {
|
||||
const exports = load()
|
||||
return exports instanceof Promise
|
||||
? exports.then((value) => ({ exports: value, loader: "object" as const }))
|
||||
: { exports, loader: "object" as const }
|
||||
})
|
||||
}
|
||||
build.onLoad({ filter: createForeignPackageFilter() }, (args) => {
|
||||
const match = args.path.match(foreignPkgPattern)
|
||||
const target = match ? `${match[2] ?? match[3]}/${match[4]}`.replaceAll("\\", "/") : args.path
|
||||
throw new Error(
|
||||
`Cannot load "${target}" from plugin node_modules: "${target}" is not provided by OpenCode; plugins must use the host's "effect" and "@opencode/plugin" modules.`,
|
||||
)
|
||||
})
|
||||
},
|
||||
})
|
||||
return modules
|
||||
}
|
||||
|
||||
export function createForeignPackageFilter(rootsInput: Iterable<string> = resolveHostPackageRoots()) {
|
||||
const suffix = String.raw`[/\\]${foreignPkgSuffix}[/\\].*\.[cm]?[jt]sx?(?:[?#].*)?$`
|
||||
const roots = [...new Set(rootsInput)]
|
||||
if (roots.length === 0) return new RegExp(suffix)
|
||||
const escaped = roots
|
||||
.map((value) =>
|
||||
value
|
||||
.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
||||
.replace(/(?:\\\/|\\\\|\/)+/g, "[/\\\\]"),
|
||||
)
|
||||
.join("|")
|
||||
return new RegExp(`^(?!(?:${escaped})[/\\\\]).*${suffix}`)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { fileURLToPath, pathToFileURL } from "node:url"
|
||||
import { Host } from "./host.js"
|
||||
import { provides } from "./runtime.js"
|
||||
import { localSource } from "./source.js"
|
||||
import { missingPackageTarget } from "./source.package.js"
|
||||
|
||||
@@ -39,6 +40,7 @@ export async function prepareSource(entrypoint: string, track: (file: string, di
|
||||
? new URL(item.path, pathToFileURL(file))
|
||||
: localSource(item.path, path.dirname(file))
|
||||
if (!local) {
|
||||
if (provides(item.path)) continue
|
||||
try {
|
||||
Bun.resolveSync(item.path, path.dirname(file))
|
||||
} catch {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"
|
||||
import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { describe, it } from "node:test"
|
||||
@@ -11,7 +11,7 @@ const source = 'throw new Error("Plugin code must not run during resolution")'
|
||||
const name = "@fixture/plugin"
|
||||
|
||||
async function fixture(files: Record<string, string>, installed = false) {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "opencode-host-"))
|
||||
const root = await realpath(await mkdtemp(path.join(tmpdir(), "opencode-host-")))
|
||||
const directory = installed ? path.join(root, "node_modules", name) : root
|
||||
await Promise.all(
|
||||
Object.entries(files).map(async ([file, content]) => {
|
||||
|
||||
@@ -18,7 +18,7 @@ import { AgentGroup } from "./groups/agent.js"
|
||||
import { PluginGroup } from "./groups/plugin.js"
|
||||
import { ServerGroup } from "./groups/server.js"
|
||||
import { DebugGroup } from "./groups/debug.js"
|
||||
import { PtyGroup } from "./groups/pty.js"
|
||||
import { makePtyGroup } from "./groups/pty.js"
|
||||
import { PersistentPtyGroup } from "./groups/persistent-pty.js"
|
||||
import { ShellGroup } from "./groups/shell.js"
|
||||
import { ReferenceGroup } from "./groups/reference.js"
|
||||
@@ -47,12 +47,15 @@ type LocationGroups<LocationId extends HttpApiMiddleware.AnyId> =
|
||||
| HttpApiGroup.AddMiddleware<typeof CommandGroup, LocationId>
|
||||
| HttpApiGroup.AddMiddleware<typeof SkillGroup, LocationId>
|
||||
| HttpApiGroup.AddMiddleware<typeof RpcGroup, LocationId>
|
||||
| HttpApiGroup.AddMiddleware<typeof PtyGroup, LocationId>
|
||||
| HttpApiGroup.AddMiddleware<typeof ShellGroup, LocationId>
|
||||
| HttpApiGroup.AddMiddleware<typeof ReferenceGroup, LocationId>
|
||||
| HttpApiGroup.AddMiddleware<typeof VcsGroup, LocationId>
|
||||
| HttpApiGroup.AddMiddleware<typeof ConfigGroup, LocationId>
|
||||
|
||||
type PtyGroups<LocationId extends HttpApiMiddleware.AnyId, LocationService> = ReturnType<
|
||||
typeof makePtyGroup<LocationId, LocationService>
|
||||
>
|
||||
|
||||
type SessionGroups<
|
||||
SessionLocationId extends HttpApiMiddleware.AnyId,
|
||||
SessionLocationService,
|
||||
@@ -95,6 +98,7 @@ type ApiGroups<
|
||||
| typeof CredentialGroup
|
||||
| LocationGroups<LocationId>
|
||||
| LocationGroup<LocationId, LocationService>
|
||||
| PtyGroups<LocationId, LocationService>
|
||||
| FormGroups<LocationId, LocationService>
|
||||
| SessionGroups<SessionLocationId, SessionLocationService, FormLocationId, FormLocationService>
|
||||
| MixedMiddlewareGroups<LocationId, LocationService, SessionLocationId, SessionLocationService>
|
||||
@@ -173,7 +177,7 @@ const makeApiFromGroup = <
|
||||
.add(SkillGroup.middleware(locationMiddleware))
|
||||
.add(RpcGroup.middleware(locationMiddleware))
|
||||
.add(eventGroup)
|
||||
.add(PtyGroup.middleware(locationMiddleware))
|
||||
.add(makePtyGroup(locationMiddleware))
|
||||
.add(PersistentPtyGroup)
|
||||
.add(ShellGroup.middleware(locationMiddleware))
|
||||
.add(ReferenceGroup.middleware(locationMiddleware))
|
||||
|
||||
@@ -79,6 +79,27 @@ export const IntegrationGroup = HttpApiGroup.make("server.integration")
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.post("integration.connect.external", "/api/integration/:integrationID/connect/external", {
|
||||
params: { integrationID: Integration.ID },
|
||||
query: LocationQuery,
|
||||
payload: Schema.Struct({
|
||||
methodID: Integration.MethodID,
|
||||
answer: Schema.optional(Form.Answer),
|
||||
label: Schema.optional(Schema.String),
|
||||
}),
|
||||
success: HttpApiSchema.NoContent,
|
||||
error: [IntegrationNotFoundError, InvalidRequestError],
|
||||
})
|
||||
.annotateMerge(locationQueryOpenApi)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "integration.connect.external",
|
||||
summary: "Connect with external credentials",
|
||||
description: "Run an external authentication method and store a reference to its credential source.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.post("integration.oauth.connect", "/api/integration/:integrationID/connect/oauth", {
|
||||
params: { integrationID: Integration.ID },
|
||||
|
||||
+127
-124
@@ -1,9 +1,9 @@
|
||||
import { Pty } from "@opencode/schema/pty"
|
||||
import { PtyTicket } from "@opencode/schema/pty-ticket"
|
||||
import { Location } from "@opencode/schema/location"
|
||||
import { Schema } from "effect"
|
||||
import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
|
||||
import { ForbiddenError, PtyNotFoundError } from "../errors.js"
|
||||
import { Context, Schema } from "effect"
|
||||
import { HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
|
||||
import { ForbiddenError, LocationNotFoundError, PtyNotFoundError } from "../errors.js"
|
||||
import { LocationQuery, locationQueryOpenApi } from "./location.js"
|
||||
|
||||
export const PTY_CONNECT_TICKET_QUERY = "ticket"
|
||||
@@ -18,127 +18,130 @@ export function hasPtyConnectTicketURL(url: URL) {
|
||||
return PTY_CONNECT_PATH.test(url.pathname) && !!url.searchParams.get(PTY_CONNECT_TICKET_QUERY)
|
||||
}
|
||||
|
||||
export const PtyGroup = HttpApiGroup.make("server.pty")
|
||||
.add(
|
||||
HttpApiEndpoint.get("pty.list", "/api/pty", {
|
||||
query: LocationQuery,
|
||||
success: Location.response(Schema.Array(Pty.Info)),
|
||||
})
|
||||
.annotateMerge(locationQueryOpenApi)
|
||||
.annotateMerge(
|
||||
export const makePtyGroup = <LocationId extends HttpApiMiddleware.AnyId, LocationService>(
|
||||
locationMiddleware: Context.Key<LocationId, LocationService>,
|
||||
) =>
|
||||
HttpApiGroup.make("server.pty")
|
||||
.add(
|
||||
HttpApiEndpoint.get("pty.list", "/api/pty", {
|
||||
query: LocationQuery,
|
||||
success: Location.response(Schema.Array(Pty.Info)),
|
||||
})
|
||||
.annotateMerge(locationQueryOpenApi)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "pty.list",
|
||||
summary: "List PTY sessions",
|
||||
description: "List PTY sessions for a location, including exited sessions retained until removal.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.post("pty.create", "/api/pty", {
|
||||
query: LocationQuery,
|
||||
payload: Pty.CreateInput,
|
||||
success: Location.response(Pty.Info),
|
||||
})
|
||||
.annotateMerge(locationQueryOpenApi)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "pty.create",
|
||||
summary: "Create PTY session",
|
||||
description: "Create a pseudo-terminal session for a location.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.get("pty.get", "/api/pty/:ptyID", {
|
||||
params: { ptyID: Pty.ID },
|
||||
query: LocationQuery,
|
||||
success: Location.response(Pty.Info),
|
||||
error: PtyNotFoundError,
|
||||
})
|
||||
.annotateMerge(locationQueryOpenApi)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "pty.get",
|
||||
summary: "Get PTY session",
|
||||
description: "Get one PTY session, including its exit code once exited.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.put("pty.update", "/api/pty/:ptyID", {
|
||||
params: { ptyID: Pty.ID },
|
||||
query: LocationQuery,
|
||||
payload: Pty.UpdateInput,
|
||||
success: Location.response(Pty.Info),
|
||||
error: PtyNotFoundError,
|
||||
})
|
||||
.annotateMerge(locationQueryOpenApi)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "pty.update",
|
||||
summary: "Update PTY session",
|
||||
description: "Update the title or viewport size of one PTY session.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.delete("pty.remove", "/api/pty/:ptyID", {
|
||||
params: { ptyID: Pty.ID },
|
||||
query: LocationQuery,
|
||||
success: HttpApiSchema.NoContent,
|
||||
error: PtyNotFoundError,
|
||||
})
|
||||
.annotateMerge(locationQueryOpenApi)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "pty.remove",
|
||||
summary: "Remove PTY session",
|
||||
description: "Terminate and remove one PTY session.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.post("pty.connectToken", "/api/pty/:ptyID/connect-token", {
|
||||
params: { ptyID: Pty.ID },
|
||||
query: LocationQuery,
|
||||
headers: Schema.Struct({ [PTY_CONNECT_TOKEN_HEADER]: Schema.optional(Schema.String) }),
|
||||
success: Location.response(PtyTicket.ConnectToken),
|
||||
error: [ForbiddenError, PtyNotFoundError],
|
||||
})
|
||||
.annotateMerge(locationQueryOpenApi)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "pty.connect.token",
|
||||
summary: "Create PTY WebSocket token",
|
||||
description: "Create a short-lived single-use ticket for opening a PTY WebSocket connection.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.middleware(locationMiddleware)
|
||||
.add(
|
||||
// Query fields are decoded in the raw handler before upgrade work.
|
||||
HttpApiEndpoint.get("pty.connect", "/api/pty/:ptyID/connect", {
|
||||
params: { ptyID: Pty.ID },
|
||||
success: Schema.Boolean,
|
||||
error: [ForbiddenError, PtyNotFoundError, LocationNotFoundError],
|
||||
}).annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "pty.list",
|
||||
summary: "List PTY sessions",
|
||||
description: "List PTY sessions for a location, including exited sessions retained until removal.",
|
||||
identifier: "pty.connect",
|
||||
summary: "Connect to PTY session",
|
||||
description: "Establish a WebSocket connection streaming PTY output and accepting terminal input.",
|
||||
transform: (operation) => ({
|
||||
...operation,
|
||||
"x-websocket": true,
|
||||
parameters: [
|
||||
...(operation.parameters ?? []),
|
||||
...["location[directory]", "cursor", PTY_CONNECT_TICKET_QUERY].map((name) => ({
|
||||
in: "query",
|
||||
name,
|
||||
schema: { type: "string" },
|
||||
})),
|
||||
],
|
||||
}),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.post("pty.create", "/api/pty", {
|
||||
query: LocationQuery,
|
||||
payload: Pty.CreateInput,
|
||||
success: Location.response(Pty.Info),
|
||||
})
|
||||
.annotateMerge(locationQueryOpenApi)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "pty.create",
|
||||
summary: "Create PTY session",
|
||||
description: "Create a pseudo-terminal session for a location.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.get("pty.get", "/api/pty/:ptyID", {
|
||||
params: { ptyID: Pty.ID },
|
||||
query: LocationQuery,
|
||||
success: Location.response(Pty.Info),
|
||||
error: PtyNotFoundError,
|
||||
})
|
||||
.annotateMerge(locationQueryOpenApi)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "pty.get",
|
||||
summary: "Get PTY session",
|
||||
description: "Get one PTY session, including its exit code once exited.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.put("pty.update", "/api/pty/:ptyID", {
|
||||
params: { ptyID: Pty.ID },
|
||||
query: LocationQuery,
|
||||
payload: Pty.UpdateInput,
|
||||
success: Location.response(Pty.Info),
|
||||
error: PtyNotFoundError,
|
||||
})
|
||||
.annotateMerge(locationQueryOpenApi)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "pty.update",
|
||||
summary: "Update PTY session",
|
||||
description: "Update the title or viewport size of one PTY session.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.delete("pty.remove", "/api/pty/:ptyID", {
|
||||
params: { ptyID: Pty.ID },
|
||||
query: LocationQuery,
|
||||
success: HttpApiSchema.NoContent,
|
||||
error: PtyNotFoundError,
|
||||
})
|
||||
.annotateMerge(locationQueryOpenApi)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "pty.remove",
|
||||
summary: "Remove PTY session",
|
||||
description: "Terminate and remove one PTY session.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.post("pty.connectToken", "/api/pty/:ptyID/connect-token", {
|
||||
params: { ptyID: Pty.ID },
|
||||
query: LocationQuery,
|
||||
headers: Schema.Struct({ [PTY_CONNECT_TOKEN_HEADER]: Schema.optional(Schema.String) }),
|
||||
success: Location.response(PtyTicket.ConnectToken),
|
||||
error: [ForbiddenError, PtyNotFoundError],
|
||||
})
|
||||
.annotateMerge(locationQueryOpenApi)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "pty.connect.token",
|
||||
summary: "Create PTY WebSocket token",
|
||||
description: "Create a short-lived single-use ticket for opening a PTY WebSocket connection.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
// Query fields are decoded in the raw handler after the existence check so a missing
|
||||
// session responds with an empty 404 before any upgrade work.
|
||||
HttpApiEndpoint.get("pty.connect", "/api/pty/:ptyID/connect", {
|
||||
params: { ptyID: Pty.ID },
|
||||
success: Schema.Boolean,
|
||||
error: [ForbiddenError, PtyNotFoundError],
|
||||
}).annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "pty.connect",
|
||||
summary: "Connect to PTY session",
|
||||
description: "Establish a WebSocket connection streaming PTY output and accepting terminal input.",
|
||||
transform: (operation) => ({
|
||||
...operation,
|
||||
"x-websocket": true,
|
||||
parameters: [
|
||||
...(operation.parameters ?? []),
|
||||
...["location[directory]", "cursor", PTY_CONNECT_TICKET_QUERY].map((name) => ({
|
||||
in: "query",
|
||||
name,
|
||||
schema: { type: "string" },
|
||||
})),
|
||||
],
|
||||
}),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.annotateMerge(OpenApi.annotations({ title: "pty", description: "Experimental location-scoped PTY routes." }))
|
||||
)
|
||||
.annotateMerge(OpenApi.annotations({ title: "pty", description: "Experimental location-scoped PTY routes." }))
|
||||
@@ -56,13 +56,6 @@ const ParentIDFilter = Schema.Union([
|
||||
description: "Filter by parent session. Use null to return only root sessions.",
|
||||
})
|
||||
|
||||
const BooleanFromString = Schema.Literals(["true", "false"]).pipe(
|
||||
Schema.decodeTo(Schema.Boolean, {
|
||||
decode: SchemaGetter.transform((value) => value === "true"),
|
||||
encode: SchemaGetter.transform((value): "true" | "false" => (value ? "true" : "false")),
|
||||
}),
|
||||
)
|
||||
|
||||
const SessionsQueryFields = {
|
||||
limit: Schema.NumberFromString.pipe(Schema.decodeTo(PositiveInt), Schema.optional).annotate({
|
||||
description: "Maximum number of sessions to return. Defaults to the newest 50 sessions.",
|
||||
@@ -72,10 +65,6 @@ const SessionsQueryFields = {
|
||||
}),
|
||||
search: Schema.optional(Schema.String),
|
||||
parentID: ParentIDFilter.pipe(Schema.optional),
|
||||
archived: BooleanFromString.pipe(Schema.optional).annotate({
|
||||
description:
|
||||
"Filter by archive state. Use true to return only archived sessions or false to exclude them. Omit to include both.",
|
||||
}),
|
||||
}
|
||||
|
||||
const SessionsDirectoryQuery = Schema.Struct({
|
||||
@@ -163,6 +152,13 @@ const FormCreatePayload = Schema.Struct({
|
||||
fields: Form.Info.fields.fields,
|
||||
}).annotate({ identifier: "Form.CreatePayload" })
|
||||
|
||||
const BooleanFromString = Schema.Literals(["true", "false"]).pipe(
|
||||
Schema.decodeTo(Schema.Boolean, {
|
||||
decode: SchemaGetter.transform((value) => value === "true"),
|
||||
encode: SchemaGetter.transform((value): "true" | "false" => (value ? "true" : "false")),
|
||||
}),
|
||||
)
|
||||
|
||||
const SessionsQueryCursor = SessionsCursor.annotate({
|
||||
description: "Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response.",
|
||||
})
|
||||
@@ -367,9 +363,6 @@ export const makeSessionGroup = <I extends HttpApiMiddleware.AnyId, S, FormI ext
|
||||
title: Schema.String.pipe(Schema.optional),
|
||||
metadata: Session.Metadata.pipe(Schema.optional),
|
||||
permissions: Permission.Ruleset.pipe(Schema.optional),
|
||||
archived: Schema.Boolean.pipe(Schema.optional).annotate({
|
||||
description: "Archive the session with true or restore it with false. Repeating the current state is a no-op.",
|
||||
}),
|
||||
}),
|
||||
success: HttpApiSchema.NoContent,
|
||||
error: SessionNotFoundError,
|
||||
|
||||
@@ -6,7 +6,7 @@ export const Effect = Schema.Literals(["allow", "deny"])
|
||||
export type Effect = typeof Effect.Type
|
||||
|
||||
export const Info = Schema.Struct({
|
||||
action: Schema.Literals(["provider.use", "permission"]),
|
||||
action: Schema.Literals(["provider.use", "tool.use", "integration.use"]),
|
||||
resource: Schema.String,
|
||||
effect: Effect,
|
||||
})
|
||||
|
||||
@@ -38,13 +38,22 @@ export const KeyMethod = Schema.Struct({
|
||||
form: optional(Form.Fields),
|
||||
}).annotate({ identifier: "Integration.KeyMethod" })
|
||||
|
||||
/** Saves a reference to credentials managed outside opencode, configured by the form answers. */
|
||||
export interface ExternalMethod extends Schema.Schema.Type<typeof ExternalMethod> {}
|
||||
export const ExternalMethod = Schema.Struct({
|
||||
id: MethodID,
|
||||
type: Schema.Literal("external"),
|
||||
label: Schema.String,
|
||||
form: optional(Form.Fields),
|
||||
}).annotate({ identifier: "Integration.ExternalMethod" })
|
||||
|
||||
export interface EnvMethod extends Schema.Schema.Type<typeof EnvMethod> {}
|
||||
export const EnvMethod = Schema.Struct({
|
||||
type: Schema.Literal("env"),
|
||||
names: Schema.Array(Schema.String),
|
||||
}).annotate({ identifier: "Integration.EnvMethod" })
|
||||
|
||||
export const Method = Schema.Union([OAuthMethod, CommandMethod, KeyMethod, EnvMethod])
|
||||
export const Method = Schema.Union([OAuthMethod, CommandMethod, KeyMethod, ExternalMethod, EnvMethod])
|
||||
.pipe(Schema.toTaggedUnion("type"))
|
||||
.annotate({ identifier: "Integration.Method" })
|
||||
export type Method = typeof Method.Type
|
||||
|
||||
@@ -139,20 +139,6 @@ export const Viewed = Event.durable({
|
||||
})
|
||||
export type Viewed = typeof Viewed.Type
|
||||
|
||||
export const Archived = Event.durable({
|
||||
type: "session.archived",
|
||||
...options,
|
||||
schema: Base,
|
||||
})
|
||||
export type Archived = typeof Archived.Type
|
||||
|
||||
export const Unarchived = Event.durable({
|
||||
type: "session.unarchived",
|
||||
...options,
|
||||
schema: Base,
|
||||
})
|
||||
export type Unarchived = typeof Unarchived.Type
|
||||
|
||||
// Replay-only: older releases allowed replacing completed assistant content.
|
||||
export const MessageContentUpdated = Event.durable({
|
||||
type: "session.message.content.updated",
|
||||
@@ -672,8 +658,6 @@ export const Definitions = Event.inventory(
|
||||
MetadataUpdated,
|
||||
Permissions,
|
||||
Viewed,
|
||||
Archived,
|
||||
Unarchived,
|
||||
UsageUpdated,
|
||||
Deleted,
|
||||
Forked,
|
||||
|
||||
@@ -10,6 +10,25 @@ import { AbsolutePath } from "../src/schema.js"
|
||||
import { WebSearch } from "../src/websearch.js"
|
||||
|
||||
describe("Config.Entry", () => {
|
||||
test("round-trips tool.use and rejects unsupported action spellings", () => {
|
||||
const input = {
|
||||
experimental: {
|
||||
policies: [
|
||||
{ action: "tool.use", resource: "shell:*", effect: "deny" },
|
||||
{ action: "tool.use", resource: "shell:git *", effect: "allow" },
|
||||
],
|
||||
},
|
||||
} as const
|
||||
const decoded = Schema.decodeUnknownSync(Config.Info)(input)
|
||||
expect(Schema.encodeSync(Config.Info)(decoded)).toEqual(input)
|
||||
for (const action of ["permission", "tool.execute"])
|
||||
expect(() =>
|
||||
Schema.decodeUnknownSync(Config.Info)({
|
||||
experimental: { policies: [{ action, resource: "*", effect: "deny" }] },
|
||||
}),
|
||||
).toThrow()
|
||||
})
|
||||
|
||||
test("accepts directory-only worktree config and omits it when absent", () => {
|
||||
const decode = Schema.decodeUnknownSync(Config.Info)
|
||||
const input = { worktree: { directory: "../worktrees" } }
|
||||
|
||||
@@ -111,8 +111,6 @@ describe("public event manifest", () => {
|
||||
"session.metadata.updated.1",
|
||||
"session.permissions.1",
|
||||
"session.viewed.1",
|
||||
"session.archived.1",
|
||||
"session.unarchived.1",
|
||||
"session.message.content.updated.1",
|
||||
"session.usage.recorded.1",
|
||||
"session.forked.2",
|
||||
|
||||
@@ -84,6 +84,26 @@ export const IntegrationHandler = HttpApiBuilder.group(Api, "server.integration"
|
||||
return HttpApiSchema.NoContent.make()
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"integration.connect.external",
|
||||
Effect.fn(function* (ctx) {
|
||||
const service = yield* Integration.Service
|
||||
if (!(yield* service.get(ctx.params.integrationID)))
|
||||
return yield* new IntegrationNotFoundError({
|
||||
integrationID: ctx.params.integrationID,
|
||||
message: `Integration not found: ${ctx.params.integrationID}`,
|
||||
})
|
||||
yield* authorize(
|
||||
service.connection.external({
|
||||
integrationID: ctx.params.integrationID,
|
||||
methodID: ctx.payload.methodID,
|
||||
answer: ctx.payload.answer,
|
||||
label: ctx.payload.label,
|
||||
}),
|
||||
)
|
||||
return HttpApiSchema.NoContent.make()
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"integration.oauth.connect",
|
||||
Effect.fn(function* (ctx) {
|
||||
|
||||
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user